blob: b30b14cfdb3a500581a31f23fac01b4769f930f9 [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.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):
Andrii Shyshkalov2f727912018-10-15 17:02:33 +000023 return (
24 re.match(r"^[a-zA-Z0-9._%\-+]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}$", email)
25 is not None)
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +000026
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000027
maruel@chromium.orgfd9cbbb2010-01-08 23:04:03 +000028def GetCasedPath(path):
29 """Elcheapos way to get the real path case on Windows."""
30 if sys.platform.startswith('win') and os.path.exists(path):
31 # Reconstruct the path.
32 path = os.path.abspath(path)
33 paths = path.split('\\')
34 for i in range(len(paths)):
35 if i == 0:
36 # Skip drive letter.
37 continue
38 subpath = '\\'.join(paths[:i+1])
39 prev = len('\\'.join(paths[:i]))
40 # glob.glob will return the cased path for the last item only. This is why
41 # we are calling it in a loop. Extract the data we want and put it back
42 # into the list.
43 paths[i] = glob.glob(subpath + '*')[0][prev+1:len(subpath)]
44 path = '\\'.join(paths)
45 return path
46
47
maruel@chromium.org3c55d982010-05-06 14:25:44 +000048def GenFakeDiff(filename):
49 """Generates a fake diff from a file."""
50 file_content = gclient_utils.FileRead(filename, 'rb').splitlines(True)
maruel@chromium.orgc6d170e2010-06-03 00:06:00 +000051 filename = filename.replace(os.sep, '/')
maruel@chromium.org3c55d982010-05-06 14:25:44 +000052 nb_lines = len(file_content)
53 # We need to use / since patch on unix will fail otherwise.
Raul Tambreb946b232019-03-26 14:48:46 +000054 data = io.StringIO()
maruel@chromium.org3c55d982010-05-06 14:25:44 +000055 data.write("Index: %s\n" % filename)
56 data.write('=' * 67 + '\n')
57 # Note: Should we use /dev/null instead?
58 data.write("--- %s\n" % filename)
59 data.write("+++ %s\n" % filename)
60 data.write("@@ -0,0 +1,%d @@\n" % nb_lines)
61 # Prepend '+' to every lines.
62 for line in file_content:
63 data.write('+')
64 data.write(line)
65 result = data.getvalue()
66 data.close()
67 return result
68
69
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000070def determine_scm(root):
71 """Similar to upload.py's version but much simpler.
72
Aaron Gable208db562016-12-21 14:46:36 -080073 Returns 'git' or None.
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000074 """
Aaron Gable208db562016-12-21 14:46:36 -080075 if os.path.isdir(os.path.join(root, '.git')):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000076 return 'git'
77 else:
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000078 try:
maruel@chromium.org91def9b2011-09-14 16:28:07 +000079 subprocess2.check_call(
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000080 ['git', 'rev-parse', '--show-cdup'],
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000081 stdout=subprocess2.VOID,
maruel@chromium.org87e6d332011-09-09 19:01:28 +000082 stderr=subprocess2.VOID,
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000083 cwd=root)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000084 return 'git'
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000085 except (OSError, subprocess2.CalledProcessError):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000086 return None
87
88
maruel@chromium.org36ac2392011-10-12 16:36:11 +000089def only_int(val):
90 if val.isdigit():
91 return int(val)
92 else:
93 return 0
94
95
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000096class GIT(object):
maruel@chromium.org36ac2392011-10-12 16:36:11 +000097 current_version = None
98
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000099 @staticmethod
szager@chromium.org6d8115d2014-04-23 20:59:23 +0000100 def ApplyEnvVars(kwargs):
101 env = kwargs.pop('env', None) or os.environ.copy()
102 # Don't prompt for passwords; just fail quickly and noisily.
103 # By default, git will use an interactive terminal prompt when a username/
104 # password is needed. That shouldn't happen in the chromium workflow,
105 # and if it does, then gclient may hide the prompt in the midst of a flood
106 # of terminal spew. The only indication that something has gone wrong
107 # will be when gclient hangs unresponsively. Instead, we disable the
108 # password prompt and simply allow git to fail noisily. The error
109 # message produced by git will be copied to gclient's output.
110 env.setdefault('GIT_ASKPASS', 'true')
111 env.setdefault('SSH_ASKPASS', 'true')
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000112 # 'cat' is a magical git string that disables pagers on all platforms.
szager@chromium.org6d8115d2014-04-23 20:59:23 +0000113 env.setdefault('GIT_PAGER', 'cat')
114 return env
115
116 @staticmethod
117 def Capture(args, cwd, strip_out=True, **kwargs):
118 env = GIT.ApplyEnvVars(kwargs)
ilevy@chromium.org4380c802013-07-12 23:38:41 +0000119 output = subprocess2.check_output(
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000120 ['git'] + args,
ilevy@chromium.org4380c802013-07-12 23:38:41 +0000121 cwd=cwd, stderr=subprocess2.PIPE, env=env, **kwargs)
122 return output.strip() if strip_out else output
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000123
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000124 @staticmethod
maruel@chromium.org80a9ef12011-12-13 20:44:10 +0000125 def CaptureStatus(files, cwd, upstream_branch):
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000126 """Returns git status.
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000127
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000128 @files can be a string (one file) or a list of files.
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000129
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000130 Returns an array of (status, file) tuples."""
msb@chromium.org786fb682010-06-02 15:16:23 +0000131 if upstream_branch is None:
maruel@chromium.org80a9ef12011-12-13 20:44:10 +0000132 upstream_branch = GIT.GetUpstreamBranch(cwd)
msb@chromium.org786fb682010-06-02 15:16:23 +0000133 if upstream_branch is None:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000134 raise gclient_utils.Error('Cannot determine upstream branch')
Aaron Gable7817f022017-12-12 09:43:17 -0800135 command = ['-c', 'core.quotePath=false', 'diff',
136 '--name-status', '--no-renames', '-r', '%s...' % upstream_branch]
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000137 if not files:
138 pass
139 elif isinstance(files, basestring):
140 command.append(files)
141 else:
142 command.extend(files)
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000143 status = GIT.Capture(command, cwd)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000144 results = []
145 if status:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000146 for statusline in status.splitlines():
maruel@chromium.orgcc1614b2010-09-20 17:13:17 +0000147 # 3-way merges can cause the status can be 'MMM' instead of 'M'. This
148 # can happen when the user has 2 local branches and he diffs between
149 # these 2 branches instead diffing to upstream.
150 m = re.match('^(\w)+\t(.+)$', statusline)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000151 if not m:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000152 raise gclient_utils.Error(
153 'status currently unsupported: %s' % statusline)
maruel@chromium.orgcc1614b2010-09-20 17:13:17 +0000154 # Only grab the first letter.
155 results.append(('%s ' % m.group(1)[0], m.group(2)))
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000156 return results
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000157
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000158 @staticmethod
nodir@chromium.orgead4c7e2014-04-03 01:01:06 +0000159 def IsWorkTreeDirty(cwd):
160 return GIT.Capture(['status', '-s'], cwd=cwd) != ''
161
162 @staticmethod
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000163 def GetEmail(cwd):
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000164 """Retrieves the user email address if known."""
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000165 try:
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000166 return GIT.Capture(['config', 'user.email'], cwd=cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000167 except subprocess2.CalledProcessError:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000168 return ''
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000169
170 @staticmethod
171 def ShortBranchName(branch):
172 """Converts a name like 'refs/heads/foo' to just 'foo'."""
173 return branch.replace('refs/heads/', '')
174
175 @staticmethod
176 def GetBranchRef(cwd):
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000177 """Returns the full branch reference, e.g. 'refs/heads/master'."""
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000178 return GIT.Capture(['symbolic-ref', 'HEAD'], cwd=cwd)
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000179
180 @staticmethod
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000181 def GetBranch(cwd):
182 """Returns the short branch name, e.g. 'master'."""
maruel@chromium.orgc308a742009-12-22 18:29:33 +0000183 return GIT.ShortBranchName(GIT.GetBranchRef(cwd))
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000184
185 @staticmethod
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000186 def FetchUpstreamTuple(cwd):
187 """Returns a tuple containg remote and remote ref,
188 e.g. 'origin', 'refs/heads/master'
189 """
190 remote = '.'
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000191 branch = GIT.GetBranch(cwd)
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000192 try:
193 upstream_branch = GIT.Capture(
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000194 ['config', '--local', 'branch.%s.merge' % branch], cwd=cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000195 except subprocess2.CalledProcessError:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000196 upstream_branch = None
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000197 if upstream_branch:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000198 try:
199 remote = GIT.Capture(
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000200 ['config', '--local', 'branch.%s.remote' % branch], cwd=cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000201 except subprocess2.CalledProcessError:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000202 pass
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000203 else:
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000204 try:
205 upstream_branch = GIT.Capture(
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000206 ['config', '--local', 'rietveld.upstream-branch'], cwd=cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000207 except subprocess2.CalledProcessError:
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000208 upstream_branch = None
209 if upstream_branch:
210 try:
211 remote = GIT.Capture(
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000212 ['config', '--local', 'rietveld.upstream-remote'], cwd=cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000213 except subprocess2.CalledProcessError:
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000214 pass
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000215 else:
Aaron Gable208db562016-12-21 14:46:36 -0800216 # Else, try to guess the origin remote.
217 remote_branches = GIT.Capture(['branch', '-r'], cwd=cwd).split()
218 if 'origin/master' in remote_branches:
219 # Fall back on origin/master if it exits.
220 remote = 'origin'
221 upstream_branch = 'refs/heads/master'
maruel@chromium.orga630bd72010-04-29 23:32:34 +0000222 else:
Aaron Gable208db562016-12-21 14:46:36 -0800223 # Give up.
224 remote = None
225 upstream_branch = None
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000226 return remote, upstream_branch
227
228 @staticmethod
Edward Lemur9a5e3bd2019-04-02 23:37:45 +0000229 def RefToRemoteRef(ref, remote):
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000230 """Convert a checkout ref to the equivalent remote ref.
231
232 Returns:
233 A tuple of the remote ref's (common prefix, unique suffix), or None if it
234 doesn't appear to refer to a remote ref (e.g. it's a commit hash).
235 """
236 # TODO(mmoss): This is just a brute-force mapping based of the expected git
237 # config. It's a bit better than the even more brute-force replace('heads',
238 # ...), but could still be smarter (like maybe actually using values gleaned
239 # from the git config).
240 m = re.match('^(refs/(remotes/)?)?branch-heads/', ref or '')
241 if m:
242 return ('refs/remotes/branch-heads/', ref.replace(m.group(0), ''))
Edward Lemur9a5e3bd2019-04-02 23:37:45 +0000243
244 m = re.match('^((refs/)?remotes/)?%s/|(refs/)?heads/' % remote, ref or '')
245 if m:
246 return ('refs/remotes/%s/' % remote, ref.replace(m.group(0), ''))
247
248 return None
249
250 @staticmethod
251 def RemoteRefToRef(ref, remote):
252 assert remote, 'A remote must be given'
253 if not ref or not ref.startswith('refs/'):
254 return None
255 if not ref.startswith('refs/remotes/'):
256 return ref
257 if ref.startswith('refs/remotes/branch-heads/'):
258 return 'refs' + ref[len('refs/remotes'):]
259 if ref.startswith('refs/remotes/%s/' % remote):
260 return 'refs/heads' + ref[len('refs/remotes/%s' % remote):]
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000261 return None
262
263 @staticmethod
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000264 def GetUpstreamBranch(cwd):
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000265 """Gets the current branch's upstream branch."""
266 remote, upstream_branch = GIT.FetchUpstreamTuple(cwd)
maruel@chromium.orga630bd72010-04-29 23:32:34 +0000267 if remote != '.' and upstream_branch:
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000268 remote_ref = GIT.RefToRemoteRef(upstream_branch, remote)
269 if remote_ref:
270 upstream_branch = ''.join(remote_ref)
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000271 return upstream_branch
272
273 @staticmethod
Edward Lemurca7d8812018-07-24 17:42:45 +0000274 def IsAncestor(cwd, maybe_ancestor, ref):
275 """Verifies if |maybe_ancestor| is an ancestor of |ref|."""
276 try:
277 GIT.Capture(['merge-base', '--is-ancestor', maybe_ancestor, ref], cwd=cwd)
278 return True
279 except subprocess2.CalledProcessError:
280 return False
281
282 @staticmethod
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700283 def GetOldContents(cwd, filename, branch=None):
284 if not branch:
285 branch = GIT.GetUpstreamBranch(cwd)
Pierre-Antoine Manzagolfc1c6f42017-05-30 12:29:58 -0400286 if platform.system() == 'Windows':
287 # git show <sha>:<path> wants a posix path.
288 filename = filename.replace('\\', '/')
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700289 command = ['show', '%s:%s' % (branch, filename)]
Daniel Chengd67e7152017-04-13 01:21:03 -0700290 try:
291 return GIT.Capture(command, cwd=cwd, strip_out=False)
292 except subprocess2.CalledProcessError:
293 return ''
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700294
295 @staticmethod
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000296 def GenerateDiff(cwd, branch=None, branch_head='HEAD', full_move=False,
297 files=None):
maruel@chromium.orga9371762009-12-22 18:27:38 +0000298 """Diffs against the upstream branch or optionally another branch.
299
300 full_move means that move or copy operations should completely recreate the
301 files, usually in the prospect to apply the patch for a try job."""
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000302 if not branch:
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000303 branch = GIT.GetUpstreamBranch(cwd)
Aaron Gablef4068aa2017-12-12 15:14:09 -0800304 command = ['-c', 'core.quotePath=false', 'diff',
305 '-p', '--no-color', '--no-prefix', '--no-ext-diff',
evan@chromium.org400f3e72010-05-19 14:23:36 +0000306 branch + "..." + branch_head]
mcgrathr@chromium.org9249f642013-06-03 21:36:18 +0000307 if full_move:
308 command.append('--no-renames')
309 else:
maruel@chromium.orga9371762009-12-22 18:27:38 +0000310 command.append('-C')
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000311 # TODO(maruel): --binary support.
312 if files:
313 command.append('--')
314 command.extend(files)
ilevy@chromium.org4380c802013-07-12 23:38:41 +0000315 diff = GIT.Capture(command, cwd=cwd, strip_out=False).splitlines(True)
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000316 for i in range(len(diff)):
317 # In the case of added files, replace /dev/null with the path to the
318 # file being added.
319 if diff[i].startswith('--- /dev/null'):
320 diff[i] = '--- %s' % diff[i+1][4:]
321 return ''.join(diff)
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000322
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000323 @staticmethod
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000324 def GetDifferentFiles(cwd, branch=None, branch_head='HEAD'):
325 """Returns the list of modified files between two branches."""
326 if not branch:
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000327 branch = GIT.GetUpstreamBranch(cwd)
Aaron Gablef4068aa2017-12-12 15:14:09 -0800328 command = ['-c', 'core.quotePath=false', 'diff',
329 '--name-only', branch + "..." + branch_head]
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000330 return GIT.Capture(command, cwd=cwd).splitlines(False)
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000331
332 @staticmethod
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000333 def GetPatchName(cwd):
334 """Constructs a name for this patch."""
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000335 short_sha = GIT.Capture(['rev-parse', '--short=4', 'HEAD'], cwd=cwd)
maruel@chromium.org862ff8e2010-08-06 15:29:16 +0000336 return "%s#%s" % (GIT.GetBranch(cwd), short_sha)
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000337
338 @staticmethod
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000339 def GetCheckoutRoot(cwd):
maruel@chromium.org01d8c1d2010-01-07 01:56:59 +0000340 """Returns the top level directory of a git checkout as an absolute path.
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000341 """
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000342 root = GIT.Capture(['rev-parse', '--show-cdup'], cwd=cwd)
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000343 return os.path.abspath(os.path.join(cwd, root))
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000344
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000345 @staticmethod
nodir@chromium.orgead4c7e2014-04-03 01:01:06 +0000346 def GetGitDir(cwd):
347 return os.path.abspath(GIT.Capture(['rev-parse', '--git-dir'], cwd=cwd))
348
349 @staticmethod
350 def IsInsideWorkTree(cwd):
351 try:
352 return GIT.Capture(['rev-parse', '--is-inside-work-tree'], cwd=cwd)
353 except (OSError, subprocess2.CalledProcessError):
354 return False
355
356 @staticmethod
primiano@chromium.org1c127382015-02-17 11:15:40 +0000357 def IsDirectoryVersioned(cwd, relative_dir):
358 """Checks whether the given |relative_dir| is part of cwd's repo."""
359 return bool(GIT.Capture(['ls-tree', 'HEAD', relative_dir], cwd=cwd))
360
361 @staticmethod
362 def CleanupDir(cwd, relative_dir):
363 """Cleans up untracked file inside |relative_dir|."""
364 return bool(GIT.Capture(['clean', '-df', relative_dir], cwd=cwd))
365
366 @staticmethod
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000367 def IsValidRevision(cwd, rev, sha_only=False):
368 """Verifies the revision is a proper git revision.
369
370 sha_only: Fail unless rev is a sha hash.
371 """
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000372 try:
Michael Spang2f3c8202019-03-07 20:05:07 +0000373 sha = GIT.Capture(['rev-parse', '--verify', '%s^{commit}' % rev],
374 cwd=cwd)
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000375 if sha_only:
Michael Spang2f3c8202019-03-07 20:05:07 +0000376 return sha == rev.lower()
hinoka@google.com68953172014-06-11 22:14:35 +0000377 return True
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000378 except subprocess2.CalledProcessError:
379 return False
380
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000381 @classmethod
382 def AssertVersion(cls, min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000383 """Asserts git's version is at least min_version."""
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000384 if cls.current_version is None:
bashi@chromium.orgfcffd482012-02-24 01:47:00 +0000385 current_version = cls.Capture(['--version'], '.')
Raul Tambreb946b232019-03-26 14:48:46 +0000386 matched = re.search(r'version ([0-9\.]+)', current_version.decode())
bashi@chromium.orgfcffd482012-02-24 01:47:00 +0000387 cls.current_version = matched.group(1)
Raul Tambreb946b232019-03-26 14:48:46 +0000388 current_version_list = list(map(only_int, cls.current_version.split('.')))
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000389 for min_ver in map(int, min_version.split('.')):
390 ver = current_version_list.pop(0)
391 if ver < min_ver:
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000392 return (False, cls.current_version)
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000393 elif ver > min_ver:
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000394 return (True, cls.current_version)
395 return (True, cls.current_version)