blob: 904f67c88748006f0720955668254d107ff143fa [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.
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +00004"""SCM-specific utility classes."""
maruel@chromium.orgd5800f12009-11-12 20:03:43 +00005
Edward Lesmes50da7702020-03-30 19:23:43 +00006import distutils.version
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
Mike Frysinger124bb8e2023-09-06 05:48:55 +000017# TODO: Should fix these warnings.
18# pylint: disable=line-too-long
19
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000020
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +000021def ValidateEmail(email):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000022 return (re.match(r"^[a-zA-Z0-9._%\-+]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}$",
23 email) is not None)
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +000024
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000025
maruel@chromium.orgfd9cbbb2010-01-08 23:04:03 +000026def GetCasedPath(path):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000027 """Elcheapos way to get the real path case on Windows."""
28 if sys.platform.startswith('win') and os.path.exists(path):
29 # Reconstruct the path.
30 path = os.path.abspath(path)
31 paths = path.split('\\')
32 for i in range(len(paths)):
33 if i == 0:
34 # Skip drive letter.
35 continue
36 subpath = '\\'.join(paths[:i + 1])
37 prev = len('\\'.join(paths[:i]))
38 # glob.glob will return the cased path for the last item only. This
39 # is why we are calling it in a loop. Extract the data we want and
40 # put it back into the list.
41 paths[i] = glob.glob(subpath + '*')[0][prev + 1:len(subpath)]
42 path = '\\'.join(paths)
43 return path
maruel@chromium.orgfd9cbbb2010-01-08 23:04:03 +000044
45
maruel@chromium.org3c55d982010-05-06 14:25:44 +000046def GenFakeDiff(filename):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000047 """Generates a fake diff from a file."""
48 file_content = gclient_utils.FileRead(filename, 'rb').splitlines(True)
49 filename = filename.replace(os.sep, '/')
50 nb_lines = len(file_content)
51 # We need to use / since patch on unix will fail otherwise.
52 data = io.StringIO()
53 data.write("Index: %s\n" % filename)
54 data.write('=' * 67 + '\n')
55 # Note: Should we use /dev/null instead?
56 data.write("--- %s\n" % filename)
57 data.write("+++ %s\n" % filename)
58 data.write("@@ -0,0 +1,%d @@\n" % nb_lines)
59 # Prepend '+' to every lines.
60 for line in file_content:
61 data.write('+')
62 data.write(line)
63 result = data.getvalue()
64 data.close()
65 return result
maruel@chromium.org3c55d982010-05-06 14:25:44 +000066
67
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000068def determine_scm(root):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000069 """Similar to upload.py's version but much simpler.
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000070
Aaron Gable208db562016-12-21 14:46:36 -080071 Returns 'git' or None.
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000072 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +000073 if os.path.isdir(os.path.join(root, '.git')):
74 return 'git'
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +000075
Mike Frysinger124bb8e2023-09-06 05:48:55 +000076 try:
77 subprocess2.check_call(['git', 'rev-parse', '--show-cdup'],
78 stdout=subprocess2.DEVNULL,
79 stderr=subprocess2.DEVNULL,
80 cwd=root)
81 return 'git'
82 except (OSError, subprocess2.CalledProcessError):
83 return None
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000084
85
maruel@chromium.org36ac2392011-10-12 16:36:11 +000086def only_int(val):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000087 if val.isdigit():
88 return int(val)
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +000089
Mike Frysinger124bb8e2023-09-06 05:48:55 +000090 return 0
maruel@chromium.org36ac2392011-10-12 16:36:11 +000091
92
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000093class GIT(object):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000094 current_version = None
maruel@chromium.org36ac2392011-10-12 16:36:11 +000095
Mike Frysinger124bb8e2023-09-06 05:48:55 +000096 @staticmethod
97 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
101 # username/ password is needed. That shouldn't happen in the chromium
102 # workflow, and if it does, then gclient may hide the prompt in the
103 # midst of a flood of terminal spew. The only indication that something
104 # has gone wrong will be when gclient hangs unresponsively. Instead, we
105 # disable the password prompt and simply allow git to fail noisily. The
106 # error message produced by git will be copied to gclient's output.
107 env.setdefault('GIT_ASKPASS', 'true')
108 env.setdefault('SSH_ASKPASS', 'true')
109 # 'cat' is a magical git string that disables pagers on all platforms.
110 env.setdefault('GIT_PAGER', 'cat')
111 return env
szager@chromium.org6d8115d2014-04-23 20:59:23 +0000112
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000113 @staticmethod
114 def Capture(args, cwd=None, strip_out=True, **kwargs):
115 env = GIT.ApplyEnvVars(kwargs)
116 output = subprocess2.check_output(['git'] + args,
117 cwd=cwd,
118 stderr=subprocess2.PIPE,
119 env=env,
120 **kwargs)
121 output = output.decode('utf-8', 'replace')
122 return output.strip() if strip_out else output
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000123
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000124 @staticmethod
125 def CaptureStatus(cwd, upstream_branch, end_commit=None):
126 # type: (str, str, Optional[str]) -> Sequence[Tuple[str, str]]
127 """Returns git status.
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."""
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000130 if end_commit is None:
131 end_commit = ''
132 if upstream_branch is None:
133 upstream_branch = GIT.GetUpstreamBranch(cwd)
134 if upstream_branch is None:
135 raise gclient_utils.Error('Cannot determine upstream branch')
136 command = [
137 '-c', 'core.quotePath=false', 'diff', '--name-status',
138 '--no-renames', '--ignore-submodules=all', '-r',
139 '%s...%s' % (upstream_branch, end_commit)
140 ]
141 status = GIT.Capture(command, cwd)
142 results = []
143 if status:
144 for statusline in status.splitlines():
145 # 3-way merges can cause the status can be 'MMM' instead of 'M'.
146 # This can happen when the user has 2 local branches and he
147 # diffs between these 2 branches instead diffing to upstream.
148 m = re.match(r'^(\w)+\t(.+)$', statusline)
149 if not m:
150 raise gclient_utils.Error(
151 'status currently unsupported: %s' % statusline)
152 # Only grab the first letter.
153 results.append(('%s ' % m.group(1)[0], m.group(2)))
154 return results
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000155
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000156 @staticmethod
157 def GetConfig(cwd, key, default=None):
158 try:
159 return GIT.Capture(['config', key], cwd=cwd)
160 except subprocess2.CalledProcessError:
161 return default
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000162
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000163 @staticmethod
164 def GetBranchConfig(cwd, branch, key, default=None):
165 assert branch, 'A branch must be given'
166 key = 'branch.%s.%s' % (branch, key)
167 return GIT.GetConfig(cwd, key, default)
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000168
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000169 @staticmethod
170 def SetConfig(cwd, key, value=None):
171 if value is None:
172 args = ['config', '--unset', key]
173 else:
174 args = ['config', key, value]
175 GIT.Capture(args, cwd=cwd)
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000176
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000177 @staticmethod
178 def SetBranchConfig(cwd, branch, key, value=None):
179 assert branch, 'A branch must be given'
180 key = 'branch.%s.%s' % (branch, key)
181 GIT.SetConfig(cwd, key, value)
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000182
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000183 @staticmethod
184 def IsWorkTreeDirty(cwd):
185 return GIT.Capture(['status', '-s'], cwd=cwd) != ''
nodir@chromium.orgead4c7e2014-04-03 01:01:06 +0000186
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000187 @staticmethod
188 def GetEmail(cwd):
189 """Retrieves the user email address if known."""
190 return GIT.GetConfig(cwd, 'user.email', '')
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000191
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000192 @staticmethod
193 def ShortBranchName(branch):
194 """Converts a name like 'refs/heads/foo' to just 'foo'."""
195 return branch.replace('refs/heads/', '')
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000196
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000197 @staticmethod
198 def GetBranchRef(cwd):
199 """Returns the full branch reference, e.g. 'refs/heads/main'."""
200 try:
201 return GIT.Capture(['symbolic-ref', 'HEAD'], cwd=cwd)
202 except subprocess2.CalledProcessError:
203 return None
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000204
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000205 @staticmethod
206 def GetRemoteHeadRef(cwd, url, remote):
207 """Returns the full default remote branch reference, e.g.
Josip Sokcevic091f5ac2021-01-14 23:14:21 +0000208 'refs/remotes/origin/main'."""
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000209 if os.path.exists(cwd):
210 try:
211 # Try using local git copy first
212 ref = 'refs/remotes/%s/HEAD' % remote
213 ref = GIT.Capture(['symbolic-ref', ref], cwd=cwd)
214 if not ref.endswith('master'):
215 return ref
216 # Check if there are changes in the default branch for this
217 # particular repository.
218 GIT.Capture(['remote', 'set-head', '-a', remote], cwd=cwd)
219 return GIT.Capture(['symbolic-ref', ref], cwd=cwd)
220 except subprocess2.CalledProcessError:
221 pass
Josip Sokcevic091f5ac2021-01-14 23:14:21 +0000222
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000223 try:
224 # Fetch information from git server
225 resp = GIT.Capture(['ls-remote', '--symref', url, 'HEAD'])
226 regex = r'^ref: (.*)\tHEAD$'
227 for line in resp.split('\n'):
228 m = re.match(regex, line)
229 if m:
230 return ''.join(GIT.RefToRemoteRef(m.group(1), remote))
231 except subprocess2.CalledProcessError:
232 pass
233 # Return default branch
234 return 'refs/remotes/%s/main' % remote
Josip Sokcevic091f5ac2021-01-14 23:14:21 +0000235
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000236 @staticmethod
237 def GetBranch(cwd):
238 """Returns the short branch name, e.g. 'main'."""
239 branchref = GIT.GetBranchRef(cwd)
240 if branchref:
241 return GIT.ShortBranchName(branchref)
242 return None
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000243
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000244 @staticmethod
245 def GetRemoteBranches(cwd):
246 return GIT.Capture(['branch', '-r'], cwd=cwd).split()
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000247
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000248 @staticmethod
249 def FetchUpstreamTuple(cwd, branch=None):
250 """Returns a tuple containing remote and remote ref,
Josip Sokcevic9c0dc302020-11-20 18:41:25 +0000251 e.g. 'origin', 'refs/heads/main'
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000252 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000253 try:
254 branch = branch or GIT.GetBranch(cwd)
255 except subprocess2.CalledProcessError:
256 pass
257 if branch:
258 upstream_branch = GIT.GetBranchConfig(cwd, branch, 'merge')
259 if upstream_branch:
260 remote = GIT.GetBranchConfig(cwd, branch, 'remote', '.')
261 return remote, upstream_branch
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000262
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000263 upstream_branch = GIT.GetConfig(cwd, 'rietveld.upstream-branch')
264 if upstream_branch:
265 remote = GIT.GetConfig(cwd, 'rietveld.upstream-remote', '.')
266 return remote, upstream_branch
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000267
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000268 # Else, try to guess the origin remote.
269 remote_branches = GIT.GetRemoteBranches(cwd)
270 if 'origin/main' in remote_branches:
271 # Fall back on origin/main if it exits.
272 return 'origin', 'refs/heads/main'
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000273
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000274 if 'origin/master' in remote_branches:
275 # Fall back on origin/master if it exits.
276 return 'origin', 'refs/heads/master'
Edward Lemur15a9b8c2020-02-13 00:52:30 +0000277
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000278 return None, None
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000279
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000280 @staticmethod
281 def RefToRemoteRef(ref, remote):
282 """Convert a checkout ref to the equivalent remote ref.
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000283
284 Returns:
285 A tuple of the remote ref's (common prefix, unique suffix), or None if it
286 doesn't appear to refer to a remote ref (e.g. it's a commit hash).
287 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000288 # TODO(mmoss): This is just a brute-force mapping based of the expected
289 # git config. It's a bit better than the even more brute-force
290 # replace('heads', ...), but could still be smarter (like maybe actually
291 # using values gleaned from the git config).
292 m = re.match('^(refs/(remotes/)?)?branch-heads/', ref or '')
293 if m:
294 return ('refs/remotes/branch-heads/', ref.replace(m.group(0), ''))
Edward Lemur9a5e3bd2019-04-02 23:37:45 +0000295
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000296 m = re.match('^((refs/)?remotes/)?%s/|(refs/)?heads/' % remote, ref
297 or '')
298 if m:
299 return ('refs/remotes/%s/' % remote, ref.replace(m.group(0), ''))
Edward Lemur9a5e3bd2019-04-02 23:37:45 +0000300
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000301 return None
Edward Lemur9a5e3bd2019-04-02 23:37:45 +0000302
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000303 @staticmethod
304 def RemoteRefToRef(ref, remote):
305 assert remote, 'A remote must be given'
306 if not ref or not ref.startswith('refs/'):
307 return None
308 if not ref.startswith('refs/remotes/'):
309 return ref
310 if ref.startswith('refs/remotes/branch-heads/'):
311 return 'refs' + ref[len('refs/remotes'):]
312 if ref.startswith('refs/remotes/%s/' % remote):
313 return 'refs/heads' + ref[len('refs/remotes/%s' % remote):]
314 return None
mmoss@chromium.org6e7202b2014-09-09 18:23:39 +0000315
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000316 @staticmethod
317 def GetUpstreamBranch(cwd):
318 """Gets the current branch's upstream branch."""
319 remote, upstream_branch = GIT.FetchUpstreamTuple(cwd)
320 if remote != '.' and upstream_branch:
321 remote_ref = GIT.RefToRemoteRef(upstream_branch, remote)
322 if remote_ref:
323 upstream_branch = ''.join(remote_ref)
324 return upstream_branch
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000325
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000326 @staticmethod
327 def IsAncestor(maybe_ancestor, ref, cwd=None):
328 # type: (string, string, Optional[string]) -> bool
329 """Verifies if |maybe_ancestor| is an ancestor of |ref|."""
330 try:
331 GIT.Capture(['merge-base', '--is-ancestor', maybe_ancestor, ref],
332 cwd=cwd)
333 return True
334 except subprocess2.CalledProcessError:
335 return False
Edward Lemurca7d8812018-07-24 17:42:45 +0000336
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000337 @staticmethod
338 def GetOldContents(cwd, filename, branch=None):
339 if not branch:
340 branch = GIT.GetUpstreamBranch(cwd)
341 if platform.system() == 'Windows':
342 # git show <sha>:<path> wants a posix path.
343 filename = filename.replace('\\', '/')
344 command = ['show', '%s:%s' % (branch, filename)]
345 try:
346 return GIT.Capture(command, cwd=cwd, strip_out=False)
347 except subprocess2.CalledProcessError:
348 return ''
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700349
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000350 @staticmethod
351 def GenerateDiff(cwd,
352 branch=None,
353 branch_head='HEAD',
354 full_move=False,
355 files=None):
356 """Diffs against the upstream branch or optionally another branch.
maruel@chromium.orga9371762009-12-22 18:27:38 +0000357
358 full_move means that move or copy operations should completely recreate the
359 files, usually in the prospect to apply the patch for a try job."""
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000360 if not branch:
361 branch = GIT.GetUpstreamBranch(cwd)
362 command = [
363 '-c', 'core.quotePath=false', 'diff', '-p', '--no-color',
364 '--no-prefix', '--no-ext-diff', branch + "..." + branch_head
365 ]
366 if full_move:
367 command.append('--no-renames')
368 else:
369 command.append('-C')
370 # TODO(maruel): --binary support.
371 if files:
372 command.append('--')
373 command.extend(files)
374 diff = GIT.Capture(command, cwd=cwd, strip_out=False).splitlines(True)
375 for i in range(len(diff)):
376 # In the case of added files, replace /dev/null with the path to the
377 # file being added.
378 if diff[i].startswith('--- /dev/null'):
379 diff[i] = '--- %s' % diff[i + 1][4:]
380 return ''.join(diff)
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000381
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000382 @staticmethod
383 def GetDifferentFiles(cwd, branch=None, branch_head='HEAD'):
384 """Returns the list of modified files between two branches."""
385 if not branch:
386 branch = GIT.GetUpstreamBranch(cwd)
387 command = [
388 '-c', 'core.quotePath=false', 'diff', '--name-only',
389 branch + "..." + branch_head
390 ]
391 return GIT.Capture(command, cwd=cwd).splitlines(False)
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000392
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000393 @staticmethod
394 def GetAllFiles(cwd):
395 """Returns the list of all files under revision control."""
396 command = ['-c', 'core.quotePath=false', 'ls-files', '-s', '--', '.']
397 files = GIT.Capture(command, cwd=cwd).splitlines(False)
398 # return only files
399 return [f.split(maxsplit=3)[-1] for f in files if f.startswith('100')]
Edward Lemur98cfac12020-01-17 19:27:01 +0000400
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000401 @staticmethod
402 def GetSubmoduleCommits(cwd, submodules):
403 # type: (string, List[string]) => Mapping[string][string]
404 """Returns a mapping of staged or committed new commits for submodules."""
405 if not submodules:
406 return {}
407 result = subprocess2.check_output(['git', 'ls-files', '-s', '--'] +
408 submodules,
409 cwd=cwd).decode('utf-8')
410 commit_hashes = {}
411 for r in result.splitlines():
412 # ['<mode>', '<commit_hash>', '<stage_number>', '<path>'].
413 record = r.strip().split(maxsplit=3) # path can contain spaces.
414 assert record[0] == '160000', 'file is not a gitlink: %s' % record
415 commit_hashes[record[3]] = record[1]
416 return commit_hashes
Joanna Wange36c6bb2023-08-30 22:09:59 +0000417
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000418 @staticmethod
419 def GetPatchName(cwd):
420 """Constructs a name for this patch."""
421 short_sha = GIT.Capture(['rev-parse', '--short=4', 'HEAD'], cwd=cwd)
422 return "%s#%s" % (GIT.GetBranch(cwd), short_sha)
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000423
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000424 @staticmethod
425 def GetCheckoutRoot(cwd):
426 """Returns the top level directory of a git checkout as an absolute path.
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000427 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000428 root = GIT.Capture(['rev-parse', '--show-cdup'], cwd=cwd)
429 return os.path.abspath(os.path.join(cwd, root))
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000430
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000431 @staticmethod
432 def GetGitDir(cwd):
433 return os.path.abspath(GIT.Capture(['rev-parse', '--git-dir'], cwd=cwd))
nodir@chromium.orgead4c7e2014-04-03 01:01:06 +0000434
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000435 @staticmethod
436 def IsInsideWorkTree(cwd):
437 try:
438 return GIT.Capture(['rev-parse', '--is-inside-work-tree'], cwd=cwd)
439 except (OSError, subprocess2.CalledProcessError):
440 return False
nodir@chromium.orgead4c7e2014-04-03 01:01:06 +0000441
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000442 @staticmethod
443 def IsDirectoryVersioned(cwd, relative_dir):
444 """Checks whether the given |relative_dir| is part of cwd's repo."""
445 return bool(GIT.Capture(['ls-tree', 'HEAD', relative_dir], cwd=cwd))
primiano@chromium.org1c127382015-02-17 11:15:40 +0000446
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000447 @staticmethod
448 def CleanupDir(cwd, relative_dir):
449 """Cleans up untracked file inside |relative_dir|."""
450 return bool(GIT.Capture(['clean', '-df', relative_dir], cwd=cwd))
primiano@chromium.org1c127382015-02-17 11:15:40 +0000451
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000452 @staticmethod
453 def ResolveCommit(cwd, rev):
454 # We do this instead of rev-parse --verify rev^{commit}, since on
455 # Windows git can be either an executable or batch script, each of which
456 # requires escaping the caret (^) a different way.
457 if gclient_utils.IsFullGitSha(rev):
458 # git-rev parse --verify FULL_GIT_SHA always succeeds, even if we
459 # don't have FULL_GIT_SHA locally. Removing the last character
460 # forces git to check if FULL_GIT_SHA refers to an object in the
461 # local database.
462 rev = rev[:-1]
463 try:
464 return GIT.Capture(['rev-parse', '--quiet', '--verify', rev],
465 cwd=cwd)
466 except subprocess2.CalledProcessError:
467 return None
Edward Lemurd52edda2020-03-11 20:13:02 +0000468
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000469 @staticmethod
470 def IsValidRevision(cwd, rev, sha_only=False):
471 """Verifies the revision is a proper git revision.
ilevy@chromium.orga41249c2013-07-03 00:09:12 +0000472
473 sha_only: Fail unless rev is a sha hash.
474 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000475 sha = GIT.ResolveCommit(cwd, rev)
476 if sha is None:
477 return False
478 if sha_only:
479 return sha == rev.lower()
480 return True
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000481
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000482 @classmethod
483 def AssertVersion(cls, min_version):
484 """Asserts git's version is at least min_version."""
485 if cls.current_version is None:
486 current_version = cls.Capture(['--version'], '.')
487 matched = re.search(r'git version (.+)', current_version)
488 cls.current_version = distutils.version.LooseVersion(
489 matched.group(1))
490 min_version = distutils.version.LooseVersion(min_version)
491 return (min_version <= cls.current_version, cls.current_version)