blob: a1699fb6de1e5212b5915ace9bbb0ec6b09f2767 [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.orgfd9cbbb2010-01-08 23:04:03 +00007import glob
Raul Tambreb946b232019-03-26 14:48:46 +00008import io
maruel@chromium.orgd5800f12009-11-12 20:03:43 +00009import os
Pierre-Antoine Manzagolfc1c6f42017-05-30 12:29:58 -040010import platform
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000011import re
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000012import sys
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000013
14import gclient_utils
maruel@chromium.org31cb48a2011-04-04 18:01:36 +000015import subprocess2
16
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000017
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +000018def ValidateEmail(email):
Andrii Shyshkalov2f727912018-10-15 17:02:33 +000019 return (
20 re.match(r"^[a-zA-Z0-9._%\-+]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}$", email)
21 is not None)
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +000022
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000023
maruel@chromium.orgfd9cbbb2010-01-08 23:04:03 +000024def GetCasedPath(path):
25 """Elcheapos way to get the real path case on Windows."""
26 if sys.platform.startswith('win') and os.path.exists(path):
27 # Reconstruct the path.
28 path = os.path.abspath(path)
29 paths = path.split('\\')
30 for i in range(len(paths)):
31 if i == 0:
32 # Skip drive letter.
33 continue
34 subpath = '\\'.join(paths[:i+1])
35 prev = len('\\'.join(paths[:i]))
36 # glob.glob will return the cased path for the last item only. This is why
37 # we are calling it in a loop. Extract the data we want and put it back
38 # into the list.
39 paths[i] = glob.glob(subpath + '*')[0][prev+1:len(subpath)]
40 path = '\\'.join(paths)
41 return path
42
43
maruel@chromium.org3c55d982010-05-06 14:25:44 +000044def GenFakeDiff(filename):
45 """Generates a fake diff from a file."""
46 file_content = gclient_utils.FileRead(filename, 'rb').splitlines(True)
maruel@chromium.orgc6d170e2010-06-03 00:06:00 +000047 filename = filename.replace(os.sep, '/')
maruel@chromium.org3c55d982010-05-06 14:25:44 +000048 nb_lines = len(file_content)
49 # We need to use / since patch on unix will fail otherwise.
Raul Tambreb946b232019-03-26 14:48:46 +000050 data = io.StringIO()
maruel@chromium.org3c55d982010-05-06 14:25:44 +000051 data.write("Index: %s\n" % filename)
52 data.write('=' * 67 + '\n')
53 # Note: Should we use /dev/null instead?
54 data.write("--- %s\n" % filename)
55 data.write("+++ %s\n" % filename)
56 data.write("@@ -0,0 +1,%d @@\n" % nb_lines)
57 # Prepend '+' to every lines.
58 for line in file_content:
59 data.write('+')
60 data.write(line)
61 result = data.getvalue()
62 data.close()
63 return result
64
65
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000066def determine_scm(root):
67 """Similar to upload.py's version but much simpler.
68
Aaron Gable208db562016-12-21 14:46:36 -080069 Returns 'git' or None.
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000070 """
Aaron Gable208db562016-12-21 14:46:36 -080071 if os.path.isdir(os.path.join(root, '.git')):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000072 return 'git'
73 else:
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000074 try:
maruel@chromium.org91def9b2011-09-14 16:28:07 +000075 subprocess2.check_call(
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000076 ['git', 'rev-parse', '--show-cdup'],
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000077 stdout=subprocess2.VOID,
maruel@chromium.org87e6d332011-09-09 19:01:28 +000078 stderr=subprocess2.VOID,
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000079 cwd=root)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000080 return 'git'
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000081 except (OSError, subprocess2.CalledProcessError):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000082 return None
83
84
maruel@chromium.org36ac2392011-10-12 16:36:11 +000085def only_int(val):
86 if val.isdigit():
87 return int(val)
88 else:
89 return 0
90
91
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000092class GIT(object):
maruel@chromium.org36ac2392011-10-12 16:36:11 +000093 current_version = None
94
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000095 @staticmethod
szager@chromium.org6d8115d2014-04-23 20:59:23 +000096 def ApplyEnvVars(kwargs):
97 env = kwargs.pop('env', None) or os.environ.copy()
98 # Don't prompt for passwords; just fail quickly and noisily.
99 # By default, git will use an interactive terminal prompt when a username/
100 # password is needed. That shouldn't happen in the chromium workflow,
101 # and if it does, then gclient may hide the prompt in the midst of a flood
102 # of terminal spew. The only indication that something has gone wrong
103 # will be when gclient hangs unresponsively. Instead, we disable the
104 # password prompt and simply allow git to fail noisily. The error
105 # message produced by git will be copied to gclient's output.
106 env.setdefault('GIT_ASKPASS', 'true')
107 env.setdefault('SSH_ASKPASS', 'true')
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000108 # 'cat' is a magical git string that disables pagers on all platforms.
szager@chromium.org6d8115d2014-04-23 20:59:23 +0000109 env.setdefault('GIT_PAGER', 'cat')
110 return env
111
112 @staticmethod
113 def Capture(args, cwd, strip_out=True, **kwargs):
114 env = GIT.ApplyEnvVars(kwargs)
ilevy@chromium.org4380c802013-07-12 23:38:41 +0000115 output = subprocess2.check_output(
Raul Tambrecd862e32019-05-10 21:19:00 +0000116 ['git'] + args, cwd=cwd, stderr=subprocess2.PIPE, env=env,
Raul Tambre6a9b00e2019-05-14 01:54:23 +0000117 **kwargs).decode('utf-8', 'replace')
ilevy@chromium.org4380c802013-07-12 23:38:41 +0000118 return output.strip() if strip_out else output
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000119
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000120 @staticmethod
maruel@chromium.org80a9ef12011-12-13 20:44:10 +0000121 def CaptureStatus(files, cwd, upstream_branch):
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000122 """Returns git status.
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000123
Edward Lemurc9144522019-10-30 21:29:10 +0000124 @files is a list of files.
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000125
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000126 Returns an array of (status, file) tuples."""
msb@chromium.org786fb682010-06-02 15:16:23 +0000127 if upstream_branch is None:
maruel@chromium.org80a9ef12011-12-13 20:44:10 +0000128 upstream_branch = GIT.GetUpstreamBranch(cwd)
msb@chromium.org786fb682010-06-02 15:16:23 +0000129 if upstream_branch is None:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000130 raise gclient_utils.Error('Cannot determine upstream branch')
Aaron Gable7817f022017-12-12 09:43:17 -0800131 command = ['-c', 'core.quotePath=false', 'diff',
132 '--name-status', '--no-renames', '-r', '%s...' % upstream_branch]
Edward Lemurc9144522019-10-30 21:29:10 +0000133 if files:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000134 command.extend(files)
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000135 status = GIT.Capture(command, cwd)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000136 results = []
137 if status:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000138 for statusline in status.splitlines():
maruel@chromium.orgcc1614b2010-09-20 17:13:17 +0000139 # 3-way merges can cause the status can be 'MMM' instead of 'M'. This
140 # can happen when the user has 2 local branches and he diffs between
141 # these 2 branches instead diffing to upstream.
Bruce Dawson9c062012019-05-02 19:20:28 +0000142 m = re.match(r'^(\w)+\t(.+)$', statusline)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000143 if not m:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000144 raise gclient_utils.Error(
145 'status currently unsupported: %s' % statusline)
maruel@chromium.orgcc1614b2010-09-20 17:13:17 +0000146 # Only grab the first letter.
147 results.append(('%s ' % m.group(1)[0], m.group(2)))
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000148 return results
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000149
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000150 @staticmethod
nodir@chromium.orgead4c7e2014-04-03 01:01:06 +0000151 def IsWorkTreeDirty(cwd):
152 return GIT.Capture(['status', '-s'], cwd=cwd) != ''
153
154 @staticmethod
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000155 def GetEmail(cwd):
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000156 """Retrieves the user email address if known."""
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000157 try:
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000158 return GIT.Capture(['config', 'user.email'], cwd=cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000159 except subprocess2.CalledProcessError:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000160 return ''
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000161
162 @staticmethod
163 def ShortBranchName(branch):
164 """Converts a name like 'refs/heads/foo' to just 'foo'."""
165 return branch.replace('refs/heads/', '')
166
167 @staticmethod
168 def GetBranchRef(cwd):
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000169 """Returns the full branch reference, e.g. 'refs/heads/master'."""
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000170 return GIT.Capture(['symbolic-ref', 'HEAD'], cwd=cwd)
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000171
172 @staticmethod
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000173 def GetBranch(cwd):
174 """Returns the short branch name, e.g. 'master'."""
maruel@chromium.orgc308a742009-12-22 18:29:33 +0000175 return GIT.ShortBranchName(GIT.GetBranchRef(cwd))
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000176
177 @staticmethod
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000178 def FetchUpstreamTuple(cwd):
179 """Returns a tuple containg remote and remote ref,
180 e.g. 'origin', 'refs/heads/master'
181 """
182 remote = '.'
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000183 branch = GIT.GetBranch(cwd)
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000184 try:
185 upstream_branch = GIT.Capture(
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000186 ['config', '--local', 'branch.%s.merge' % branch], cwd=cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000187 except subprocess2.CalledProcessError:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000188 upstream_branch = None
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000189 if upstream_branch:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000190 try:
191 remote = GIT.Capture(
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000192 ['config', '--local', 'branch.%s.remote' % branch], cwd=cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000193 except subprocess2.CalledProcessError:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000194 pass
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000195 else:
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000196 try:
197 upstream_branch = GIT.Capture(
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000198 ['config', '--local', 'rietveld.upstream-branch'], cwd=cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000199 except subprocess2.CalledProcessError:
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000200 upstream_branch = None
201 if upstream_branch:
202 try:
203 remote = GIT.Capture(
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000204 ['config', '--local', 'rietveld.upstream-remote'], cwd=cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000205 except subprocess2.CalledProcessError:
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000206 pass
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000207 else:
Aaron Gable208db562016-12-21 14:46:36 -0800208 # Else, try to guess the origin remote.
209 remote_branches = GIT.Capture(['branch', '-r'], cwd=cwd).split()
210 if 'origin/master' in remote_branches:
211 # Fall back on origin/master if it exits.
212 remote = 'origin'
213 upstream_branch = 'refs/heads/master'
maruel@chromium.orga630bd72010-04-29 23:32:34 +0000214 else:
Aaron Gable208db562016-12-21 14:46:36 -0800215 # Give up.
216 remote = None
217 upstream_branch = None
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000218 return remote, upstream_branch
219
220 @staticmethod
Edward Lemur9a5e3bd2019-04-02 23:37:45 +0000221 def RefToRemoteRef(ref, remote):
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000222 """Convert a checkout ref to the equivalent remote ref.
223
224 Returns:
225 A tuple of the remote ref's (common prefix, unique suffix), or None if it
226 doesn't appear to refer to a remote ref (e.g. it's a commit hash).
227 """
228 # TODO(mmoss): This is just a brute-force mapping based of the expected git
229 # config. It's a bit better than the even more brute-force replace('heads',
230 # ...), but could still be smarter (like maybe actually using values gleaned
231 # from the git config).
232 m = re.match('^(refs/(remotes/)?)?branch-heads/', ref or '')
233 if m:
234 return ('refs/remotes/branch-heads/', ref.replace(m.group(0), ''))
Edward Lemur9a5e3bd2019-04-02 23:37:45 +0000235
236 m = re.match('^((refs/)?remotes/)?%s/|(refs/)?heads/' % remote, ref or '')
237 if m:
238 return ('refs/remotes/%s/' % remote, ref.replace(m.group(0), ''))
239
240 return None
241
242 @staticmethod
243 def RemoteRefToRef(ref, remote):
244 assert remote, 'A remote must be given'
245 if not ref or not ref.startswith('refs/'):
246 return None
247 if not ref.startswith('refs/remotes/'):
248 return ref
249 if ref.startswith('refs/remotes/branch-heads/'):
250 return 'refs' + ref[len('refs/remotes'):]
251 if ref.startswith('refs/remotes/%s/' % remote):
252 return 'refs/heads' + ref[len('refs/remotes/%s' % remote):]
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000253 return None
254
255 @staticmethod
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000256 def GetUpstreamBranch(cwd):
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000257 """Gets the current branch's upstream branch."""
258 remote, upstream_branch = GIT.FetchUpstreamTuple(cwd)
maruel@chromium.orga630bd72010-04-29 23:32:34 +0000259 if remote != '.' and upstream_branch:
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000260 remote_ref = GIT.RefToRemoteRef(upstream_branch, remote)
261 if remote_ref:
262 upstream_branch = ''.join(remote_ref)
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000263 return upstream_branch
264
265 @staticmethod
Edward Lemurca7d8812018-07-24 17:42:45 +0000266 def IsAncestor(cwd, maybe_ancestor, ref):
267 """Verifies if |maybe_ancestor| is an ancestor of |ref|."""
268 try:
269 GIT.Capture(['merge-base', '--is-ancestor', maybe_ancestor, ref], cwd=cwd)
270 return True
271 except subprocess2.CalledProcessError:
272 return False
273
274 @staticmethod
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700275 def GetOldContents(cwd, filename, branch=None):
276 if not branch:
277 branch = GIT.GetUpstreamBranch(cwd)
Pierre-Antoine Manzagolfc1c6f42017-05-30 12:29:58 -0400278 if platform.system() == 'Windows':
279 # git show <sha>:<path> wants a posix path.
280 filename = filename.replace('\\', '/')
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700281 command = ['show', '%s:%s' % (branch, filename)]
Daniel Chengd67e7152017-04-13 01:21:03 -0700282 try:
283 return GIT.Capture(command, cwd=cwd, strip_out=False)
284 except subprocess2.CalledProcessError:
285 return ''
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700286
287 @staticmethod
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000288 def GenerateDiff(cwd, branch=None, branch_head='HEAD', full_move=False,
289 files=None):
maruel@chromium.orga9371762009-12-22 18:27:38 +0000290 """Diffs against the upstream branch or optionally another branch.
291
292 full_move means that move or copy operations should completely recreate the
293 files, usually in the prospect to apply the patch for a try job."""
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000294 if not branch:
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000295 branch = GIT.GetUpstreamBranch(cwd)
Aaron Gablef4068aa2017-12-12 15:14:09 -0800296 command = ['-c', 'core.quotePath=false', 'diff',
297 '-p', '--no-color', '--no-prefix', '--no-ext-diff',
evan@chromium.org400f3e72010-05-19 14:23:36 +0000298 branch + "..." + branch_head]
mcgrathr@chromium.org9249f642013-06-03 21:36:18 +0000299 if full_move:
300 command.append('--no-renames')
301 else:
maruel@chromium.orga9371762009-12-22 18:27:38 +0000302 command.append('-C')
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000303 # TODO(maruel): --binary support.
304 if files:
305 command.append('--')
306 command.extend(files)
ilevy@chromium.org4380c802013-07-12 23:38:41 +0000307 diff = GIT.Capture(command, cwd=cwd, strip_out=False).splitlines(True)
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000308 for i in range(len(diff)):
309 # In the case of added files, replace /dev/null with the path to the
310 # file being added.
311 if diff[i].startswith('--- /dev/null'):
312 diff[i] = '--- %s' % diff[i+1][4:]
313 return ''.join(diff)
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000314
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000315 @staticmethod
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000316 def GetDifferentFiles(cwd, branch=None, branch_head='HEAD'):
317 """Returns the list of modified files between two branches."""
318 if not branch:
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000319 branch = GIT.GetUpstreamBranch(cwd)
Aaron Gablef4068aa2017-12-12 15:14:09 -0800320 command = ['-c', 'core.quotePath=false', 'diff',
321 '--name-only', branch + "..." + branch_head]
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000322 return GIT.Capture(command, cwd=cwd).splitlines(False)
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000323
324 @staticmethod
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000325 def GetPatchName(cwd):
326 """Constructs a name for this patch."""
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000327 short_sha = GIT.Capture(['rev-parse', '--short=4', 'HEAD'], cwd=cwd)
maruel@chromium.org862ff8e2010-08-06 15:29:16 +0000328 return "%s#%s" % (GIT.GetBranch(cwd), short_sha)
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000329
330 @staticmethod
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000331 def GetCheckoutRoot(cwd):
maruel@chromium.org01d8c1d2010-01-07 01:56:59 +0000332 """Returns the top level directory of a git checkout as an absolute path.
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000333 """
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000334 root = GIT.Capture(['rev-parse', '--show-cdup'], cwd=cwd)
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000335 return os.path.abspath(os.path.join(cwd, root))
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000336
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000337 @staticmethod
nodir@chromium.orgead4c7e2014-04-03 01:01:06 +0000338 def GetGitDir(cwd):
339 return os.path.abspath(GIT.Capture(['rev-parse', '--git-dir'], cwd=cwd))
340
341 @staticmethod
342 def IsInsideWorkTree(cwd):
343 try:
344 return GIT.Capture(['rev-parse', '--is-inside-work-tree'], cwd=cwd)
345 except (OSError, subprocess2.CalledProcessError):
346 return False
347
348 @staticmethod
primiano@chromium.org1c127382015-02-17 11:15:40 +0000349 def IsDirectoryVersioned(cwd, relative_dir):
350 """Checks whether the given |relative_dir| is part of cwd's repo."""
351 return bool(GIT.Capture(['ls-tree', 'HEAD', relative_dir], cwd=cwd))
352
353 @staticmethod
354 def CleanupDir(cwd, relative_dir):
355 """Cleans up untracked file inside |relative_dir|."""
356 return bool(GIT.Capture(['clean', '-df', relative_dir], cwd=cwd))
357
358 @staticmethod
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000359 def IsValidRevision(cwd, rev, sha_only=False):
360 """Verifies the revision is a proper git revision.
361
362 sha_only: Fail unless rev is a sha hash.
363 """
Edward Lemur8c665652019-05-08 20:23:33 +0000364 if sys.platform.startswith('win'):
365 # Windows .bat scripts use ^ as escape sequence, which means we have to
366 # escape it with itself for every .bat invocation.
367 needle = '%s^^^^{commit}' % rev
368 else:
369 needle = '%s^{commit}' % rev
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000370 try:
Edward Lemur8c665652019-05-08 20:23:33 +0000371 sha = GIT.Capture(['rev-parse', '--verify', needle], cwd=cwd)
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000372 if sha_only:
Michael Spang2f3c8202019-03-07 20:05:07 +0000373 return sha == rev.lower()
hinoka@google.com68953172014-06-11 22:14:35 +0000374 return True
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000375 except subprocess2.CalledProcessError:
376 return False
377
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000378 @classmethod
379 def AssertVersion(cls, min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000380 """Asserts git's version is at least min_version."""
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000381 if cls.current_version is None:
bashi@chromium.orgfcffd482012-02-24 01:47:00 +0000382 current_version = cls.Capture(['--version'], '.')
Raul Tambrecd862e32019-05-10 21:19:00 +0000383 matched = re.search(r'version ([0-9\.]+)', current_version)
bashi@chromium.orgfcffd482012-02-24 01:47:00 +0000384 cls.current_version = matched.group(1)
Raul Tambreb946b232019-03-26 14:48:46 +0000385 current_version_list = list(map(only_int, cls.current_version.split('.')))
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000386 for min_ver in map(int, min_version.split('.')):
387 ver = current_version_list.pop(0)
388 if ver < min_ver:
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000389 return (False, cls.current_version)
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000390 elif ver > min_ver:
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000391 return (True, cls.current_version)
392 return (True, cls.current_version)