scm.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """SCM-specific utility classes."""
  5. import distutils.version
  6. import glob
  7. import io
  8. import os
  9. import platform
  10. import re
  11. import sys
  12. import gclient_utils
  13. import subprocess2
  14. def ValidateEmail(email):
  15. return (
  16. re.match(r"^[a-zA-Z0-9._%\-+]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}$", email)
  17. is not None)
  18. def GetCasedPath(path):
  19. """Elcheapos way to get the real path case on Windows."""
  20. if sys.platform.startswith('win') and os.path.exists(path):
  21. # Reconstruct the path.
  22. path = os.path.abspath(path)
  23. paths = path.split('\\')
  24. for i in range(len(paths)):
  25. if i == 0:
  26. # Skip drive letter.
  27. continue
  28. subpath = '\\'.join(paths[:i+1])
  29. prev = len('\\'.join(paths[:i]))
  30. # glob.glob will return the cased path for the last item only. This is why
  31. # we are calling it in a loop. Extract the data we want and put it back
  32. # into the list.
  33. paths[i] = glob.glob(subpath + '*')[0][prev+1:len(subpath)]
  34. path = '\\'.join(paths)
  35. return path
  36. def GenFakeDiff(filename):
  37. """Generates a fake diff from a file."""
  38. file_content = gclient_utils.FileRead(filename, 'rb').splitlines(True)
  39. filename = filename.replace(os.sep, '/')
  40. nb_lines = len(file_content)
  41. # We need to use / since patch on unix will fail otherwise.
  42. data = io.StringIO()
  43. data.write("Index: %s\n" % filename)
  44. data.write('=' * 67 + '\n')
  45. # Note: Should we use /dev/null instead?
  46. data.write("--- %s\n" % filename)
  47. data.write("+++ %s\n" % filename)
  48. data.write("@@ -0,0 +1,%d @@\n" % nb_lines)
  49. # Prepend '+' to every lines.
  50. for line in file_content:
  51. data.write('+')
  52. data.write(line)
  53. result = data.getvalue()
  54. data.close()
  55. return result
  56. def determine_scm(root):
  57. """Similar to upload.py's version but much simpler.
  58. Returns 'git' or None.
  59. """
  60. if os.path.isdir(os.path.join(root, '.git')):
  61. return 'git'
  62. try:
  63. subprocess2.check_call(
  64. ['git', 'rev-parse', '--show-cdup'],
  65. stdout=subprocess2.DEVNULL,
  66. stderr=subprocess2.DEVNULL,
  67. cwd=root)
  68. return 'git'
  69. except (OSError, subprocess2.CalledProcessError):
  70. return None
  71. def only_int(val):
  72. if val.isdigit():
  73. return int(val)
  74. return 0
  75. class GIT(object):
  76. current_version = None
  77. @staticmethod
  78. def ApplyEnvVars(kwargs):
  79. env = kwargs.pop('env', None) or os.environ.copy()
  80. # Don't prompt for passwords; just fail quickly and noisily.
  81. # By default, git will use an interactive terminal prompt when a username/
  82. # password is needed. That shouldn't happen in the chromium workflow,
  83. # and if it does, then gclient may hide the prompt in the midst of a flood
  84. # of terminal spew. The only indication that something has gone wrong
  85. # will be when gclient hangs unresponsively. Instead, we disable the
  86. # password prompt and simply allow git to fail noisily. The error
  87. # message produced by git will be copied to gclient's output.
  88. env.setdefault('GIT_ASKPASS', 'true')
  89. env.setdefault('SSH_ASKPASS', 'true')
  90. # 'cat' is a magical git string that disables pagers on all platforms.
  91. env.setdefault('GIT_PAGER', 'cat')
  92. return env
  93. @staticmethod
  94. def Capture(args, cwd=None, strip_out=True, **kwargs):
  95. env = GIT.ApplyEnvVars(kwargs)
  96. output = subprocess2.check_output(
  97. ['git'] + args, cwd=cwd, stderr=subprocess2.PIPE, env=env, **kwargs)
  98. output = output.decode('utf-8', 'replace')
  99. return output.strip() if strip_out else output
  100. @staticmethod
  101. def CaptureStatus(cwd, upstream_branch):
  102. """Returns git status.
  103. Returns an array of (status, file) tuples."""
  104. if upstream_branch is None:
  105. upstream_branch = GIT.GetUpstreamBranch(cwd)
  106. if upstream_branch is None:
  107. raise gclient_utils.Error('Cannot determine upstream branch')
  108. command = ['-c', 'core.quotePath=false', 'diff',
  109. '--name-status', '--no-renames', '-r', '%s...' % upstream_branch]
  110. status = GIT.Capture(command, cwd)
  111. results = []
  112. if status:
  113. for statusline in status.splitlines():
  114. # 3-way merges can cause the status can be 'MMM' instead of 'M'. This
  115. # can happen when the user has 2 local branches and he diffs between
  116. # these 2 branches instead diffing to upstream.
  117. m = re.match(r'^(\w)+\t(.+)$', statusline)
  118. if not m:
  119. raise gclient_utils.Error(
  120. 'status currently unsupported: %s' % statusline)
  121. # Only grab the first letter.
  122. results.append(('%s ' % m.group(1)[0], m.group(2)))
  123. return results
  124. @staticmethod
  125. def GetConfig(cwd, key, default=None):
  126. try:
  127. return GIT.Capture(['config', key], cwd=cwd)
  128. except subprocess2.CalledProcessError:
  129. return default
  130. @staticmethod
  131. def GetBranchConfig(cwd, branch, key, default=None):
  132. assert branch, 'A branch must be given'
  133. key = 'branch.%s.%s' % (branch, key)
  134. return GIT.GetConfig(cwd, key, default)
  135. @staticmethod
  136. def SetConfig(cwd, key, value=None):
  137. if value is None:
  138. args = ['config', '--unset', key]
  139. else:
  140. args = ['config', key, value]
  141. GIT.Capture(args, cwd=cwd)
  142. @staticmethod
  143. def SetBranchConfig(cwd, branch, key, value=None):
  144. assert branch, 'A branch must be given'
  145. key = 'branch.%s.%s' % (branch, key)
  146. GIT.SetConfig(cwd, key, value)
  147. @staticmethod
  148. def IsWorkTreeDirty(cwd):
  149. return GIT.Capture(['status', '-s'], cwd=cwd) != ''
  150. @staticmethod
  151. def GetEmail(cwd):
  152. """Retrieves the user email address if known."""
  153. return GIT.GetConfig(cwd, 'user.email', '')
  154. @staticmethod
  155. def ShortBranchName(branch):
  156. """Converts a name like 'refs/heads/foo' to just 'foo'."""
  157. return branch.replace('refs/heads/', '')
  158. @staticmethod
  159. def GetBranchRef(cwd):
  160. """Returns the full branch reference, e.g. 'refs/heads/main'."""
  161. try:
  162. return GIT.Capture(['symbolic-ref', 'HEAD'], cwd=cwd)
  163. except subprocess2.CalledProcessError:
  164. return None
  165. @staticmethod
  166. def GetRemoteHeadRef(cwd, url, remote):
  167. """Returns the full default remote branch reference, e.g.
  168. 'refs/remotes/origin/main'."""
  169. if os.path.exists(cwd):
  170. try:
  171. # Try using local git copy first
  172. ref = 'refs/remotes/%s/HEAD' % remote
  173. ref = GIT.Capture(['symbolic-ref', ref], cwd=cwd)
  174. if not ref.endswith('master'):
  175. return ref
  176. # Check if there are changes in the default branch for this particular
  177. # repository.
  178. GIT.Capture(['remote', 'set-head', '-a', remote], cwd=cwd)
  179. return GIT.Capture(['symbolic-ref', ref], cwd=cwd)
  180. except subprocess2.CalledProcessError:
  181. pass
  182. try:
  183. # Fetch information from git server
  184. resp = GIT.Capture(['ls-remote', '--symref', url, 'HEAD'])
  185. regex = r'^ref: (.*)\tHEAD$'
  186. for line in resp.split('\n'):
  187. m = re.match(regex, line)
  188. if m:
  189. return ''.join(GIT.RefToRemoteRef(m.group(1), remote))
  190. except subprocess2.CalledProcessError:
  191. pass
  192. # Return default branch
  193. return 'refs/remotes/%s/main' % remote
  194. @staticmethod
  195. def GetBranch(cwd):
  196. """Returns the short branch name, e.g. 'main'."""
  197. branchref = GIT.GetBranchRef(cwd)
  198. if branchref:
  199. return GIT.ShortBranchName(branchref)
  200. return None
  201. @staticmethod
  202. def GetRemoteBranches(cwd):
  203. return GIT.Capture(['branch', '-r'], cwd=cwd).split()
  204. @staticmethod
  205. def FetchUpstreamTuple(cwd, branch=None):
  206. """Returns a tuple containing remote and remote ref,
  207. e.g. 'origin', 'refs/heads/main'
  208. """
  209. try:
  210. branch = branch or GIT.GetBranch(cwd)
  211. except subprocess2.CalledProcessError:
  212. pass
  213. if branch:
  214. upstream_branch = GIT.GetBranchConfig(cwd, branch, 'merge')
  215. if upstream_branch:
  216. remote = GIT.GetBranchConfig(cwd, branch, 'remote', '.')
  217. return remote, upstream_branch
  218. upstream_branch = GIT.GetConfig(cwd, 'rietveld.upstream-branch')
  219. if upstream_branch:
  220. remote = GIT.GetConfig(cwd, 'rietveld.upstream-remote', '.')
  221. return remote, upstream_branch
  222. # Else, try to guess the origin remote.
  223. remote_branches = GIT.GetRemoteBranches(cwd)
  224. if 'origin/main' in remote_branches:
  225. # Fall back on origin/main if it exits.
  226. return 'origin', 'refs/heads/main'
  227. if 'origin/master' in remote_branches:
  228. # Fall back on origin/master if it exits.
  229. return 'origin', 'refs/heads/master'
  230. return None, None
  231. @staticmethod
  232. def RefToRemoteRef(ref, remote):
  233. """Convert a checkout ref to the equivalent remote ref.
  234. Returns:
  235. A tuple of the remote ref's (common prefix, unique suffix), or None if it
  236. doesn't appear to refer to a remote ref (e.g. it's a commit hash).
  237. """
  238. # TODO(mmoss): This is just a brute-force mapping based of the expected git
  239. # config. It's a bit better than the even more brute-force replace('heads',
  240. # ...), but could still be smarter (like maybe actually using values gleaned
  241. # from the git config).
  242. m = re.match('^(refs/(remotes/)?)?branch-heads/', ref or '')
  243. if m:
  244. return ('refs/remotes/branch-heads/', ref.replace(m.group(0), ''))
  245. m = re.match('^((refs/)?remotes/)?%s/|(refs/)?heads/' % remote, ref or '')
  246. if m:
  247. return ('refs/remotes/%s/' % remote, ref.replace(m.group(0), ''))
  248. return None
  249. @staticmethod
  250. def RemoteRefToRef(ref, remote):
  251. assert remote, 'A remote must be given'
  252. if not ref or not ref.startswith('refs/'):
  253. return None
  254. if not ref.startswith('refs/remotes/'):
  255. return ref
  256. if ref.startswith('refs/remotes/branch-heads/'):
  257. return 'refs' + ref[len('refs/remotes'):]
  258. if ref.startswith('refs/remotes/%s/' % remote):
  259. return 'refs/heads' + ref[len('refs/remotes/%s' % remote):]
  260. return None
  261. @staticmethod
  262. def GetUpstreamBranch(cwd):
  263. """Gets the current branch's upstream branch."""
  264. remote, upstream_branch = GIT.FetchUpstreamTuple(cwd)
  265. if remote != '.' and upstream_branch:
  266. remote_ref = GIT.RefToRemoteRef(upstream_branch, remote)
  267. if remote_ref:
  268. upstream_branch = ''.join(remote_ref)
  269. return upstream_branch
  270. @staticmethod
  271. def IsAncestor(cwd, maybe_ancestor, ref):
  272. """Verifies if |maybe_ancestor| is an ancestor of |ref|."""
  273. try:
  274. GIT.Capture(['merge-base', '--is-ancestor', maybe_ancestor, ref], cwd=cwd)
  275. return True
  276. except subprocess2.CalledProcessError:
  277. return False
  278. @staticmethod
  279. def GetOldContents(cwd, filename, branch=None):
  280. if not branch:
  281. branch = GIT.GetUpstreamBranch(cwd)
  282. if platform.system() == 'Windows':
  283. # git show <sha>:<path> wants a posix path.
  284. filename = filename.replace('\\', '/')
  285. command = ['show', '%s:%s' % (branch, filename)]
  286. try:
  287. return GIT.Capture(command, cwd=cwd, strip_out=False)
  288. except subprocess2.CalledProcessError:
  289. return ''
  290. @staticmethod
  291. def GenerateDiff(cwd, branch=None, branch_head='HEAD', full_move=False,
  292. files=None):
  293. """Diffs against the upstream branch or optionally another branch.
  294. full_move means that move or copy operations should completely recreate the
  295. files, usually in the prospect to apply the patch for a try job."""
  296. if not branch:
  297. branch = GIT.GetUpstreamBranch(cwd)
  298. command = ['-c', 'core.quotePath=false', 'diff',
  299. '-p', '--no-color', '--no-prefix', '--no-ext-diff',
  300. branch + "..." + branch_head]
  301. if full_move:
  302. command.append('--no-renames')
  303. else:
  304. command.append('-C')
  305. # TODO(maruel): --binary support.
  306. if files:
  307. command.append('--')
  308. command.extend(files)
  309. diff = GIT.Capture(command, cwd=cwd, strip_out=False).splitlines(True)
  310. for i in range(len(diff)):
  311. # In the case of added files, replace /dev/null with the path to the
  312. # file being added.
  313. if diff[i].startswith('--- /dev/null'):
  314. diff[i] = '--- %s' % diff[i+1][4:]
  315. return ''.join(diff)
  316. @staticmethod
  317. def GetDifferentFiles(cwd, branch=None, branch_head='HEAD'):
  318. """Returns the list of modified files between two branches."""
  319. if not branch:
  320. branch = GIT.GetUpstreamBranch(cwd)
  321. command = ['-c', 'core.quotePath=false', 'diff',
  322. '--name-only', branch + "..." + branch_head]
  323. return GIT.Capture(command, cwd=cwd).splitlines(False)
  324. @staticmethod
  325. def GetAllFiles(cwd):
  326. """Returns the list of all files under revision control."""
  327. command = ['-c', 'core.quotePath=false', 'ls-files', '--', '.']
  328. return GIT.Capture(command, cwd=cwd).splitlines(False)
  329. @staticmethod
  330. def GetPatchName(cwd):
  331. """Constructs a name for this patch."""
  332. short_sha = GIT.Capture(['rev-parse', '--short=4', 'HEAD'], cwd=cwd)
  333. return "%s#%s" % (GIT.GetBranch(cwd), short_sha)
  334. @staticmethod
  335. def GetCheckoutRoot(cwd):
  336. """Returns the top level directory of a git checkout as an absolute path.
  337. """
  338. root = GIT.Capture(['rev-parse', '--show-cdup'], cwd=cwd)
  339. return os.path.abspath(os.path.join(cwd, root))
  340. @staticmethod
  341. def GetGitDir(cwd):
  342. return os.path.abspath(GIT.Capture(['rev-parse', '--git-dir'], cwd=cwd))
  343. @staticmethod
  344. def IsInsideWorkTree(cwd):
  345. try:
  346. return GIT.Capture(['rev-parse', '--is-inside-work-tree'], cwd=cwd)
  347. except (OSError, subprocess2.CalledProcessError):
  348. return False
  349. @staticmethod
  350. def IsDirectoryVersioned(cwd, relative_dir):
  351. """Checks whether the given |relative_dir| is part of cwd's repo."""
  352. return bool(GIT.Capture(['ls-tree', 'HEAD', relative_dir], cwd=cwd))
  353. @staticmethod
  354. def CleanupDir(cwd, relative_dir):
  355. """Cleans up untracked file inside |relative_dir|."""
  356. return bool(GIT.Capture(['clean', '-df', relative_dir], cwd=cwd))
  357. @staticmethod
  358. def ResolveCommit(cwd, rev):
  359. # We do this instead of rev-parse --verify rev^{commit}, since on Windows
  360. # git can be either an executable or batch script, each of which requires
  361. # escaping the caret (^) a different way.
  362. if gclient_utils.IsFullGitSha(rev):
  363. # git-rev parse --verify FULL_GIT_SHA always succeeds, even if we don't
  364. # have FULL_GIT_SHA locally. Removing the last character forces git to
  365. # check if FULL_GIT_SHA refers to an object in the local database.
  366. rev = rev[:-1]
  367. try:
  368. return GIT.Capture(['rev-parse', '--quiet', '--verify', rev], cwd=cwd)
  369. except subprocess2.CalledProcessError:
  370. return None
  371. @staticmethod
  372. def IsValidRevision(cwd, rev, sha_only=False):
  373. """Verifies the revision is a proper git revision.
  374. sha_only: Fail unless rev is a sha hash.
  375. """
  376. sha = GIT.ResolveCommit(cwd, rev)
  377. if sha is None:
  378. return False
  379. if sha_only:
  380. return sha == rev.lower()
  381. return True
  382. @classmethod
  383. def AssertVersion(cls, min_version):
  384. """Asserts git's version is at least min_version."""
  385. if cls.current_version is None:
  386. current_version = cls.Capture(['--version'], '.')
  387. matched = re.search(r'git version (.+)', current_version)
  388. cls.current_version = distutils.version.LooseVersion(matched.group(1))
  389. min_version = distutils.version.LooseVersion(min_version)
  390. return (min_version <= cls.current_version, cls.current_version)