scm.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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, end_commit=None):
  102. # type: (str, str, Optional[str]) -> Sequence[Tuple[str, str]]
  103. """Returns git status.
  104. Returns an array of (status, file) tuples."""
  105. if end_commit is None:
  106. end_commit = ''
  107. if upstream_branch is None:
  108. upstream_branch = GIT.GetUpstreamBranch(cwd)
  109. if upstream_branch is None:
  110. raise gclient_utils.Error('Cannot determine upstream branch')
  111. command = [
  112. '-c', 'core.quotePath=false', 'diff', '--name-status', '--no-renames',
  113. '-r',
  114. '%s...%s' % (upstream_branch, end_commit)
  115. ]
  116. status = GIT.Capture(command, cwd)
  117. results = []
  118. if status:
  119. for statusline in status.splitlines():
  120. # 3-way merges can cause the status can be 'MMM' instead of 'M'. This
  121. # can happen when the user has 2 local branches and he diffs between
  122. # these 2 branches instead diffing to upstream.
  123. m = re.match(r'^(\w)+\t(.+)$', statusline)
  124. if not m:
  125. raise gclient_utils.Error(
  126. 'status currently unsupported: %s' % statusline)
  127. # Only grab the first letter.
  128. results.append(('%s ' % m.group(1)[0], m.group(2)))
  129. return results
  130. @staticmethod
  131. def GetConfig(cwd, key, default=None):
  132. try:
  133. return GIT.Capture(['config', key], cwd=cwd)
  134. except subprocess2.CalledProcessError:
  135. return default
  136. @staticmethod
  137. def GetBranchConfig(cwd, branch, key, default=None):
  138. assert branch, 'A branch must be given'
  139. key = 'branch.%s.%s' % (branch, key)
  140. return GIT.GetConfig(cwd, key, default)
  141. @staticmethod
  142. def SetConfig(cwd, key, value=None):
  143. if value is None:
  144. args = ['config', '--unset', key]
  145. else:
  146. args = ['config', key, value]
  147. GIT.Capture(args, cwd=cwd)
  148. @staticmethod
  149. def SetBranchConfig(cwd, branch, key, value=None):
  150. assert branch, 'A branch must be given'
  151. key = 'branch.%s.%s' % (branch, key)
  152. GIT.SetConfig(cwd, key, value)
  153. @staticmethod
  154. def IsWorkTreeDirty(cwd):
  155. return GIT.Capture(['status', '-s'], cwd=cwd) != ''
  156. @staticmethod
  157. def GetEmail(cwd):
  158. """Retrieves the user email address if known."""
  159. return GIT.GetConfig(cwd, 'user.email', '')
  160. @staticmethod
  161. def ShortBranchName(branch):
  162. """Converts a name like 'refs/heads/foo' to just 'foo'."""
  163. return branch.replace('refs/heads/', '')
  164. @staticmethod
  165. def GetBranchRef(cwd):
  166. """Returns the full branch reference, e.g. 'refs/heads/main'."""
  167. try:
  168. return GIT.Capture(['symbolic-ref', 'HEAD'], cwd=cwd)
  169. except subprocess2.CalledProcessError:
  170. return None
  171. @staticmethod
  172. def GetRemoteHeadRef(cwd, url, remote):
  173. """Returns the full default remote branch reference, e.g.
  174. 'refs/remotes/origin/main'."""
  175. if os.path.exists(cwd):
  176. try:
  177. # Try using local git copy first
  178. ref = 'refs/remotes/%s/HEAD' % remote
  179. ref = GIT.Capture(['symbolic-ref', ref], cwd=cwd)
  180. if not ref.endswith('master'):
  181. return ref
  182. # Check if there are changes in the default branch for this particular
  183. # repository.
  184. GIT.Capture(['remote', 'set-head', '-a', remote], cwd=cwd)
  185. return GIT.Capture(['symbolic-ref', ref], cwd=cwd)
  186. except subprocess2.CalledProcessError:
  187. pass
  188. try:
  189. # Fetch information from git server
  190. resp = GIT.Capture(['ls-remote', '--symref', url, 'HEAD'])
  191. regex = r'^ref: (.*)\tHEAD$'
  192. for line in resp.split('\n'):
  193. m = re.match(regex, line)
  194. if m:
  195. return ''.join(GIT.RefToRemoteRef(m.group(1), remote))
  196. except subprocess2.CalledProcessError:
  197. pass
  198. # Return default branch
  199. return 'refs/remotes/%s/main' % remote
  200. @staticmethod
  201. def GetBranch(cwd):
  202. """Returns the short branch name, e.g. 'main'."""
  203. branchref = GIT.GetBranchRef(cwd)
  204. if branchref:
  205. return GIT.ShortBranchName(branchref)
  206. return None
  207. @staticmethod
  208. def GetRemoteBranches(cwd):
  209. return GIT.Capture(['branch', '-r'], cwd=cwd).split()
  210. @staticmethod
  211. def FetchUpstreamTuple(cwd, branch=None):
  212. """Returns a tuple containing remote and remote ref,
  213. e.g. 'origin', 'refs/heads/main'
  214. """
  215. try:
  216. branch = branch or GIT.GetBranch(cwd)
  217. except subprocess2.CalledProcessError:
  218. pass
  219. if branch:
  220. upstream_branch = GIT.GetBranchConfig(cwd, branch, 'merge')
  221. if upstream_branch:
  222. remote = GIT.GetBranchConfig(cwd, branch, 'remote', '.')
  223. return remote, upstream_branch
  224. upstream_branch = GIT.GetConfig(cwd, 'rietveld.upstream-branch')
  225. if upstream_branch:
  226. remote = GIT.GetConfig(cwd, 'rietveld.upstream-remote', '.')
  227. return remote, upstream_branch
  228. # Else, try to guess the origin remote.
  229. remote_branches = GIT.GetRemoteBranches(cwd)
  230. if 'origin/main' in remote_branches:
  231. # Fall back on origin/main if it exits.
  232. return 'origin', 'refs/heads/main'
  233. if 'origin/master' in remote_branches:
  234. # Fall back on origin/master if it exits.
  235. return 'origin', 'refs/heads/master'
  236. return None, None
  237. @staticmethod
  238. def RefToRemoteRef(ref, remote):
  239. """Convert a checkout ref to the equivalent remote ref.
  240. Returns:
  241. A tuple of the remote ref's (common prefix, unique suffix), or None if it
  242. doesn't appear to refer to a remote ref (e.g. it's a commit hash).
  243. """
  244. # TODO(mmoss): This is just a brute-force mapping based of the expected git
  245. # config. It's a bit better than the even more brute-force replace('heads',
  246. # ...), but could still be smarter (like maybe actually using values gleaned
  247. # from the git config).
  248. m = re.match('^(refs/(remotes/)?)?branch-heads/', ref or '')
  249. if m:
  250. return ('refs/remotes/branch-heads/', ref.replace(m.group(0), ''))
  251. m = re.match('^((refs/)?remotes/)?%s/|(refs/)?heads/' % remote, ref or '')
  252. if m:
  253. return ('refs/remotes/%s/' % remote, ref.replace(m.group(0), ''))
  254. return None
  255. @staticmethod
  256. def RemoteRefToRef(ref, remote):
  257. assert remote, 'A remote must be given'
  258. if not ref or not ref.startswith('refs/'):
  259. return None
  260. if not ref.startswith('refs/remotes/'):
  261. return ref
  262. if ref.startswith('refs/remotes/branch-heads/'):
  263. return 'refs' + ref[len('refs/remotes'):]
  264. if ref.startswith('refs/remotes/%s/' % remote):
  265. return 'refs/heads' + ref[len('refs/remotes/%s' % remote):]
  266. return None
  267. @staticmethod
  268. def GetUpstreamBranch(cwd):
  269. """Gets the current branch's upstream branch."""
  270. remote, upstream_branch = GIT.FetchUpstreamTuple(cwd)
  271. if remote != '.' and upstream_branch:
  272. remote_ref = GIT.RefToRemoteRef(upstream_branch, remote)
  273. if remote_ref:
  274. upstream_branch = ''.join(remote_ref)
  275. return upstream_branch
  276. @staticmethod
  277. def IsAncestor(maybe_ancestor, ref, cwd=None):
  278. # type: (string, string, Optional[string]) -> bool
  279. """Verifies if |maybe_ancestor| is an ancestor of |ref|."""
  280. try:
  281. GIT.Capture(['merge-base', '--is-ancestor', maybe_ancestor, ref], cwd=cwd)
  282. return True
  283. except subprocess2.CalledProcessError:
  284. return False
  285. @staticmethod
  286. def GetOldContents(cwd, filename, branch=None):
  287. if not branch:
  288. branch = GIT.GetUpstreamBranch(cwd)
  289. if platform.system() == 'Windows':
  290. # git show <sha>:<path> wants a posix path.
  291. filename = filename.replace('\\', '/')
  292. command = ['show', '%s:%s' % (branch, filename)]
  293. try:
  294. return GIT.Capture(command, cwd=cwd, strip_out=False)
  295. except subprocess2.CalledProcessError:
  296. return ''
  297. @staticmethod
  298. def GenerateDiff(cwd, branch=None, branch_head='HEAD', full_move=False,
  299. files=None):
  300. """Diffs against the upstream branch or optionally another branch.
  301. full_move means that move or copy operations should completely recreate the
  302. files, usually in the prospect to apply the patch for a try job."""
  303. if not branch:
  304. branch = GIT.GetUpstreamBranch(cwd)
  305. command = ['-c', 'core.quotePath=false', 'diff',
  306. '-p', '--no-color', '--no-prefix', '--no-ext-diff',
  307. branch + "..." + branch_head]
  308. if full_move:
  309. command.append('--no-renames')
  310. else:
  311. command.append('-C')
  312. # TODO(maruel): --binary support.
  313. if files:
  314. command.append('--')
  315. command.extend(files)
  316. diff = GIT.Capture(command, cwd=cwd, strip_out=False).splitlines(True)
  317. for i in range(len(diff)):
  318. # In the case of added files, replace /dev/null with the path to the
  319. # file being added.
  320. if diff[i].startswith('--- /dev/null'):
  321. diff[i] = '--- %s' % diff[i+1][4:]
  322. return ''.join(diff)
  323. @staticmethod
  324. def GetDifferentFiles(cwd, branch=None, branch_head='HEAD'):
  325. """Returns the list of modified files between two branches."""
  326. if not branch:
  327. branch = GIT.GetUpstreamBranch(cwd)
  328. command = ['-c', 'core.quotePath=false', 'diff',
  329. '--name-only', branch + "..." + branch_head]
  330. return GIT.Capture(command, cwd=cwd).splitlines(False)
  331. @staticmethod
  332. def GetAllFiles(cwd):
  333. """Returns the list of all files under revision control."""
  334. command = ['-c', 'core.quotePath=false', 'ls-files', '--', '.']
  335. return GIT.Capture(command, cwd=cwd).splitlines(False)
  336. @staticmethod
  337. def GetPatchName(cwd):
  338. """Constructs a name for this patch."""
  339. short_sha = GIT.Capture(['rev-parse', '--short=4', 'HEAD'], cwd=cwd)
  340. return "%s#%s" % (GIT.GetBranch(cwd), short_sha)
  341. @staticmethod
  342. def GetCheckoutRoot(cwd):
  343. """Returns the top level directory of a git checkout as an absolute path.
  344. """
  345. root = GIT.Capture(['rev-parse', '--show-cdup'], cwd=cwd)
  346. return os.path.abspath(os.path.join(cwd, root))
  347. @staticmethod
  348. def GetGitDir(cwd):
  349. return os.path.abspath(GIT.Capture(['rev-parse', '--git-dir'], cwd=cwd))
  350. @staticmethod
  351. def IsInsideWorkTree(cwd):
  352. try:
  353. return GIT.Capture(['rev-parse', '--is-inside-work-tree'], cwd=cwd)
  354. except (OSError, subprocess2.CalledProcessError):
  355. return False
  356. @staticmethod
  357. def IsDirectoryVersioned(cwd, relative_dir):
  358. """Checks whether the given |relative_dir| is part of cwd's repo."""
  359. return bool(GIT.Capture(['ls-tree', 'HEAD', relative_dir], cwd=cwd))
  360. @staticmethod
  361. def CleanupDir(cwd, relative_dir):
  362. """Cleans up untracked file inside |relative_dir|."""
  363. return bool(GIT.Capture(['clean', '-df', relative_dir], cwd=cwd))
  364. @staticmethod
  365. def ResolveCommit(cwd, rev):
  366. # We do this instead of rev-parse --verify rev^{commit}, since on Windows
  367. # git can be either an executable or batch script, each of which requires
  368. # escaping the caret (^) a different way.
  369. if gclient_utils.IsFullGitSha(rev):
  370. # git-rev parse --verify FULL_GIT_SHA always succeeds, even if we don't
  371. # have FULL_GIT_SHA locally. Removing the last character forces git to
  372. # check if FULL_GIT_SHA refers to an object in the local database.
  373. rev = rev[:-1]
  374. try:
  375. return GIT.Capture(['rev-parse', '--quiet', '--verify', rev], cwd=cwd)
  376. except subprocess2.CalledProcessError:
  377. return None
  378. @staticmethod
  379. def IsValidRevision(cwd, rev, sha_only=False):
  380. """Verifies the revision is a proper git revision.
  381. sha_only: Fail unless rev is a sha hash.
  382. """
  383. sha = GIT.ResolveCommit(cwd, rev)
  384. if sha is None:
  385. return False
  386. if sha_only:
  387. return sha == rev.lower()
  388. return True
  389. @classmethod
  390. def AssertVersion(cls, min_version):
  391. """Asserts git's version is at least min_version."""
  392. if cls.current_version is None:
  393. current_version = cls.Capture(['--version'], '.')
  394. matched = re.search(r'git version (.+)', current_version)
  395. cls.current_version = distutils.version.LooseVersion(matched.group(1))
  396. min_version = distutils.version.LooseVersion(min_version)
  397. return (min_version <= cls.current_version, cls.current_version)