scm.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. else:
  63. try:
  64. subprocess2.check_call(
  65. ['git', 'rev-parse', '--show-cdup'],
  66. stdout=subprocess2.VOID,
  67. stderr=subprocess2.VOID,
  68. cwd=root)
  69. return 'git'
  70. except (OSError, subprocess2.CalledProcessError):
  71. return None
  72. def only_int(val):
  73. if val.isdigit():
  74. return int(val)
  75. else:
  76. return 0
  77. class GIT(object):
  78. current_version = None
  79. @staticmethod
  80. def ApplyEnvVars(kwargs):
  81. env = kwargs.pop('env', None) or os.environ.copy()
  82. # Don't prompt for passwords; just fail quickly and noisily.
  83. # By default, git will use an interactive terminal prompt when a username/
  84. # password is needed. That shouldn't happen in the chromium workflow,
  85. # and if it does, then gclient may hide the prompt in the midst of a flood
  86. # of terminal spew. The only indication that something has gone wrong
  87. # will be when gclient hangs unresponsively. Instead, we disable the
  88. # password prompt and simply allow git to fail noisily. The error
  89. # message produced by git will be copied to gclient's output.
  90. env.setdefault('GIT_ASKPASS', 'true')
  91. env.setdefault('SSH_ASKPASS', 'true')
  92. # 'cat' is a magical git string that disables pagers on all platforms.
  93. env.setdefault('GIT_PAGER', 'cat')
  94. return env
  95. @staticmethod
  96. def Capture(args, cwd, strip_out=True, **kwargs):
  97. env = GIT.ApplyEnvVars(kwargs)
  98. output = subprocess2.check_output(
  99. ['git'] + args, cwd=cwd, stderr=subprocess2.PIPE, env=env, **kwargs)
  100. output = output.decode('utf-8', 'replace')
  101. return output.strip() if strip_out else output
  102. @staticmethod
  103. def CaptureStatus(cwd, upstream_branch):
  104. """Returns git status.
  105. Returns an array of (status, file) tuples."""
  106. if upstream_branch is None:
  107. upstream_branch = GIT.GetUpstreamBranch(cwd)
  108. if upstream_branch is None:
  109. raise gclient_utils.Error('Cannot determine upstream branch')
  110. command = ['-c', 'core.quotePath=false', 'diff',
  111. '--name-status', '--no-renames', '-r', '%s...' % upstream_branch]
  112. status = GIT.Capture(command, cwd)
  113. results = []
  114. if status:
  115. for statusline in status.splitlines():
  116. # 3-way merges can cause the status can be 'MMM' instead of 'M'. This
  117. # can happen when the user has 2 local branches and he diffs between
  118. # these 2 branches instead diffing to upstream.
  119. m = re.match(r'^(\w)+\t(.+)$', statusline)
  120. if not m:
  121. raise gclient_utils.Error(
  122. 'status currently unsupported: %s' % statusline)
  123. # Only grab the first letter.
  124. results.append(('%s ' % m.group(1)[0], m.group(2)))
  125. return results
  126. @staticmethod
  127. def GetConfig(cwd, key, default=None):
  128. try:
  129. return GIT.Capture(['config', key], cwd=cwd)
  130. except subprocess2.CalledProcessError:
  131. return default
  132. @staticmethod
  133. def GetBranchConfig(cwd, branch, key, default=None):
  134. assert branch, 'A branch must be given'
  135. key = 'branch.%s.%s' % (branch, key)
  136. return GIT.GetConfig(cwd, key, default)
  137. @staticmethod
  138. def SetConfig(cwd, key, value=None):
  139. if value is None:
  140. args = ['config', '--unset', key]
  141. else:
  142. args = ['config', key, value]
  143. GIT.Capture(args, cwd=cwd)
  144. @staticmethod
  145. def SetBranchConfig(cwd, branch, key, value=None):
  146. assert branch, 'A branch must be given'
  147. key = 'branch.%s.%s' % (branch, key)
  148. GIT.SetConfig(cwd, key, value)
  149. @staticmethod
  150. def IsWorkTreeDirty(cwd):
  151. return GIT.Capture(['status', '-s'], cwd=cwd) != ''
  152. @staticmethod
  153. def GetEmail(cwd):
  154. """Retrieves the user email address if known."""
  155. return GIT.GetConfig(cwd, 'user.email', '')
  156. @staticmethod
  157. def ShortBranchName(branch):
  158. """Converts a name like 'refs/heads/foo' to just 'foo'."""
  159. return branch.replace('refs/heads/', '')
  160. @staticmethod
  161. def GetBranchRef(cwd):
  162. """Returns the full branch reference, e.g. 'refs/heads/master'."""
  163. try:
  164. return GIT.Capture(['symbolic-ref', 'HEAD'], cwd=cwd)
  165. except subprocess2.CalledProcessError:
  166. return None
  167. @staticmethod
  168. def GetBranch(cwd):
  169. """Returns the short branch name, e.g. 'master'."""
  170. branchref = GIT.GetBranchRef(cwd)
  171. if branchref:
  172. return GIT.ShortBranchName(branchref)
  173. return None
  174. @staticmethod
  175. def GetRemoteBranches(cwd):
  176. return GIT.Capture(['branch', '-r'], cwd=cwd).split()
  177. @staticmethod
  178. def FetchUpstreamTuple(cwd, branch=None):
  179. """Returns a tuple containing remote and remote ref,
  180. e.g. 'origin', 'refs/heads/master'
  181. """
  182. try:
  183. branch = branch or GIT.GetBranch(cwd)
  184. except subprocess2.CalledProcessError:
  185. pass
  186. if branch:
  187. upstream_branch = GIT.GetBranchConfig(cwd, branch, 'merge')
  188. if upstream_branch:
  189. remote = GIT.GetBranchConfig(cwd, branch, 'remote', '.')
  190. return remote, upstream_branch
  191. upstream_branch = GIT.GetConfig(cwd, 'rietveld.upstream-branch')
  192. if upstream_branch:
  193. remote = GIT.GetConfig(cwd, 'rietveld.upstream-remote', '.')
  194. return remote, upstream_branch
  195. # Else, try to guess the origin remote.
  196. if 'origin/master' in GIT.GetRemoteBranches(cwd):
  197. # Fall back on origin/master if it exits.
  198. return 'origin', 'refs/heads/master'
  199. return None, None
  200. @staticmethod
  201. def RefToRemoteRef(ref, remote):
  202. """Convert a checkout ref to the equivalent remote ref.
  203. Returns:
  204. A tuple of the remote ref's (common prefix, unique suffix), or None if it
  205. doesn't appear to refer to a remote ref (e.g. it's a commit hash).
  206. """
  207. # TODO(mmoss): This is just a brute-force mapping based of the expected git
  208. # config. It's a bit better than the even more brute-force replace('heads',
  209. # ...), but could still be smarter (like maybe actually using values gleaned
  210. # from the git config).
  211. m = re.match('^(refs/(remotes/)?)?branch-heads/', ref or '')
  212. if m:
  213. return ('refs/remotes/branch-heads/', ref.replace(m.group(0), ''))
  214. m = re.match('^((refs/)?remotes/)?%s/|(refs/)?heads/' % remote, ref or '')
  215. if m:
  216. return ('refs/remotes/%s/' % remote, ref.replace(m.group(0), ''))
  217. return None
  218. @staticmethod
  219. def RemoteRefToRef(ref, remote):
  220. assert remote, 'A remote must be given'
  221. if not ref or not ref.startswith('refs/'):
  222. return None
  223. if not ref.startswith('refs/remotes/'):
  224. return ref
  225. if ref.startswith('refs/remotes/branch-heads/'):
  226. return 'refs' + ref[len('refs/remotes'):]
  227. if ref.startswith('refs/remotes/%s/' % remote):
  228. return 'refs/heads' + ref[len('refs/remotes/%s' % remote):]
  229. return None
  230. @staticmethod
  231. def GetUpstreamBranch(cwd):
  232. """Gets the current branch's upstream branch."""
  233. remote, upstream_branch = GIT.FetchUpstreamTuple(cwd)
  234. if remote != '.' and upstream_branch:
  235. remote_ref = GIT.RefToRemoteRef(upstream_branch, remote)
  236. if remote_ref:
  237. upstream_branch = ''.join(remote_ref)
  238. return upstream_branch
  239. @staticmethod
  240. def IsAncestor(cwd, maybe_ancestor, ref):
  241. """Verifies if |maybe_ancestor| is an ancestor of |ref|."""
  242. try:
  243. GIT.Capture(['merge-base', '--is-ancestor', maybe_ancestor, ref], cwd=cwd)
  244. return True
  245. except subprocess2.CalledProcessError:
  246. return False
  247. @staticmethod
  248. def GetOldContents(cwd, filename, branch=None):
  249. if not branch:
  250. branch = GIT.GetUpstreamBranch(cwd)
  251. if platform.system() == 'Windows':
  252. # git show <sha>:<path> wants a posix path.
  253. filename = filename.replace('\\', '/')
  254. command = ['show', '%s:%s' % (branch, filename)]
  255. try:
  256. return GIT.Capture(command, cwd=cwd, strip_out=False)
  257. except subprocess2.CalledProcessError:
  258. return ''
  259. @staticmethod
  260. def GenerateDiff(cwd, branch=None, branch_head='HEAD', full_move=False,
  261. files=None):
  262. """Diffs against the upstream branch or optionally another branch.
  263. full_move means that move or copy operations should completely recreate the
  264. files, usually in the prospect to apply the patch for a try job."""
  265. if not branch:
  266. branch = GIT.GetUpstreamBranch(cwd)
  267. command = ['-c', 'core.quotePath=false', 'diff',
  268. '-p', '--no-color', '--no-prefix', '--no-ext-diff',
  269. branch + "..." + branch_head]
  270. if full_move:
  271. command.append('--no-renames')
  272. else:
  273. command.append('-C')
  274. # TODO(maruel): --binary support.
  275. if files:
  276. command.append('--')
  277. command.extend(files)
  278. diff = GIT.Capture(command, cwd=cwd, strip_out=False).splitlines(True)
  279. for i in range(len(diff)):
  280. # In the case of added files, replace /dev/null with the path to the
  281. # file being added.
  282. if diff[i].startswith('--- /dev/null'):
  283. diff[i] = '--- %s' % diff[i+1][4:]
  284. return ''.join(diff)
  285. @staticmethod
  286. def GetDifferentFiles(cwd, branch=None, branch_head='HEAD'):
  287. """Returns the list of modified files between two branches."""
  288. if not branch:
  289. branch = GIT.GetUpstreamBranch(cwd)
  290. command = ['-c', 'core.quotePath=false', 'diff',
  291. '--name-only', branch + "..." + branch_head]
  292. return GIT.Capture(command, cwd=cwd).splitlines(False)
  293. @staticmethod
  294. def GetAllFiles(cwd):
  295. """Returns the list of all files under revision control."""
  296. command = ['-c', 'core.quotePath=false', 'ls-files', '--', '.']
  297. return GIT.Capture(command, cwd=cwd).splitlines(False)
  298. @staticmethod
  299. def GetPatchName(cwd):
  300. """Constructs a name for this patch."""
  301. short_sha = GIT.Capture(['rev-parse', '--short=4', 'HEAD'], cwd=cwd)
  302. return "%s#%s" % (GIT.GetBranch(cwd), short_sha)
  303. @staticmethod
  304. def GetCheckoutRoot(cwd):
  305. """Returns the top level directory of a git checkout as an absolute path.
  306. """
  307. root = GIT.Capture(['rev-parse', '--show-cdup'], cwd=cwd)
  308. return os.path.abspath(os.path.join(cwd, root))
  309. @staticmethod
  310. def GetGitDir(cwd):
  311. return os.path.abspath(GIT.Capture(['rev-parse', '--git-dir'], cwd=cwd))
  312. @staticmethod
  313. def IsInsideWorkTree(cwd):
  314. try:
  315. return GIT.Capture(['rev-parse', '--is-inside-work-tree'], cwd=cwd)
  316. except (OSError, subprocess2.CalledProcessError):
  317. return False
  318. @staticmethod
  319. def IsDirectoryVersioned(cwd, relative_dir):
  320. """Checks whether the given |relative_dir| is part of cwd's repo."""
  321. return bool(GIT.Capture(['ls-tree', 'HEAD', relative_dir], cwd=cwd))
  322. @staticmethod
  323. def CleanupDir(cwd, relative_dir):
  324. """Cleans up untracked file inside |relative_dir|."""
  325. return bool(GIT.Capture(['clean', '-df', relative_dir], cwd=cwd))
  326. @staticmethod
  327. def ResolveCommit(cwd, rev):
  328. # We do this instead of rev-parse --verify rev^{commit}, since on Windows
  329. # git can be either an executable or batch script, each of which requires
  330. # escaping the caret (^) a different way.
  331. if gclient_utils.IsFullGitSha(rev):
  332. # git-rev parse --verify FULL_GIT_SHA always succeeds, even if we don't
  333. # have FULL_GIT_SHA locally. Removing the last character forces git to
  334. # check if FULL_GIT_SHA refers to an object in the local database.
  335. rev = rev[:-1]
  336. try:
  337. return GIT.Capture(['rev-parse', '--quiet', '--verify', rev], cwd=cwd)
  338. except subprocess2.CalledProcessError:
  339. return None
  340. @staticmethod
  341. def IsValidRevision(cwd, rev, sha_only=False):
  342. """Verifies the revision is a proper git revision.
  343. sha_only: Fail unless rev is a sha hash.
  344. """
  345. sha = GIT.ResolveCommit(cwd, rev)
  346. if sha is None:
  347. return False
  348. if sha_only:
  349. return sha == rev.lower()
  350. return True
  351. @classmethod
  352. def AssertVersion(cls, min_version):
  353. """Asserts git's version is at least min_version."""
  354. if cls.current_version is None:
  355. current_version = cls.Capture(['--version'], '.')
  356. matched = re.search(r'git version (.+)', current_version)
  357. cls.current_version = distutils.version.LooseVersion(matched.group(1))
  358. min_version = distutils.version.LooseVersion(min_version)
  359. return (min_version <= cls.current_version, cls.current_version)