scm.py 18 KB

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