blob: 42f566bdd7aca7da11acd83eeb02eaaa7677c30f [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
Edward Lesmes50da7702020-03-30 19:23:43 +00007import distutils.version
maruel@chromium.orgfd9cbbb2010-01-08 23:04:03 +00008import glob
Raul Tambreb946b232019-03-26 14:48:46 +00009import io
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
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000014
15import gclient_utils
maruel@chromium.org31cb48a2011-04-04 18:01:36 +000016import subprocess2
17
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000018
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +000019def ValidateEmail(email):
Andrii Shyshkalov2f727912018-10-15 17:02:33 +000020 return (
21 re.match(r"^[a-zA-Z0-9._%\-+]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}$", email)
22 is not None)
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +000023
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000024
maruel@chromium.orgfd9cbbb2010-01-08 23:04:03 +000025def GetCasedPath(path):
26 """Elcheapos way to get the real path case on Windows."""
27 if sys.platform.startswith('win') and os.path.exists(path):
28 # Reconstruct the path.
29 path = os.path.abspath(path)
30 paths = path.split('\\')
31 for i in range(len(paths)):
32 if i == 0:
33 # Skip drive letter.
34 continue
35 subpath = '\\'.join(paths[:i+1])
36 prev = len('\\'.join(paths[:i]))
37 # glob.glob will return the cased path for the last item only. This is why
38 # we are calling it in a loop. Extract the data we want and put it back
39 # into the list.
40 paths[i] = glob.glob(subpath + '*')[0][prev+1:len(subpath)]
41 path = '\\'.join(paths)
42 return path
43
44
maruel@chromium.org3c55d982010-05-06 14:25:44 +000045def GenFakeDiff(filename):
46 """Generates a fake diff from a file."""
47 file_content = gclient_utils.FileRead(filename, 'rb').splitlines(True)
maruel@chromium.orgc6d170e2010-06-03 00:06:00 +000048 filename = filename.replace(os.sep, '/')
maruel@chromium.org3c55d982010-05-06 14:25:44 +000049 nb_lines = len(file_content)
50 # We need to use / since patch on unix will fail otherwise.
Raul Tambreb946b232019-03-26 14:48:46 +000051 data = io.StringIO()
maruel@chromium.org3c55d982010-05-06 14:25:44 +000052 data.write("Index: %s\n" % filename)
53 data.write('=' * 67 + '\n')
54 # Note: Should we use /dev/null instead?
55 data.write("--- %s\n" % filename)
56 data.write("+++ %s\n" % filename)
57 data.write("@@ -0,0 +1,%d @@\n" % nb_lines)
58 # Prepend '+' to every lines.
59 for line in file_content:
60 data.write('+')
61 data.write(line)
62 result = data.getvalue()
63 data.close()
64 return result
65
66
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000067def determine_scm(root):
68 """Similar to upload.py's version but much simpler.
69
Aaron Gable208db562016-12-21 14:46:36 -080070 Returns 'git' or None.
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000071 """
Aaron Gable208db562016-12-21 14:46:36 -080072 if os.path.isdir(os.path.join(root, '.git')):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000073 return 'git'
74 else:
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000075 try:
maruel@chromium.org91def9b2011-09-14 16:28:07 +000076 subprocess2.check_call(
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000077 ['git', 'rev-parse', '--show-cdup'],
Edward Lesmescf06cad2020-12-14 22:03:23 +000078 stdout=subprocess2.DEVNULL,
79 stderr=subprocess2.DEVNULL,
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000080 cwd=root)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000081 return 'git'
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000082 except (OSError, subprocess2.CalledProcessError):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000083 return None
84
85
maruel@chromium.org36ac2392011-10-12 16:36:11 +000086def only_int(val):
87 if val.isdigit():
88 return int(val)
89 else:
90 return 0
91
92
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000093class GIT(object):
maruel@chromium.org36ac2392011-10-12 16:36:11 +000094 current_version = None
95
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000096 @staticmethod
szager@chromium.org6d8115d2014-04-23 20:59:23 +000097 def ApplyEnvVars(kwargs):
98 env = kwargs.pop('env', None) or os.environ.copy()
99 # Don't prompt for passwords; just fail quickly and noisily.
100 # By default, git will use an interactive terminal prompt when a username/
101 # password is needed. That shouldn't happen in the chromium workflow,
102 # and if it does, then gclient may hide the prompt in the midst of a flood
103 # of terminal spew. The only indication that something has gone wrong
104 # will be when gclient hangs unresponsively. Instead, we disable the
105 # password prompt and simply allow git to fail noisily. The error
106 # message produced by git will be copied to gclient's output.
107 env.setdefault('GIT_ASKPASS', 'true')
108 env.setdefault('SSH_ASKPASS', 'true')
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000109 # 'cat' is a magical git string that disables pagers on all platforms.
szager@chromium.org6d8115d2014-04-23 20:59:23 +0000110 env.setdefault('GIT_PAGER', 'cat')
111 return env
112
113 @staticmethod
114 def Capture(args, cwd, strip_out=True, **kwargs):
115 env = GIT.ApplyEnvVars(kwargs)
ilevy@chromium.org4380c802013-07-12 23:38:41 +0000116 output = subprocess2.check_output(
Edward Lesmes50da7702020-03-30 19:23:43 +0000117 ['git'] + args, cwd=cwd, stderr=subprocess2.PIPE, env=env, **kwargs)
118 output = output.decode('utf-8', 'replace')
ilevy@chromium.org4380c802013-07-12 23:38:41 +0000119 return output.strip() if strip_out else output
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000120
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000121 @staticmethod
Edward Lemur7f6dec02020-02-06 20:23:58 +0000122 def CaptureStatus(cwd, upstream_branch):
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000123 """Returns git status.
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000124
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000125 Returns an array of (status, file) tuples."""
msb@chromium.org786fb682010-06-02 15:16:23 +0000126 if upstream_branch is None:
maruel@chromium.org80a9ef12011-12-13 20:44:10 +0000127 upstream_branch = GIT.GetUpstreamBranch(cwd)
msb@chromium.org786fb682010-06-02 15:16:23 +0000128 if upstream_branch is None:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000129 raise gclient_utils.Error('Cannot determine upstream branch')
Aaron Gable7817f022017-12-12 09:43:17 -0800130 command = ['-c', 'core.quotePath=false', 'diff',
131 '--name-status', '--no-renames', '-r', '%s...' % upstream_branch]
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000132 status = GIT.Capture(command, cwd)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000133 results = []
134 if status:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000135 for statusline in status.splitlines():
maruel@chromium.orgcc1614b2010-09-20 17:13:17 +0000136 # 3-way merges can cause the status can be 'MMM' instead of 'M'. This
137 # can happen when the user has 2 local branches and he diffs between
138 # these 2 branches instead diffing to upstream.
Bruce Dawson9c062012019-05-02 19:20:28 +0000139 m = re.match(r'^(\w)+\t(.+)$', statusline)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000140 if not m:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000141 raise gclient_utils.Error(
142 'status currently unsupported: %s' % statusline)
maruel@chromium.orgcc1614b2010-09-20 17:13:17 +0000143 # Only grab the first letter.
144 results.append(('%s ' % m.group(1)[0], m.group(2)))
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000145 return results
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000146
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000147 @staticmethod
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000148 def GetConfig(cwd, key, default=None):
149 try:
150 return GIT.Capture(['config', key], cwd=cwd)
151 except subprocess2.CalledProcessError:
152 return default
153
154 @staticmethod
155 def GetBranchConfig(cwd, branch, key, default=None):
156 assert branch, 'A branch must be given'
157 key = 'branch.%s.%s' % (branch, key)
158 return GIT.GetConfig(cwd, key, default)
159
160 @staticmethod
161 def SetConfig(cwd, key, value=None):
162 if value is None:
163 args = ['config', '--unset', key]
164 else:
165 args = ['config', key, value]
166 GIT.Capture(args, cwd=cwd)
167
168 @staticmethod
169 def SetBranchConfig(cwd, branch, key, value=None):
170 assert branch, 'A branch must be given'
171 key = 'branch.%s.%s' % (branch, key)
172 GIT.SetConfig(cwd, key, value)
173
174 @staticmethod
nodir@chromium.orgead4c7e2014-04-03 01:01:06 +0000175 def IsWorkTreeDirty(cwd):
176 return GIT.Capture(['status', '-s'], cwd=cwd) != ''
177
178 @staticmethod
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000179 def GetEmail(cwd):
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000180 """Retrieves the user email address if known."""
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000181 return GIT.GetConfig(cwd, 'user.email', '')
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000182
183 @staticmethod
184 def ShortBranchName(branch):
185 """Converts a name like 'refs/heads/foo' to just 'foo'."""
186 return branch.replace('refs/heads/', '')
187
188 @staticmethod
189 def GetBranchRef(cwd):
Josip Sokcevic9c0dc302020-11-20 18:41:25 +0000190 """Returns the full branch reference, e.g. 'refs/heads/main'."""
Edward Lemur85153282020-02-14 22:06:29 +0000191 try:
192 return GIT.Capture(['symbolic-ref', 'HEAD'], cwd=cwd)
193 except subprocess2.CalledProcessError:
194 return None
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000195
196 @staticmethod
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000197 def GetBranch(cwd):
Josip Sokcevic9c0dc302020-11-20 18:41:25 +0000198 """Returns the short branch name, e.g. 'main'."""
Edward Lemur85153282020-02-14 22:06:29 +0000199 branchref = GIT.GetBranchRef(cwd)
200 if branchref:
201 return GIT.ShortBranchName(branchref)
202 return None
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000203
204 @staticmethod
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000205 def GetRemoteBranches(cwd):
206 return GIT.Capture(['branch', '-r'], cwd=cwd).split()
207
208 @staticmethod
209 def FetchUpstreamTuple(cwd, branch=None):
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000210 """Returns a tuple containing remote and remote ref,
Josip Sokcevic9c0dc302020-11-20 18:41:25 +0000211 e.g. 'origin', 'refs/heads/main'
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000212 """
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000213 try:
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000214 branch = branch or GIT.GetBranch(cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000215 except subprocess2.CalledProcessError:
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000216 pass
217 if branch:
218 upstream_branch = GIT.GetBranchConfig(cwd, branch, 'merge')
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000219 if upstream_branch:
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000220 remote = GIT.GetBranchConfig(cwd, branch, 'remote', '.')
221 return remote, upstream_branch
222
223 upstream_branch = GIT.GetConfig(cwd, 'rietveld.upstream-branch')
224 if upstream_branch:
225 remote = GIT.GetConfig(cwd, 'rietveld.upstream-remote', '.')
226 return remote, upstream_branch
227
228 # Else, try to guess the origin remote.
Josip Sokcevic5bdfcd82020-11-03 17:27:15 +0000229 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 elif 'origin/master' in remote_branches:
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000234 # Fall back on origin/master if it exits.
235 return 'origin', 'refs/heads/master'
236
237 return None, None
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000238
239 @staticmethod
Edward Lemur9a5e3bd2019-04-02 23:37:45 +0000240 def RefToRemoteRef(ref, remote):
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000241 """Convert a checkout ref to the equivalent remote ref.
242
243 Returns:
244 A tuple of the remote ref's (common prefix, unique suffix), or None if it
245 doesn't appear to refer to a remote ref (e.g. it's a commit hash).
246 """
247 # TODO(mmoss): This is just a brute-force mapping based of the expected git
248 # config. It's a bit better than the even more brute-force replace('heads',
249 # ...), but could still be smarter (like maybe actually using values gleaned
250 # from the git config).
251 m = re.match('^(refs/(remotes/)?)?branch-heads/', ref or '')
252 if m:
253 return ('refs/remotes/branch-heads/', ref.replace(m.group(0), ''))
Edward Lemur9a5e3bd2019-04-02 23:37:45 +0000254
255 m = re.match('^((refs/)?remotes/)?%s/|(refs/)?heads/' % remote, ref or '')
256 if m:
257 return ('refs/remotes/%s/' % remote, ref.replace(m.group(0), ''))
258
259 return None
260
261 @staticmethod
262 def RemoteRefToRef(ref, remote):
263 assert remote, 'A remote must be given'
264 if not ref or not ref.startswith('refs/'):
265 return None
266 if not ref.startswith('refs/remotes/'):
267 return ref
268 if ref.startswith('refs/remotes/branch-heads/'):
269 return 'refs' + ref[len('refs/remotes'):]
270 if ref.startswith('refs/remotes/%s/' % remote):
271 return 'refs/heads' + ref[len('refs/remotes/%s' % remote):]
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000272 return None
273
274 @staticmethod
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000275 def GetUpstreamBranch(cwd):
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000276 """Gets the current branch's upstream branch."""
277 remote, upstream_branch = GIT.FetchUpstreamTuple(cwd)
maruel@chromium.orga630bd72010-04-29 23:32:34 +0000278 if remote != '.' and upstream_branch:
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000279 remote_ref = GIT.RefToRemoteRef(upstream_branch, remote)
280 if remote_ref:
281 upstream_branch = ''.join(remote_ref)
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000282 return upstream_branch
283
284 @staticmethod
Edward Lemurca7d8812018-07-24 17:42:45 +0000285 def IsAncestor(cwd, maybe_ancestor, ref):
286 """Verifies if |maybe_ancestor| is an ancestor of |ref|."""
287 try:
288 GIT.Capture(['merge-base', '--is-ancestor', maybe_ancestor, ref], cwd=cwd)
289 return True
290 except subprocess2.CalledProcessError:
291 return False
292
293 @staticmethod
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700294 def GetOldContents(cwd, filename, branch=None):
295 if not branch:
296 branch = GIT.GetUpstreamBranch(cwd)
Pierre-Antoine Manzagolfc1c6f42017-05-30 12:29:58 -0400297 if platform.system() == 'Windows':
298 # git show <sha>:<path> wants a posix path.
299 filename = filename.replace('\\', '/')
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700300 command = ['show', '%s:%s' % (branch, filename)]
Daniel Chengd67e7152017-04-13 01:21:03 -0700301 try:
302 return GIT.Capture(command, cwd=cwd, strip_out=False)
303 except subprocess2.CalledProcessError:
304 return ''
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700305
306 @staticmethod
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000307 def GenerateDiff(cwd, branch=None, branch_head='HEAD', full_move=False,
308 files=None):
maruel@chromium.orga9371762009-12-22 18:27:38 +0000309 """Diffs against the upstream branch or optionally another branch.
310
311 full_move means that move or copy operations should completely recreate the
312 files, usually in the prospect to apply the patch for a try job."""
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000313 if not branch:
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000314 branch = GIT.GetUpstreamBranch(cwd)
Aaron Gablef4068aa2017-12-12 15:14:09 -0800315 command = ['-c', 'core.quotePath=false', 'diff',
316 '-p', '--no-color', '--no-prefix', '--no-ext-diff',
evan@chromium.org400f3e72010-05-19 14:23:36 +0000317 branch + "..." + branch_head]
mcgrathr@chromium.org9249f642013-06-03 21:36:18 +0000318 if full_move:
319 command.append('--no-renames')
320 else:
maruel@chromium.orga9371762009-12-22 18:27:38 +0000321 command.append('-C')
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000322 # TODO(maruel): --binary support.
323 if files:
324 command.append('--')
325 command.extend(files)
ilevy@chromium.org4380c802013-07-12 23:38:41 +0000326 diff = GIT.Capture(command, cwd=cwd, strip_out=False).splitlines(True)
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000327 for i in range(len(diff)):
328 # In the case of added files, replace /dev/null with the path to the
329 # file being added.
330 if diff[i].startswith('--- /dev/null'):
331 diff[i] = '--- %s' % diff[i+1][4:]
332 return ''.join(diff)
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000333
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000334 @staticmethod
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000335 def GetDifferentFiles(cwd, branch=None, branch_head='HEAD'):
336 """Returns the list of modified files between two branches."""
337 if not branch:
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000338 branch = GIT.GetUpstreamBranch(cwd)
Aaron Gablef4068aa2017-12-12 15:14:09 -0800339 command = ['-c', 'core.quotePath=false', 'diff',
340 '--name-only', branch + "..." + branch_head]
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000341 return GIT.Capture(command, cwd=cwd).splitlines(False)
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000342
343 @staticmethod
Edward Lemur98cfac12020-01-17 19:27:01 +0000344 def GetAllFiles(cwd):
345 """Returns the list of all files under revision control."""
346 command = ['-c', 'core.quotePath=false', 'ls-files', '--', '.']
347 return GIT.Capture(command, cwd=cwd).splitlines(False)
348
349 @staticmethod
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000350 def GetPatchName(cwd):
351 """Constructs a name for this patch."""
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000352 short_sha = GIT.Capture(['rev-parse', '--short=4', 'HEAD'], cwd=cwd)
maruel@chromium.org862ff8e2010-08-06 15:29:16 +0000353 return "%s#%s" % (GIT.GetBranch(cwd), short_sha)
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000354
355 @staticmethod
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000356 def GetCheckoutRoot(cwd):
maruel@chromium.org01d8c1d2010-01-07 01:56:59 +0000357 """Returns the top level directory of a git checkout as an absolute path.
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000358 """
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000359 root = GIT.Capture(['rev-parse', '--show-cdup'], cwd=cwd)
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000360 return os.path.abspath(os.path.join(cwd, root))
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000361
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000362 @staticmethod
nodir@chromium.orgead4c7e2014-04-03 01:01:06 +0000363 def GetGitDir(cwd):
364 return os.path.abspath(GIT.Capture(['rev-parse', '--git-dir'], cwd=cwd))
365
366 @staticmethod
367 def IsInsideWorkTree(cwd):
368 try:
369 return GIT.Capture(['rev-parse', '--is-inside-work-tree'], cwd=cwd)
370 except (OSError, subprocess2.CalledProcessError):
371 return False
372
373 @staticmethod
primiano@chromium.org1c127382015-02-17 11:15:40 +0000374 def IsDirectoryVersioned(cwd, relative_dir):
375 """Checks whether the given |relative_dir| is part of cwd's repo."""
376 return bool(GIT.Capture(['ls-tree', 'HEAD', relative_dir], cwd=cwd))
377
378 @staticmethod
379 def CleanupDir(cwd, relative_dir):
380 """Cleans up untracked file inside |relative_dir|."""
381 return bool(GIT.Capture(['clean', '-df', relative_dir], cwd=cwd))
382
383 @staticmethod
Edward Lemurd52edda2020-03-11 20:13:02 +0000384 def ResolveCommit(cwd, rev):
Edward Lesmes56dbf9a2020-03-31 22:52:54 +0000385 # We do this instead of rev-parse --verify rev^{commit}, since on Windows
386 # git can be either an executable or batch script, each of which requires
387 # escaping the caret (^) a different way.
388 if gclient_utils.IsFullGitSha(rev):
389 # git-rev parse --verify FULL_GIT_SHA always succeeds, even if we don't
390 # have FULL_GIT_SHA locally. Removing the last character forces git to
391 # check if FULL_GIT_SHA refers to an object in the local database.
392 rev = rev[:-1]
Edward Lemurd52edda2020-03-11 20:13:02 +0000393 try:
Edward Lesmes56dbf9a2020-03-31 22:52:54 +0000394 return GIT.Capture(['rev-parse', '--quiet', '--verify', rev], cwd=cwd)
Edward Lemurd52edda2020-03-11 20:13:02 +0000395 except subprocess2.CalledProcessError:
396 return None
397
398 @staticmethod
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000399 def IsValidRevision(cwd, rev, sha_only=False):
400 """Verifies the revision is a proper git revision.
401
402 sha_only: Fail unless rev is a sha hash.
403 """
Edward Lemurd52edda2020-03-11 20:13:02 +0000404 sha = GIT.ResolveCommit(cwd, rev)
405 if sha is None:
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000406 return False
Edward Lemurd52edda2020-03-11 20:13:02 +0000407 if sha_only:
408 return sha == rev.lower()
409 return True
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000410
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000411 @classmethod
412 def AssertVersion(cls, min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000413 """Asserts git's version is at least min_version."""
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000414 if cls.current_version is None:
bashi@chromium.orgfcffd482012-02-24 01:47:00 +0000415 current_version = cls.Capture(['--version'], '.')
Edward Lesmes50da7702020-03-30 19:23:43 +0000416 matched = re.search(r'git version (.+)', current_version)
417 cls.current_version = distutils.version.LooseVersion(matched.group(1))
418 min_version = distutils.version.LooseVersion(min_version)
419 return (min_version <= cls.current_version, cls.current_version)