blob: a8b3579143f25520efee4c469a00fda26cd74893 [file] [log] [blame]
maruel@chromium.org7d654672012-01-05 19:07:23 +00001# Copyright (c) 2012 The Chromium Authors. All rights reserved.
maruel@chromium.orgd5800f12009-11-12 20:03:43 +00002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +00005"""SCM-specific utility classes."""
maruel@chromium.orgd5800f12009-11-12 20:03:43 +00006
maruel@chromium.org3c55d982010-05-06 14:25:44 +00007import cStringIO
maruel@chromium.orgfd9cbbb2010-01-08 23:04:03 +00008import glob
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00009import logging
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000010import os
Pierre-Antoine Manzagolfc1c6f42017-05-30 12:29:58 -040011import platform
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000012import re
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000013import sys
pkasting@chromium.org4755b582013-04-18 21:38:40 +000014import tempfile
maruel@chromium.orgfd876172010-04-30 14:01:05 +000015import time
maruel@chromium.orgade9c592011-04-07 15:59:11 +000016from xml.etree import ElementTree
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000017
18import gclient_utils
maruel@chromium.org31cb48a2011-04-04 18:01:36 +000019import subprocess2
20
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000021
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +000022def ValidateEmail(email):
maruel@chromium.org6e29d572010-06-04 17:32:20 +000023 return (re.match(r"^[a-zA-Z0-9._%-+]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}$", email)
24 is not None)
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +000025
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000026
maruel@chromium.orgfd9cbbb2010-01-08 23:04:03 +000027def GetCasedPath(path):
28 """Elcheapos way to get the real path case on Windows."""
29 if sys.platform.startswith('win') and os.path.exists(path):
30 # Reconstruct the path.
31 path = os.path.abspath(path)
32 paths = path.split('\\')
33 for i in range(len(paths)):
34 if i == 0:
35 # Skip drive letter.
36 continue
37 subpath = '\\'.join(paths[:i+1])
38 prev = len('\\'.join(paths[:i]))
39 # glob.glob will return the cased path for the last item only. This is why
40 # we are calling it in a loop. Extract the data we want and put it back
41 # into the list.
42 paths[i] = glob.glob(subpath + '*')[0][prev+1:len(subpath)]
43 path = '\\'.join(paths)
44 return path
45
46
maruel@chromium.org3c55d982010-05-06 14:25:44 +000047def GenFakeDiff(filename):
48 """Generates a fake diff from a file."""
49 file_content = gclient_utils.FileRead(filename, 'rb').splitlines(True)
maruel@chromium.orgc6d170e2010-06-03 00:06:00 +000050 filename = filename.replace(os.sep, '/')
maruel@chromium.org3c55d982010-05-06 14:25:44 +000051 nb_lines = len(file_content)
52 # We need to use / since patch on unix will fail otherwise.
53 data = cStringIO.StringIO()
54 data.write("Index: %s\n" % filename)
55 data.write('=' * 67 + '\n')
56 # Note: Should we use /dev/null instead?
57 data.write("--- %s\n" % filename)
58 data.write("+++ %s\n" % filename)
59 data.write("@@ -0,0 +1,%d @@\n" % nb_lines)
60 # Prepend '+' to every lines.
61 for line in file_content:
62 data.write('+')
63 data.write(line)
64 result = data.getvalue()
65 data.close()
66 return result
67
68
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000069def determine_scm(root):
70 """Similar to upload.py's version but much simpler.
71
Aaron Gable208db562016-12-21 14:46:36 -080072 Returns 'git' or None.
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000073 """
Aaron Gable208db562016-12-21 14:46:36 -080074 if os.path.isdir(os.path.join(root, '.git')):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000075 return 'git'
76 else:
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000077 try:
maruel@chromium.org91def9b2011-09-14 16:28:07 +000078 subprocess2.check_call(
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000079 ['git', 'rev-parse', '--show-cdup'],
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000080 stdout=subprocess2.VOID,
maruel@chromium.org87e6d332011-09-09 19:01:28 +000081 stderr=subprocess2.VOID,
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000082 cwd=root)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000083 return 'git'
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000084 except (OSError, subprocess2.CalledProcessError):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000085 return None
86
87
maruel@chromium.org36ac2392011-10-12 16:36:11 +000088def only_int(val):
89 if val.isdigit():
90 return int(val)
91 else:
92 return 0
93
94
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000095class GIT(object):
maruel@chromium.org36ac2392011-10-12 16:36:11 +000096 current_version = None
97
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000098 @staticmethod
szager@chromium.org6d8115d2014-04-23 20:59:23 +000099 def ApplyEnvVars(kwargs):
100 env = kwargs.pop('env', None) or os.environ.copy()
101 # Don't prompt for passwords; just fail quickly and noisily.
102 # By default, git will use an interactive terminal prompt when a username/
103 # password is needed. That shouldn't happen in the chromium workflow,
104 # and if it does, then gclient may hide the prompt in the midst of a flood
105 # of terminal spew. The only indication that something has gone wrong
106 # will be when gclient hangs unresponsively. Instead, we disable the
107 # password prompt and simply allow git to fail noisily. The error
108 # message produced by git will be copied to gclient's output.
109 env.setdefault('GIT_ASKPASS', 'true')
110 env.setdefault('SSH_ASKPASS', 'true')
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000111 # 'cat' is a magical git string that disables pagers on all platforms.
szager@chromium.org6d8115d2014-04-23 20:59:23 +0000112 env.setdefault('GIT_PAGER', 'cat')
113 return env
114
115 @staticmethod
116 def Capture(args, cwd, strip_out=True, **kwargs):
117 env = GIT.ApplyEnvVars(kwargs)
ilevy@chromium.org4380c802013-07-12 23:38:41 +0000118 output = subprocess2.check_output(
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000119 ['git'] + args,
ilevy@chromium.org4380c802013-07-12 23:38:41 +0000120 cwd=cwd, stderr=subprocess2.PIPE, env=env, **kwargs)
121 return output.strip() if strip_out else output
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000122
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000123 @staticmethod
maruel@chromium.org80a9ef12011-12-13 20:44:10 +0000124 def CaptureStatus(files, cwd, upstream_branch):
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000125 """Returns git status.
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000126
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000127 @files can be a string (one file) or a list of files.
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000128
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000129 Returns an array of (status, file) tuples."""
msb@chromium.org786fb682010-06-02 15:16:23 +0000130 if upstream_branch is None:
maruel@chromium.org80a9ef12011-12-13 20:44:10 +0000131 upstream_branch = GIT.GetUpstreamBranch(cwd)
msb@chromium.org786fb682010-06-02 15:16:23 +0000132 if upstream_branch is None:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000133 raise gclient_utils.Error('Cannot determine upstream branch')
Aaron Gable7817f022017-12-12 09:43:17 -0800134 command = ['-c', 'core.quotePath=false', 'diff',
135 '--name-status', '--no-renames', '-r', '%s...' % upstream_branch]
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000136 if not files:
137 pass
138 elif isinstance(files, basestring):
139 command.append(files)
140 else:
141 command.extend(files)
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000142 status = GIT.Capture(command, cwd)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000143 results = []
144 if status:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000145 for statusline in status.splitlines():
maruel@chromium.orgcc1614b2010-09-20 17:13:17 +0000146 # 3-way merges can cause the status can be 'MMM' instead of 'M'. This
147 # can happen when the user has 2 local branches and he diffs between
148 # these 2 branches instead diffing to upstream.
149 m = re.match('^(\w)+\t(.+)$', statusline)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000150 if not m:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000151 raise gclient_utils.Error(
152 'status currently unsupported: %s' % statusline)
maruel@chromium.orgcc1614b2010-09-20 17:13:17 +0000153 # Only grab the first letter.
154 results.append(('%s ' % m.group(1)[0], m.group(2)))
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000155 return results
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000156
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000157 @staticmethod
nodir@chromium.orgead4c7e2014-04-03 01:01:06 +0000158 def IsWorkTreeDirty(cwd):
159 return GIT.Capture(['status', '-s'], cwd=cwd) != ''
160
161 @staticmethod
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000162 def GetEmail(cwd):
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000163 """Retrieves the user email address if known."""
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000164 try:
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000165 return GIT.Capture(['config', 'user.email'], cwd=cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000166 except subprocess2.CalledProcessError:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000167 return ''
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000168
169 @staticmethod
170 def ShortBranchName(branch):
171 """Converts a name like 'refs/heads/foo' to just 'foo'."""
172 return branch.replace('refs/heads/', '')
173
174 @staticmethod
175 def GetBranchRef(cwd):
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000176 """Returns the full branch reference, e.g. 'refs/heads/master'."""
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000177 return GIT.Capture(['symbolic-ref', 'HEAD'], cwd=cwd)
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000178
179 @staticmethod
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000180 def GetBranch(cwd):
181 """Returns the short branch name, e.g. 'master'."""
maruel@chromium.orgc308a742009-12-22 18:29:33 +0000182 return GIT.ShortBranchName(GIT.GetBranchRef(cwd))
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000183
184 @staticmethod
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000185 def FetchUpstreamTuple(cwd):
186 """Returns a tuple containg remote and remote ref,
187 e.g. 'origin', 'refs/heads/master'
188 """
189 remote = '.'
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000190 branch = GIT.GetBranch(cwd)
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000191 try:
192 upstream_branch = GIT.Capture(
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000193 ['config', '--local', 'branch.%s.merge' % branch], cwd=cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000194 except subprocess2.CalledProcessError:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000195 upstream_branch = None
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000196 if upstream_branch:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000197 try:
198 remote = GIT.Capture(
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000199 ['config', '--local', 'branch.%s.remote' % branch], cwd=cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000200 except subprocess2.CalledProcessError:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000201 pass
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000202 else:
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000203 try:
204 upstream_branch = GIT.Capture(
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000205 ['config', '--local', 'rietveld.upstream-branch'], cwd=cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000206 except subprocess2.CalledProcessError:
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000207 upstream_branch = None
208 if upstream_branch:
209 try:
210 remote = GIT.Capture(
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000211 ['config', '--local', 'rietveld.upstream-remote'], cwd=cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000212 except subprocess2.CalledProcessError:
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000213 pass
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000214 else:
Aaron Gable208db562016-12-21 14:46:36 -0800215 # Else, try to guess the origin remote.
216 remote_branches = GIT.Capture(['branch', '-r'], cwd=cwd).split()
217 if 'origin/master' in remote_branches:
218 # Fall back on origin/master if it exits.
219 remote = 'origin'
220 upstream_branch = 'refs/heads/master'
maruel@chromium.orga630bd72010-04-29 23:32:34 +0000221 else:
Aaron Gable208db562016-12-21 14:46:36 -0800222 # Give up.
223 remote = None
224 upstream_branch = None
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000225 return remote, upstream_branch
226
227 @staticmethod
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000228 def RefToRemoteRef(ref, remote=None):
229 """Convert a checkout ref to the equivalent remote ref.
230
231 Returns:
232 A tuple of the remote ref's (common prefix, unique suffix), or None if it
233 doesn't appear to refer to a remote ref (e.g. it's a commit hash).
234 """
235 # TODO(mmoss): This is just a brute-force mapping based of the expected git
236 # config. It's a bit better than the even more brute-force replace('heads',
237 # ...), but could still be smarter (like maybe actually using values gleaned
238 # from the git config).
239 m = re.match('^(refs/(remotes/)?)?branch-heads/', ref or '')
240 if m:
241 return ('refs/remotes/branch-heads/', ref.replace(m.group(0), ''))
242 if remote:
243 m = re.match('^((refs/)?remotes/)?%s/|(refs/)?heads/' % remote, ref or '')
244 if m:
245 return ('refs/remotes/%s/' % remote, ref.replace(m.group(0), ''))
246 return None
247
248 @staticmethod
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000249 def GetUpstreamBranch(cwd):
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000250 """Gets the current branch's upstream branch."""
251 remote, upstream_branch = GIT.FetchUpstreamTuple(cwd)
maruel@chromium.orga630bd72010-04-29 23:32:34 +0000252 if remote != '.' and upstream_branch:
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000253 remote_ref = GIT.RefToRemoteRef(upstream_branch, remote)
254 if remote_ref:
255 upstream_branch = ''.join(remote_ref)
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000256 return upstream_branch
257
258 @staticmethod
Edward Lemurca7d8812018-07-24 17:42:45 +0000259 def IsAncestor(cwd, maybe_ancestor, ref):
260 """Verifies if |maybe_ancestor| is an ancestor of |ref|."""
261 try:
262 GIT.Capture(['merge-base', '--is-ancestor', maybe_ancestor, ref], cwd=cwd)
263 return True
264 except subprocess2.CalledProcessError:
265 return False
266
267 @staticmethod
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700268 def GetOldContents(cwd, filename, branch=None):
269 if not branch:
270 branch = GIT.GetUpstreamBranch(cwd)
Pierre-Antoine Manzagolfc1c6f42017-05-30 12:29:58 -0400271 if platform.system() == 'Windows':
272 # git show <sha>:<path> wants a posix path.
273 filename = filename.replace('\\', '/')
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700274 command = ['show', '%s:%s' % (branch, filename)]
Daniel Chengd67e7152017-04-13 01:21:03 -0700275 try:
276 return GIT.Capture(command, cwd=cwd, strip_out=False)
277 except subprocess2.CalledProcessError:
278 return ''
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700279
280 @staticmethod
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000281 def GenerateDiff(cwd, branch=None, branch_head='HEAD', full_move=False,
282 files=None):
maruel@chromium.orga9371762009-12-22 18:27:38 +0000283 """Diffs against the upstream branch or optionally another branch.
284
285 full_move means that move or copy operations should completely recreate the
286 files, usually in the prospect to apply the patch for a try job."""
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000287 if not branch:
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000288 branch = GIT.GetUpstreamBranch(cwd)
Aaron Gablef4068aa2017-12-12 15:14:09 -0800289 command = ['-c', 'core.quotePath=false', 'diff',
290 '-p', '--no-color', '--no-prefix', '--no-ext-diff',
evan@chromium.org400f3e72010-05-19 14:23:36 +0000291 branch + "..." + branch_head]
mcgrathr@chromium.org9249f642013-06-03 21:36:18 +0000292 if full_move:
293 command.append('--no-renames')
294 else:
maruel@chromium.orga9371762009-12-22 18:27:38 +0000295 command.append('-C')
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000296 # TODO(maruel): --binary support.
297 if files:
298 command.append('--')
299 command.extend(files)
ilevy@chromium.org4380c802013-07-12 23:38:41 +0000300 diff = GIT.Capture(command, cwd=cwd, strip_out=False).splitlines(True)
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000301 for i in range(len(diff)):
302 # In the case of added files, replace /dev/null with the path to the
303 # file being added.
304 if diff[i].startswith('--- /dev/null'):
305 diff[i] = '--- %s' % diff[i+1][4:]
306 return ''.join(diff)
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000307
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000308 @staticmethod
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000309 def GetDifferentFiles(cwd, branch=None, branch_head='HEAD'):
310 """Returns the list of modified files between two branches."""
311 if not branch:
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000312 branch = GIT.GetUpstreamBranch(cwd)
Aaron Gablef4068aa2017-12-12 15:14:09 -0800313 command = ['-c', 'core.quotePath=false', 'diff',
314 '--name-only', branch + "..." + branch_head]
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000315 return GIT.Capture(command, cwd=cwd).splitlines(False)
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000316
317 @staticmethod
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000318 def GetPatchName(cwd):
319 """Constructs a name for this patch."""
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000320 short_sha = GIT.Capture(['rev-parse', '--short=4', 'HEAD'], cwd=cwd)
maruel@chromium.org862ff8e2010-08-06 15:29:16 +0000321 return "%s#%s" % (GIT.GetBranch(cwd), short_sha)
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000322
323 @staticmethod
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000324 def GetCheckoutRoot(cwd):
maruel@chromium.org01d8c1d2010-01-07 01:56:59 +0000325 """Returns the top level directory of a git checkout as an absolute path.
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000326 """
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000327 root = GIT.Capture(['rev-parse', '--show-cdup'], cwd=cwd)
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000328 return os.path.abspath(os.path.join(cwd, root))
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000329
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000330 @staticmethod
nodir@chromium.orgead4c7e2014-04-03 01:01:06 +0000331 def GetGitDir(cwd):
332 return os.path.abspath(GIT.Capture(['rev-parse', '--git-dir'], cwd=cwd))
333
334 @staticmethod
335 def IsInsideWorkTree(cwd):
336 try:
337 return GIT.Capture(['rev-parse', '--is-inside-work-tree'], cwd=cwd)
338 except (OSError, subprocess2.CalledProcessError):
339 return False
340
341 @staticmethod
primiano@chromium.org1c127382015-02-17 11:15:40 +0000342 def IsDirectoryVersioned(cwd, relative_dir):
343 """Checks whether the given |relative_dir| is part of cwd's repo."""
344 return bool(GIT.Capture(['ls-tree', 'HEAD', relative_dir], cwd=cwd))
345
346 @staticmethod
347 def CleanupDir(cwd, relative_dir):
348 """Cleans up untracked file inside |relative_dir|."""
349 return bool(GIT.Capture(['clean', '-df', relative_dir], cwd=cwd))
350
351 @staticmethod
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000352 def IsValidRevision(cwd, rev, sha_only=False):
353 """Verifies the revision is a proper git revision.
354
355 sha_only: Fail unless rev is a sha hash.
356 """
maruel@chromium.org81473862012-06-27 17:30:56 +0000357 # 'git rev-parse foo' where foo is *any* 40 character hex string will return
358 # the string and return code 0. So strip one character to force 'git
359 # rev-parse' to do a hash table look-up and returns 128 if the hash is not
360 # present.
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000361 lookup_rev = rev
maruel@chromium.org81473862012-06-27 17:30:56 +0000362 if re.match(r'^[0-9a-fA-F]{40}$', rev):
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000363 lookup_rev = rev[:-1]
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000364 try:
ilevy@chromium.org224ba242013-07-08 22:02:31 +0000365 sha = GIT.Capture(['rev-parse', lookup_rev], cwd=cwd).lower()
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000366 if lookup_rev != rev:
367 # Make sure we get the original 40 chars back.
hinoka@google.com68953172014-06-11 22:14:35 +0000368 return rev.lower() == sha
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000369 if sha_only:
hinoka@google.com68953172014-06-11 22:14:35 +0000370 return sha.startswith(rev.lower())
371 return True
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000372 except subprocess2.CalledProcessError:
373 return False
374
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000375 @classmethod
376 def AssertVersion(cls, min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000377 """Asserts git's version is at least min_version."""
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000378 if cls.current_version is None:
bashi@chromium.orgfcffd482012-02-24 01:47:00 +0000379 current_version = cls.Capture(['--version'], '.')
380 matched = re.search(r'version ([0-9\.]+)', current_version)
381 cls.current_version = matched.group(1)
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000382 current_version_list = map(only_int, cls.current_version.split('.'))
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000383 for min_ver in map(int, min_version.split('.')):
384 ver = current_version_list.pop(0)
385 if ver < min_ver:
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000386 return (False, cls.current_version)
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000387 elif ver > min_ver:
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000388 return (True, cls.current_version)
389 return (True, cls.current_version)