blob: 4bac47dfcaef6907379a34091e7b41057caf209f [file] [log] [blame]
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001# Copyright 2014 The Chromium Authors. All rights reserved.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +00002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5# Monkeypatch IMapIterator so that Ctrl-C can kill everything properly.
6# Derived from https://gist.github.com/aljungberg/626518
Raul Tambrec2f74c12019-03-19 05:55:53 +00007
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +00008import multiprocessing.pool
Josip Sokcevicde6c4562020-03-26 00:39:42 +00009import sys
10import threading
11
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000012from multiprocessing.pool import IMapIterator
Josip Sokcevicde6c4562020-03-26 00:39:42 +000013
Aravind Vasudevanb8164182023-08-25 21:49:12 +000014from third_party import colorama
15
16
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000017def wrapper(func):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000018 def wrap(self, timeout=None):
19 return func(self, timeout=timeout or threading.TIMEOUT_MAX)
Josip Sokcevicde6c4562020-03-26 00:39:42 +000020
Mike Frysinger124bb8e2023-09-06 05:48:55 +000021 return wrap
22
23
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000024IMapIterator.next = wrapper(IMapIterator.next)
25IMapIterator.__next__ = IMapIterator.next
26# TODO(iannucci): Monkeypatch all other 'wait' methods too.
27
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000028import binascii
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000029import collections
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000030import contextlib
31import functools
32import logging
iannucci@chromium.org97345eb2014-03-13 07:55:15 +000033import os
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000034import re
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +000035import setup_color
sammc@chromium.org900a33f2015-09-29 06:57:09 +000036import shutil
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000037import signal
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000038import tempfile
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +000039import textwrap
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000040
41import subprocess2
42
Raul Tambrec2f74c12019-03-19 05:55:53 +000043from io import BytesIO
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000044
agable02b3c982016-06-22 07:51:22 -070045ROOT = os.path.abspath(os.path.dirname(__file__))
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +000046IS_WIN = sys.platform == 'win32'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000047TEST_MODE = False
48
Dan Jacques209a6812017-07-12 11:40:20 -070049
50def win_find_git():
Mike Frysinger124bb8e2023-09-06 05:48:55 +000051 for elem in os.environ.get('PATH', '').split(os.pathsep):
52 for candidate in ('git.exe', 'git.bat'):
53 path = os.path.join(elem, candidate)
54 if os.path.isfile(path):
55 return path
56 raise ValueError('Could not find Git on PATH.')
Dan Jacques209a6812017-07-12 11:40:20 -070057
58
59GIT_EXE = 'git' if not IS_WIN else win_find_git()
60
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000061FREEZE = 'FREEZE'
Mike Frysinger124bb8e2023-09-06 05:48:55 +000062FREEZE_SECTIONS = {'indexed': 'soft', 'unindexed': 'mixed'}
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000063FREEZE_MATCHER = re.compile(r'%s.(%s)' % (FREEZE, '|'.join(FREEZE_SECTIONS)))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000064
Dan Jacques2f8b0c12017-04-05 12:57:21 -070065# NOTE: This list is DEPRECATED in favor of the Infra Git wrapper:
Josip Sokcevic9c0dc302020-11-20 18:41:25 +000066# https://chromium.googlesource.com/infra/infra/+/HEAD/go/src/infra/tools/git
Dan Jacques2f8b0c12017-04-05 12:57:21 -070067#
68# New entries should be added to the Git wrapper, NOT to this list. "git_retry"
69# is, similarly, being deprecated in favor of the Git wrapper.
70#
71# ---
72#
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000073# Retry a git operation if git returns a error response with any of these
74# messages. It's all observed 'bad' GoB responses so far.
75#
76# This list is inspired/derived from the one in ChromiumOS's Chromite:
77# <CHROMITE>/lib/git.py::GIT_TRANSIENT_ERRORS
78#
79# It was last imported from '7add3ac29564d98ac35ce426bc295e743e7c0c02'.
80GIT_TRANSIENT_ERRORS = (
81 # crbug.com/285832
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000082 r'!.*\[remote rejected\].*\(error in hook\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000083
84 # crbug.com/289932
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000085 r'!.*\[remote rejected\].*\(failed to lock\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000086
87 # crbug.com/307156
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000088 r'!.*\[remote rejected\].*\(error in Gerrit backend\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000089
90 # crbug.com/285832
91 r'remote error: Internal Server Error',
92
93 # crbug.com/294449
94 r'fatal: Couldn\'t find remote ref ',
95
96 # crbug.com/220543
97 r'git fetch_pack: expected ACK/NAK, got',
98
99 # crbug.com/189455
100 r'protocol error: bad pack header',
101
102 # crbug.com/202807
103 r'The remote end hung up unexpectedly',
104
105 # crbug.com/298189
106 r'TLS packet with unexpected length was received',
107
108 # crbug.com/187444
109 r'RPC failed; result=\d+, HTTP code = \d+',
110
dnj@chromium.orgde219ec2014-07-28 17:39:08 +0000111 # crbug.com/388876
112 r'Connection timed out',
dnj@chromium.org45cddd62014-11-06 19:36:42 +0000113
114 # crbug.com/430343
115 # TODO(dnj): Resync with Chromite.
116 r'The requested URL returned error: 5\d+',
Arikonb3a21482016-07-22 10:12:24 -0700117 r'Connection reset by peer',
Arikonb3a21482016-07-22 10:12:24 -0700118 r'Unable to look up',
Arikonb3a21482016-07-22 10:12:24 -0700119 r'Couldn\'t resolve host',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +0000120)
121
122GIT_TRANSIENT_ERRORS_RE = re.compile('|'.join(GIT_TRANSIENT_ERRORS),
123 re.IGNORECASE)
124
raphael.kubo.da.costa@intel.com58d05b02015-06-24 08:54:41 +0000125# git's for-each-ref command first supported the upstream:track token in its
126# format string in version 1.9.0, but some usages were broken until 2.3.0.
127# See git commit b6160d95 for more information.
128MIN_UPSTREAM_TRACK_GIT_VERSION = (2, 3)
dnj@chromium.orgde219ec2014-07-28 17:39:08 +0000129
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000130
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000131class BadCommitRefException(Exception):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000132 def __init__(self, refs):
133 msg = ('one of %s does not seem to be a valid commitref.' % str(refs))
134 super(BadCommitRefException, self).__init__(msg)
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000135
136
137def memoize_one(**kwargs):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000138 """Memoizes a single-argument pure function.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000139
140 Values of None are not cached.
141
142 Kwargs:
143 threadsafe (bool) - REQUIRED. Specifies whether to use locking around
144 cache manipulation functions. This is a kwarg so that users of memoize_one
145 are forced to explicitly and verbosely pick True or False.
146
147 Adds three methods to the decorated function:
148 * get(key, default=None) - Gets the value for this key from the cache.
149 * set(key, value) - Sets the value for this key from the cache.
150 * clear() - Drops the entire contents of the cache. Useful for unittests.
151 * update(other) - Updates the contents of the cache from another dict.
152 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000153 assert 'threadsafe' in kwargs, 'Must specify threadsafe={True,False}'
154 threadsafe = kwargs['threadsafe']
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000155
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000156 if threadsafe:
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000157
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000158 def withlock(lock, f):
159 def inner(*args, **kwargs):
160 with lock:
161 return f(*args, **kwargs)
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000162
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000163 return inner
164 else:
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000165
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000166 def withlock(_lock, f):
167 return f
168
169 def decorator(f):
170 # Instantiate the lock in decorator, in case users of memoize_one do:
171 #
172 # memoizer = memoize_one(threadsafe=True)
173 #
174 # @memoizer
175 # def fn1(val): ...
176 #
177 # @memoizer
178 # def fn2(val): ...
179
180 lock = threading.Lock() if threadsafe else None
181 cache = {}
182 _get = withlock(lock, cache.get)
183 _set = withlock(lock, cache.__setitem__)
184
185 @functools.wraps(f)
186 def inner(arg):
187 ret = _get(arg)
188 if ret is None:
189 ret = f(arg)
190 if ret is not None:
191 _set(arg, ret)
192 return ret
193
194 inner.get = _get
195 inner.set = _set
196 inner.clear = withlock(lock, cache.clear)
197 inner.update = withlock(lock, cache.update)
198 return inner
199
200 return decorator
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000201
202
203def _ScopedPool_initer(orig, orig_args): # pragma: no cover
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000204 """Initializer method for ScopedPool's subprocesses.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000205
206 This helps ScopedPool handle Ctrl-C's correctly.
207 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000208 signal.signal(signal.SIGINT, signal.SIG_IGN)
209 if orig:
210 orig(*orig_args)
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000211
212
213@contextlib.contextmanager
214def ScopedPool(*args, **kwargs):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000215 """Context Manager which returns a multiprocessing.pool instance which
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000216 correctly deals with thrown exceptions.
217
218 *args - Arguments to multiprocessing.pool
219
220 Kwargs:
221 kind ('threads', 'procs') - The type of underlying coprocess to use.
222 **etc - Arguments to multiprocessing.pool
223 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000224 if kwargs.pop('kind', None) == 'threads':
225 pool = multiprocessing.pool.ThreadPool(*args, **kwargs)
226 else:
227 orig, orig_args = kwargs.get('initializer'), kwargs.get('initargs', ())
228 kwargs['initializer'] = _ScopedPool_initer
229 kwargs['initargs'] = orig, orig_args
230 pool = multiprocessing.pool.Pool(*args, **kwargs)
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000231
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000232 try:
233 yield pool
234 pool.close()
235 except:
236 pool.terminate()
237 raise
238 finally:
239 pool.join()
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000240
241
242class ProgressPrinter(object):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000243 """Threaded single-stat status message printer."""
244 def __init__(self, fmt, enabled=None, fout=sys.stderr, period=0.5):
245 """Create a ProgressPrinter.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000246
247 Use it as a context manager which produces a simple 'increment' method:
248
249 with ProgressPrinter('(%%(count)d/%d)' % 1000) as inc:
250 for i in xrange(1000):
251 # do stuff
252 if i % 10 == 0:
253 inc(10)
254
255 Args:
256 fmt - String format with a single '%(count)d' where the counter value
257 should go.
258 enabled (bool) - If this is None, will default to True if
259 logging.getLogger() is set to INFO or more verbose.
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000260 fout (file-like) - The stream to print status messages to.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000261 period (float) - The time in seconds for the printer thread to wait
262 between printing.
263 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000264 self.fmt = fmt
265 if enabled is None: # pragma: no cover
266 self.enabled = logging.getLogger().isEnabledFor(logging.INFO)
267 else:
268 self.enabled = enabled
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000269
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000270 self._count = 0
271 self._dead = False
272 self._dead_cond = threading.Condition()
273 self._stream = fout
274 self._thread = threading.Thread(target=self._run)
275 self._period = period
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000276
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000277 def _emit(self, s):
278 if self.enabled:
279 self._stream.write('\r' + s)
280 self._stream.flush()
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000281
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000282 def _run(self):
283 with self._dead_cond:
284 while not self._dead:
285 self._emit(self.fmt % {'count': self._count})
286 self._dead_cond.wait(self._period)
287 self._emit((self.fmt + '\n') % {'count': self._count})
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000288
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000289 def inc(self, amount=1):
290 self._count += amount
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000291
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000292 def __enter__(self):
293 self._thread.start()
294 return self.inc
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000295
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000296 def __exit__(self, _exc_type, _exc_value, _traceback):
297 self._dead = True
298 with self._dead_cond:
299 self._dead_cond.notifyAll()
300 self._thread.join()
301 del self._thread
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000302
303
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000304def once(function):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000305 """@Decorates |function| so that it only performs its action once, no matter
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000306 how many times the decorated |function| is called."""
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000307 has_run = [False]
308
309 def _wrapper(*args, **kwargs):
310 if not has_run[0]:
311 has_run[0] = True
312 function(*args, **kwargs)
313
314 return _wrapper
Edward Lemur12a537f2019-10-03 21:57:15 +0000315
316
317def unicode_repr(s):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000318 result = repr(s)
319 return result[1:] if result.startswith('u') else result
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000320
321
322## Git functions
323
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000324
agable7aa2ddd2016-06-21 07:47:00 -0700325def die(message, *args):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000326 print(textwrap.dedent(message % args), file=sys.stderr)
327 sys.exit(1)
agable7aa2ddd2016-06-21 07:47:00 -0700328
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000329
Mark Mentovaif548d082017-03-08 13:32:00 -0500330def blame(filename, revision=None, porcelain=False, abbrev=None, *_args):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000331 command = ['blame']
332 if porcelain:
333 command.append('-p')
334 if revision is not None:
335 command.append(revision)
336 if abbrev is not None:
337 command.append('--abbrev=%d' % abbrev)
338 command.extend(['--', filename])
339 return run(*command)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000340
341
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000342def branch_config(branch, option, default=None):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000343 return get_config('branch.%s.%s' % (branch, option), default=default)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000344
345
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000346def branch_config_map(option):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000347 """Return {branch: <|option| value>} for all branches."""
348 try:
349 reg = re.compile(r'^branch\.(.*)\.%s$' % option)
350 lines = get_config_regexp(reg.pattern)
351 return {reg.match(k).group(1): v for k, v in (l.split() for l in lines)}
352 except subprocess2.CalledProcessError:
353 return {}
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000354
355
Francois Dorayd42c6812017-05-30 15:10:20 -0400356def branches(use_limit=True, *args):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000357 NO_BRANCH = ('* (no branch', '* (detached', '* (HEAD detached')
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000358
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000359 key = 'depot-tools.branch-limit'
360 limit = get_config_int(key, 20)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000361
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000362 raw_branches = run('branch', *args).splitlines()
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000363
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000364 num = len(raw_branches)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000365
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000366 if use_limit and num > limit:
367 die(
368 """\
agable7aa2ddd2016-06-21 07:47:00 -0700369 Your git repo has too many branches (%d/%d) for this tool to work well.
370
371 You may adjust this limit by running:
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000372 git config %s <new_limit>
agable7aa2ddd2016-06-21 07:47:00 -0700373
374 You may also try cleaning up your old branches by running:
375 git cl archive
376 """, num, limit, key)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000377
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000378 for line in raw_branches:
379 if line.startswith(NO_BRANCH):
380 continue
381 yield line.split()[-1]
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000382
383
agable7aa2ddd2016-06-21 07:47:00 -0700384def get_config(option, default=None):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000385 try:
386 return run('config', '--get', option) or default
387 except subprocess2.CalledProcessError:
388 return default
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000389
390
agable7aa2ddd2016-06-21 07:47:00 -0700391def get_config_int(option, default=0):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000392 assert isinstance(default, int)
393 try:
394 return int(get_config(option, default))
395 except ValueError:
396 return default
agable7aa2ddd2016-06-21 07:47:00 -0700397
398
399def get_config_list(option):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000400 try:
401 return run('config', '--get-all', option).split()
402 except subprocess2.CalledProcessError:
403 return []
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000404
405
agable7aa2ddd2016-06-21 07:47:00 -0700406def get_config_regexp(pattern):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000407 if IS_WIN: # pragma: no cover
408 # this madness is because we call git.bat which calls git.exe which
409 # calls bash.exe (or something to that effect). Each layer divides the
410 # number of ^'s by 2.
411 pattern = pattern.replace('^', '^' * 8)
412 return run('config', '--get-regexp', pattern).splitlines()
agable7aa2ddd2016-06-21 07:47:00 -0700413
414
Aravind Vasudevanb8164182023-08-25 21:49:12 +0000415def is_fsmonitor_enabled():
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000416 """Returns true if core.fsmonitor is enabled in git config."""
417 fsmonitor = get_config('core.fsmonitor', 'False')
418 return fsmonitor.strip().lower() == 'true'
Aravind Vasudevanb8164182023-08-25 21:49:12 +0000419
420
421def warn_submodule():
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000422 """Print warnings for submodules."""
423 # TODO(crbug.com/1475405): Warn users if the project uses submodules and
424 # they have fsmonitor enabled.
425 if sys.platform.startswith('darwin') and is_fsmonitor_enabled():
Josip Sokcevicd95084e2023-09-25 23:45:56 +0000426 version_string = run('--version')
427 if version_string.endswith('goog'):
428 return
429 version_tuple = _extract_git_tuple(version_string)
430 if version_tuple >= (2, 43):
431 return
432
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000433 print(colorama.Fore.RED)
434 print('WARNING: You have fsmonitor enabled. There is a major issue '
435 'resulting in git diff-index returning wrong results. Please '
Thiago Perrotta32e73632023-10-04 16:44:26 +0000436 'either disable it by running:')
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000437 print(' git config core.fsmonitor false')
Thiago Perrotta32e73632023-10-04 16:44:26 +0000438 print('or upgrade git to version >= 2.43.')
439 print('See https://crbug.com/1475405 for details.')
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000440 print(colorama.Style.RESET_ALL)
Aravind Vasudevanb8164182023-08-25 21:49:12 +0000441
442
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000443def current_branch():
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000444 try:
445 return run('rev-parse', '--abbrev-ref', 'HEAD')
446 except subprocess2.CalledProcessError:
447 return None
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000448
449
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000450def del_branch_config(branch, option, scope='local'):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000451 del_config('branch.%s.%s' % (branch, option), scope=scope)
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000452
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000453
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000454def del_config(option, scope='local'):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000455 try:
456 run('config', '--' + scope, '--unset', option)
457 except subprocess2.CalledProcessError:
458 pass
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000459
460
mgiuca@chromium.org01d2cde2016-02-05 03:25:41 +0000461def diff(oldrev, newrev, *args):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000462 return run('diff', oldrev, newrev, *args)
mgiuca@chromium.org01d2cde2016-02-05 03:25:41 +0000463
464
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000465def freeze():
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000466 took_action = False
467 key = 'depot-tools.freeze-size-limit'
468 MB = 2**20
469 limit_mb = get_config_int(key, 100)
470 untracked_bytes = 0
agable02b3c982016-06-22 07:51:22 -0700471
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000472 root_path = repo_root()
iannuccieaca0332016-08-03 16:46:50 -0700473
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000474 # unindexed tracks all the files which are unindexed but we want to add to
475 # the `FREEZE.unindexed` commit.
476 unindexed = []
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000477
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000478 # will be set to true if there are any indexed files to commit.
479 have_indexed_files = False
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000480
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000481 for f, s in status(ignore_submodules='all'):
482 if is_unmerged(s):
483 die("Cannot freeze unmerged changes!")
484 if s.lstat not in ' ?':
485 # This covers all changes to indexed files.
486 # lstat = ' ' means that the file is tracked and modified, but
487 # wasn't added yet. lstat = '?' means that the file is untracked.
488 have_indexed_files = True
Aravind Vasudevanc71efb52023-08-29 23:02:15 +0000489
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000490 # If the file has both indexed and unindexed changes.
491 # rstat shows the status of the working tree. If the file also has
492 # changes in the working tree, it should be tracked both in indexed
493 # and unindexed changes.
494 if s.rstat != ' ':
495 unindexed.append(f.encode('utf-8'))
496 else:
497 unindexed.append(f.encode('utf-8'))
Aravind Vasudevanc71efb52023-08-29 23:02:15 +0000498
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000499 if s.lstat == '?' and limit_mb > 0:
500 untracked_bytes += os.lstat(os.path.join(root_path, f)).st_size
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000501
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000502 if limit_mb > 0 and untracked_bytes > limit_mb * MB:
503 die(
504 """\
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800505 You appear to have too much untracked+unignored data in your git
506 checkout: %.1f / %d MB.
agable02b3c982016-06-22 07:51:22 -0700507
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800508 Run `git status` to see what it is.
agable02b3c982016-06-22 07:51:22 -0700509
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800510 In addition to making many git commands slower, this will prevent
511 depot_tools from freezing your in-progress changes.
agable02b3c982016-06-22 07:51:22 -0700512
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800513 You should add untracked data that you want to ignore to your repo's
514 .git/info/exclude
515 file. See `git help ignore` for the format of this file.
agable02b3c982016-06-22 07:51:22 -0700516
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000517 If this data is intended as part of your commit, you may adjust the
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800518 freeze limit by running:
519 git config %s <new_limit>
520 Where <new_limit> is an integer threshold in megabytes.""",
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000521 untracked_bytes / (MB * 1.0), limit_mb, key)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000522
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000523 if have_indexed_files:
524 try:
525 run('commit', '--no-verify', '-m', f'{FREEZE}.indexed')
526 took_action = True
527 except subprocess2.CalledProcessError:
528 pass
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000529
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000530 add_errors = False
531 if unindexed:
532 try:
533 run('add',
534 '--pathspec-from-file',
535 '-',
536 '--ignore-errors',
537 indata=b'\n'.join(unindexed),
538 cwd=root_path)
539 except subprocess2.CalledProcessError:
540 add_errors = True
agable96e179b2016-06-24 10:32:51 -0700541
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000542 try:
543 run('commit', '--no-verify', '-m', f'{FREEZE}.unindexed')
544 took_action = True
545 except subprocess2.CalledProcessError:
546 pass
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000547
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000548 ret = []
549 if add_errors:
550 ret.append('Failed to index some unindexed files.')
551 if not took_action:
552 ret.append('Nothing to freeze.')
553 return ' '.join(ret) or None
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000554
555
Gavin Mak2cbe95c2023-03-06 22:39:56 +0000556def get_branch_tree(use_limit=False):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000557 """Get the dictionary of {branch: parent}, compatible with topo_iter.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000558
559 Returns a tuple of (skipped, <branch_tree dict>) where skipped is a set of
560 branches without upstream branches defined.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000561 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000562 skipped = set()
563 branch_tree = {}
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000564
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000565 for branch in branches(use_limit=use_limit):
566 parent = upstream(branch)
567 if not parent:
568 skipped.add(branch)
569 continue
570 branch_tree[branch] = parent
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000571
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000572 return skipped, branch_tree
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000573
574
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000575def get_or_create_merge_base(branch, parent=None):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000576 """Finds the configured merge base for branch.
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000577
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000578 If parent is supplied, it's used instead of calling upstream(branch).
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000579 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000580 base = branch_config(branch, 'base')
581 base_upstream = branch_config(branch, 'base-upstream')
582 parent = parent or upstream(branch)
583 if parent is None or branch is None:
584 return None
585 actual_merge_base = run('merge-base', parent, branch)
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000586
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000587 if base_upstream != parent:
588 base = None
589 base_upstream = None
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000590
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000591 def is_ancestor(a, b):
592 return run_with_retcode('merge-base', '--is-ancestor', a, b) == 0
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000593
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000594 if base and base != actual_merge_base:
595 if not is_ancestor(base, branch):
596 logging.debug('Found WRONG pre-set merge-base for %s: %s', branch,
597 base)
598 base = None
599 elif is_ancestor(base, actual_merge_base):
600 logging.debug('Found OLD pre-set merge-base for %s: %s', branch,
601 base)
602 base = None
603 else:
604 logging.debug('Found pre-set merge-base for %s: %s', branch, base)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000605
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000606 if not base:
607 base = actual_merge_base
608 manual_merge_base(branch, base, parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000609
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000610 return base
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000611
612
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000613def hash_multi(*reflike):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000614 return run('rev-parse', *reflike).splitlines()
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000615
616
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000617def hash_one(reflike, short=False):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000618 args = ['rev-parse', reflike]
619 if short:
620 args.insert(1, '--short')
621 return run(*args)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000622
623
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000624def in_rebase():
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000625 git_dir = run('rev-parse', '--git-dir')
626 return (os.path.exists(os.path.join(git_dir, 'rebase-merge'))
627 or os.path.exists(os.path.join(git_dir, 'rebase-apply')))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000628
629
630def intern_f(f, kind='blob'):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000631 """Interns a file object into the git object store.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000632
633 Args:
634 f (file-like object) - The file-like object to intern
635 kind (git object type) - One of 'blob', 'commit', 'tree', 'tag'.
636
637 Returns the git hash of the interned object (hex encoded).
638 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000639 ret = run('hash-object', '-t', kind, '-w', '--stdin', stdin=f)
640 f.close()
641 return ret
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000642
643
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000644def is_dormant(branch):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000645 # TODO(iannucci): Do an oldness check?
646 return branch_config(branch, 'dormant', 'false') != 'false'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000647
648
agable02b3c982016-06-22 07:51:22 -0700649def is_unmerged(stat_value):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000650 return ('U' in (stat_value.lstat, stat_value.rstat)
651 or ((stat_value.lstat == stat_value.rstat)
652 and stat_value.lstat in 'AD'))
agable02b3c982016-06-22 07:51:22 -0700653
654
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000655def manual_merge_base(branch, base, parent):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000656 set_branch_config(branch, 'base', base)
657 set_branch_config(branch, 'base-upstream', parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000658
659
660def mktree(treedict):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000661 """Makes a git tree object and returns its hash.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000662
663 See |tree()| for the values of mode, type, and ref.
664
665 Args:
666 treedict - { name: (mode, type, ref) }
667 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000668 with tempfile.TemporaryFile() as f:
669 for name, (mode, typ, ref) in treedict.items():
670 f.write(('%s %s %s\t%s\0' % (mode, typ, ref, name)).encode('utf-8'))
671 f.seek(0)
672 return run('mktree', '-z', stdin=f)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000673
674
675def parse_commitrefs(*commitrefs):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000676 """Returns binary encoded commit hashes for one or more commitrefs.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000677
678 A commitref is anything which can resolve to a commit. Popular examples:
679 * 'HEAD'
Josip Sokcevic9c0dc302020-11-20 18:41:25 +0000680 * 'origin/main'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000681 * 'cool_branch~2'
682 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000683 try:
684 return [binascii.unhexlify(h) for h in hash_multi(*commitrefs)]
685 except subprocess2.CalledProcessError:
686 raise BadCommitRefException(commitrefs)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000687
688
sbc@chromium.org384039b2014-10-13 21:01:00 +0000689RebaseRet = collections.namedtuple('RebaseRet', 'success stdout stderr')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000690
691
Robert Iannuccid3acb162021-05-04 21:37:40 +0000692def rebase(parent, start, branch, abort=False, allow_gc=False):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000693 """Rebases |start|..|branch| onto the branch |parent|.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000694
Robert Iannuccid3acb162021-05-04 21:37:40 +0000695 Sets 'gc.auto=0' for the duration of this call to prevent the rebase from
696 running a potentially slow garbage collection cycle.
697
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000698 Args:
699 parent - The new parent ref for the rebased commits.
700 start - The commit to start from
701 branch - The branch to rebase
702 abort - If True, will call git-rebase --abort in the event that the rebase
703 doesn't complete successfully.
Robert Iannuccid3acb162021-05-04 21:37:40 +0000704 allow_gc - If True, sets "-c gc.auto=1" on the rebase call, rather than
705 "-c gc.auto=0". Usually if you're doing a series of rebases,
706 you'll only want to run a single gc pass at the end of all the
707 rebase activity.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000708
709 Returns a namedtuple with fields:
710 success - a boolean indicating that the rebase command completed
711 successfully.
712 message - if the rebase failed, this contains the stdout of the failed
713 rebase.
714 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000715 try:
716 args = [
717 '-c',
718 'gc.auto={}'.format('1' if allow_gc else '0'),
719 'rebase',
720 ]
721 if TEST_MODE:
722 args.append('--committer-date-is-author-date')
723 args += [
724 '--onto',
725 parent,
726 start,
727 branch,
728 ]
729 run(*args)
730 return RebaseRet(True, '', '')
731 except subprocess2.CalledProcessError as cpe:
732 if abort:
733 run_with_retcode('rebase', '--abort') # ignore failure
734 return RebaseRet(False, cpe.stdout.decode('utf-8', 'replace'),
735 cpe.stderr.decode('utf-8', 'replace'))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000736
737
738def remove_merge_base(branch):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000739 del_branch_config(branch, 'base')
740 del_branch_config(branch, 'base-upstream')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000741
742
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000743def repo_root():
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000744 """Returns the absolute path to the repository root."""
745 return run('rev-parse', '--show-toplevel')
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000746
747
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000748def upstream_default():
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000749 """Returns the default branch name of the origin repository."""
750 try:
Josip Sokcevic06423732021-03-31 19:04:42 +0000751 ret = run('rev-parse', '--abbrev-ref', 'origin/HEAD')
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000752 # Detect if the repository migrated to main branch
753 if ret == 'origin/master':
754 try:
755 ret = run('rev-parse', '--abbrev-ref', 'origin/main')
756 run('remote', 'set-head', '-a', 'origin')
757 ret = run('rev-parse', '--abbrev-ref', 'origin/HEAD')
758 except subprocess2.CalledProcessError:
759 pass
760 return ret
761 except subprocess2.CalledProcessError:
762 return 'origin/main'
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000763
764
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000765def root():
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000766 return get_config('depot-tools.upstream', upstream_default())
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000767
768
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000769@contextlib.contextmanager
770def less(): # pragma: no cover
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000771 """Runs 'less' as context manager yielding its stdin as a PIPE.
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000772
773 Automatically checks if sys.stdout is a non-TTY stream. If so, it avoids
774 running less and just yields sys.stdout.
Edward Lemur0d462e92020-01-08 20:11:31 +0000775
776 The returned PIPE is opened on binary mode.
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000777 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000778 if not setup_color.IS_TTY:
779 # On Python 3, sys.stdout doesn't accept bytes, and sys.stdout.buffer
780 # must be used.
781 yield getattr(sys.stdout, 'buffer', sys.stdout)
782 return
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000783
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000784 # Run with the same options that git uses (see setup_pager in git repo).
785 # -F: Automatically quit if the output is less than one screen.
786 # -R: Don't escape ANSI color codes.
787 # -X: Don't clear the screen before starting.
788 cmd = ('less', '-FRX')
Edward Lemurb800fde2020-01-10 23:04:44 +0000789 try:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000790 proc = subprocess2.Popen(cmd, stdin=subprocess2.PIPE)
791 yield proc.stdin
792 finally:
793 try:
794 proc.stdin.close()
795 except BrokenPipeError:
796 # BrokenPipeError is raised if proc has already completed,
797 pass
798 proc.wait()
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000799
800
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000801def run(*cmd, **kwargs):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000802 """The same as run_with_stderr, except it only returns stdout."""
803 return run_with_stderr(*cmd, **kwargs)[0]
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000804
805
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000806def run_with_retcode(*cmd, **kwargs):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000807 """Run a command but only return the status code."""
808 try:
809 run(*cmd, **kwargs)
810 return 0
811 except subprocess2.CalledProcessError as cpe:
812 return cpe.returncode
813
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000814
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000815def run_stream(*cmd, **kwargs):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000816 """Runs a git command. Returns stdout as a PIPE (file-like object).
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000817
818 stderr is dropped to avoid races if the process outputs to both stdout and
819 stderr.
820 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000821 kwargs.setdefault('stderr', subprocess2.DEVNULL)
822 kwargs.setdefault('stdout', subprocess2.PIPE)
823 kwargs.setdefault('shell', False)
824 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
825 proc = subprocess2.Popen(cmd, **kwargs)
826 return proc.stdout
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000827
828
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000829@contextlib.contextmanager
830def run_stream_with_retcode(*cmd, **kwargs):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000831 """Runs a git command as context manager yielding stdout as a PIPE.
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000832
833 stderr is dropped to avoid races if the process outputs to both stdout and
834 stderr.
835
836 Raises subprocess2.CalledProcessError on nonzero return code.
837 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000838 kwargs.setdefault('stderr', subprocess2.DEVNULL)
839 kwargs.setdefault('stdout', subprocess2.PIPE)
840 kwargs.setdefault('shell', False)
841 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
842 try:
843 proc = subprocess2.Popen(cmd, **kwargs)
844 yield proc.stdout
845 finally:
846 retcode = proc.wait()
847 if retcode != 0:
848 raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(), b'',
849 b'')
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000850
851
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000852def run_with_stderr(*cmd, **kwargs):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000853 """Runs a git command.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000854
855 Returns (stdout, stderr) as a pair of strings.
856
857 kwargs
858 autostrip (bool) - Strip the output. Defaults to True.
859 indata (str) - Specifies stdin data for the process.
860 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000861 kwargs.setdefault('stdin', subprocess2.PIPE)
862 kwargs.setdefault('stdout', subprocess2.PIPE)
863 kwargs.setdefault('stderr', subprocess2.PIPE)
864 kwargs.setdefault('shell', False)
865 autostrip = kwargs.pop('autostrip', True)
866 indata = kwargs.pop('indata', None)
867 decode = kwargs.pop('decode', True)
868 accepted_retcodes = kwargs.pop('accepted_retcodes', [0])
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000869
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000870 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
871 proc = subprocess2.Popen(cmd, **kwargs)
872 ret, err = proc.communicate(indata)
873 retcode = proc.wait()
874 if retcode not in accepted_retcodes:
875 raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(), ret,
876 err)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000877
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000878 if autostrip:
879 ret = (ret or b'').strip()
880 err = (err or b'').strip()
Edward Lemur12a537f2019-10-03 21:57:15 +0000881
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000882 if decode:
883 ret = ret.decode('utf-8', 'replace')
884 err = err.decode('utf-8', 'replace')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000885
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000886 return ret, err
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000887
888
889def set_branch_config(branch, option, value, scope='local'):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000890 set_config('branch.%s.%s' % (branch, option), value, scope=scope)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000891
892
893def set_config(option, value, scope='local'):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000894 run('config', '--' + scope, option, value)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000895
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000896
sbc@chromium.org71437c02015-04-09 19:29:40 +0000897def get_dirty_files():
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000898 # Make sure index is up-to-date before running diff-index.
899 run_with_retcode('update-index', '--refresh', '-q')
900 return run('diff-index', '--ignore-submodules', '--name-status', 'HEAD')
sbc@chromium.org71437c02015-04-09 19:29:40 +0000901
902
903def is_dirty_git_tree(cmd):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000904 w = lambda s: sys.stderr.write(s + "\n")
iannuccie38699b2016-08-15 17:32:31 -0700905
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000906 dirty = get_dirty_files()
907 if dirty:
908 w('Cannot %s with a dirty tree. Commit%s or stash your changes first.' %
909 (cmd, '' if cmd == 'upload' else ', freeze'))
910 w('Uncommitted files: (git diff-index --name-status HEAD)')
911 w(dirty[:4096])
912 if len(dirty) > 4096: # pragma: no cover
913 w('... (run "git diff-index --name-status HEAD" to see full '
914 'output).')
915 return True
916 return False
sbc@chromium.org71437c02015-04-09 19:29:40 +0000917
918
Greg NISBET923bcf82023-08-10 22:50:46 +0000919def status(ignore_submodules=None):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000920 """Returns a parsed version of git-status.
agable02b3c982016-06-22 07:51:22 -0700921
Greg NISBET923bcf82023-08-10 22:50:46 +0000922 Args:
923 ignore_submodules (str|None): "all", "none", or None.
924 None is equivalent to "none".
925
agable02b3c982016-06-22 07:51:22 -0700926 Returns a generator of (current_name, (lstat, rstat, src)) pairs where:
927 * current_name is the name of the file
928 * lstat is the left status code letter from git-status
Aravind Vasudevanc71efb52023-08-29 23:02:15 +0000929 * rstat is the right status code letter from git-status
agable02b3c982016-06-22 07:51:22 -0700930 * src is the current name of the file, or the original name of the file
931 if lstat == 'R'
932 """
Greg NISBET923bcf82023-08-10 22:50:46 +0000933
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000934 ignore_submodules = ignore_submodules or 'none'
935 assert ignore_submodules in (
936 'all',
937 'none'), f'ignore_submodules value {ignore_submodules} is invalid'
Greg NISBET923bcf82023-08-10 22:50:46 +0000938
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000939 stat_entry = collections.namedtuple('stat_entry', 'lstat rstat src')
agable02b3c982016-06-22 07:51:22 -0700940
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000941 def tokenizer(stream):
942 acc = BytesIO()
943 c = None
944 while c != b'':
945 c = stream.read(1)
946 if c in (None, b'', b'\0'):
947 if len(acc.getvalue()) > 0:
948 yield acc.getvalue()
949 acc = BytesIO()
950 else:
951 acc.write(c)
agable02b3c982016-06-22 07:51:22 -0700952
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000953 def parser(tokens):
954 while True:
955 try:
956 status_dest = next(tokens).decode('utf-8')
957 except StopIteration:
958 return
959 stat, dest = status_dest[:2], status_dest[3:]
960 lstat, rstat = stat
961 if lstat == 'R':
962 src = next(tokens).decode('utf-8')
963 else:
964 src = dest
965 yield (dest, stat_entry(lstat, rstat, src))
agable02b3c982016-06-22 07:51:22 -0700966
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000967 return parser(
968 tokenizer(
969 run_stream('status',
970 '-z',
971 f'--ignore-submodules={ignore_submodules}',
972 bufsize=-1)))
agable02b3c982016-06-22 07:51:22 -0700973
974
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000975def squash_current_branch(header=None, merge_base=None):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000976 header = header or 'git squash commit for %s.' % current_branch()
977 merge_base = merge_base or get_or_create_merge_base(current_branch())
978 log_msg = header + '\n'
979 if log_msg:
980 log_msg += '\n'
981 log_msg += run('log', '--reverse', '--format=%H%n%B',
982 '%s..HEAD' % merge_base)
983 run('reset', '--soft', merge_base)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000984
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000985 if not get_dirty_files():
986 # Sometimes the squash can result in the same tree, meaning that there
987 # is nothing to commit at this point.
988 print('Nothing to commit; squashed branch is empty')
989 return False
Josip Sokcevic4a442842023-09-13 20:42:53 +0000990
991 # git reset --soft will stage all changes so we can just commit those.
992 # Note: Just before reset --soft is called, we may have git submodules
993 # checked to an old commit (not latest state). We don't want to include
994 # those in our commit.
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000995 run('commit',
996 '--no-verify',
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000997 '-F',
998 '-',
999 indata=log_msg.encode('utf-8'))
1000 return True
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001001
1002
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +00001003def tags(*args):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001004 return run('tag', *args).splitlines()
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +00001005
1006
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001007def thaw():
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001008 took_action = False
1009 with run_stream('rev-list', 'HEAD') as stream:
1010 for sha in stream:
1011 sha = sha.strip().decode('utf-8')
1012 msg = run('show', '--format=%f%b', '-s', 'HEAD')
1013 match = FREEZE_MATCHER.match(msg)
1014 if not match:
1015 if not took_action:
1016 return 'Nothing to thaw.'
1017 break
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001018
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001019 run('reset', '--' + FREEZE_SECTIONS[match.group(1)], sha)
1020 took_action = True
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001021
1022
1023def topo_iter(branch_tree, top_down=True):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001024 """Generates (branch, parent) in topographical order for a branch tree.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001025
1026 Given a tree:
1027
1028 A1
1029 B1 B2
1030 C1 C2 C3
1031 D1
1032
1033 branch_tree would look like: {
1034 'D1': 'C3',
1035 'C3': 'B2',
1036 'B2': 'A1',
1037 'C1': 'B1',
1038 'C2': 'B1',
1039 'B1': 'A1',
1040 }
1041
1042 It is OK to have multiple 'root' nodes in your graph.
1043
1044 if top_down is True, items are yielded from A->D. Otherwise they're yielded
1045 from D->A. Within a layer the branches will be yielded in sorted order.
1046 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001047 branch_tree = branch_tree.copy()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001048
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001049 # TODO(iannucci): There is probably a more efficient way to do these.
1050 if top_down:
1051 while branch_tree:
1052 this_pass = [(b, p) for b, p in branch_tree.items()
1053 if p not in branch_tree]
1054 assert this_pass, "Branch tree has cycles: %r" % branch_tree
1055 for branch, parent in sorted(this_pass):
1056 yield branch, parent
1057 del branch_tree[branch]
1058 else:
1059 parent_to_branches = collections.defaultdict(set)
1060 for branch, parent in branch_tree.items():
1061 parent_to_branches[parent].add(branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001062
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001063 while branch_tree:
1064 this_pass = [(b, p) for b, p in branch_tree.items()
1065 if not parent_to_branches[b]]
1066 assert this_pass, "Branch tree has cycles: %r" % branch_tree
1067 for branch, parent in sorted(this_pass):
1068 yield branch, parent
1069 parent_to_branches[parent].discard(branch)
1070 del branch_tree[branch]
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001071
1072
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +00001073def tree(treeref, recurse=False):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001074 """Returns a dict representation of a git tree object.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +00001075
1076 Args:
1077 treeref (str) - a git ref which resolves to a tree (commits count as trees).
qyearsley12fa6ff2016-08-24 09:18:40 -07001078 recurse (bool) - include all of the tree's descendants too. File names will
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +00001079 take the form of 'some/path/to/file'.
1080
1081 Return format:
1082 { 'file_name': (mode, type, ref) }
1083
1084 mode is an integer where:
1085 * 0040000 - Directory
1086 * 0100644 - Regular non-executable file
1087 * 0100664 - Regular non-executable group-writeable file
1088 * 0100755 - Regular executable file
1089 * 0120000 - Symbolic link
1090 * 0160000 - Gitlink
1091
1092 type is a string where it's one of 'blob', 'commit', 'tree', 'tag'.
1093
1094 ref is the hex encoded hash of the entry.
1095 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001096 ret = {}
1097 opts = ['ls-tree', '--full-tree']
1098 if recurse:
1099 opts.append('-r')
1100 opts.append(treeref)
1101 try:
1102 for line in run(*opts).splitlines():
1103 mode, typ, ref, name = line.split(None, 3)
1104 ret[name] = (mode, typ, ref)
1105 except subprocess2.CalledProcessError:
1106 return None
1107 return ret
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +00001108
1109
Mun Yong Jang781e71e2017-10-25 15:46:20 -07001110def get_remote_url(remote='origin'):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001111 try:
1112 return run('config', 'remote.%s.url' % remote)
1113 except subprocess2.CalledProcessError:
1114 return None
Mun Yong Jang781e71e2017-10-25 15:46:20 -07001115
1116
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +00001117def upstream(branch):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001118 try:
1119 return run('rev-parse', '--abbrev-ref', '--symbolic-full-name',
1120 branch + '@{upstream}')
1121 except subprocess2.CalledProcessError:
1122 return None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001123
agable@chromium.orgd629fb42014-10-01 09:40:10 +00001124
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001125def get_git_version():
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001126 """Returns a tuple that contains the numeric components of the current git
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001127 version."""
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001128 version_string = run('--version')
Josip Sokcevicd95084e2023-09-25 23:45:56 +00001129 return _extract_git_tuple(version_string)
1130
1131
1132def _extract_git_tuple(version_string):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001133 version_match = re.search(r'(\d+.)+(\d+)', version_string)
1134 version = version_match.group() if version_match else ''
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001135
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001136 return tuple(int(x) for x in version.split('.'))
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001137
1138
calamity@chromium.org745ffa62014-09-08 01:03:19 +00001139def get_branches_info(include_tracking_status):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001140 format_string = (
1141 '--format=%(refname:short):%(objectname:short):%(upstream:short):')
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001142
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001143 # This is not covered by the depot_tools CQ which only has git version 1.8.
1144 if (include_tracking_status and get_git_version() >=
1145 MIN_UPSTREAM_TRACK_GIT_VERSION): # pragma: no cover
1146 format_string += '%(upstream:track)'
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001147
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001148 info_map = {}
1149 data = run('for-each-ref', format_string, 'refs/heads')
1150 BranchesInfo = collections.namedtuple('BranchesInfo',
1151 'hash upstream commits behind')
1152 for line in data.splitlines():
1153 (branch, branch_hash, upstream_branch,
1154 tracking_status) = line.split(':')
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001155
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001156 commits = None
1157 if include_tracking_status:
1158 base = get_or_create_merge_base(branch)
1159 if base:
1160 commits_list = run('rev-list', '--count', branch, '^%s' % base,
1161 '--')
1162 commits = int(commits_list) or None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001163
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001164 behind_match = re.search(r'behind (\d+)', tracking_status)
1165 behind = int(behind_match.group(1)) if behind_match else None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001166
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001167 info_map[branch] = BranchesInfo(hash=branch_hash,
1168 upstream=upstream_branch,
1169 commits=commits,
1170 behind=behind)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001171
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001172 # Set None for upstreams which are not branches (e.g empty upstream, remotes
1173 # and deleted upstream branches).
1174 missing_upstreams = {}
1175 for info in info_map.values():
1176 if (info.upstream not in info_map
1177 and info.upstream not in missing_upstreams):
1178 missing_upstreams[info.upstream] = None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001179
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001180 result = info_map.copy()
1181 result.update(missing_upstreams)
1182 return result
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001183
1184
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001185def make_workdir_common(repository,
1186 new_workdir,
1187 files_to_symlink,
1188 files_to_copy,
1189 symlink=None):
1190 if not symlink:
1191 symlink = os.symlink
1192 os.makedirs(new_workdir)
1193 for entry in files_to_symlink:
1194 clone_file(repository, new_workdir, entry, symlink)
1195 for entry in files_to_copy:
1196 clone_file(repository, new_workdir, entry, shutil.copy)
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001197
1198
1199def make_workdir(repository, new_workdir):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001200 GIT_DIRECTORY_WHITELIST = [
1201 'config',
1202 'info',
1203 'hooks',
1204 'logs/refs',
1205 'objects',
1206 'packed-refs',
1207 'refs',
1208 'remotes',
1209 'rr-cache',
1210 'shallow',
1211 ]
1212 make_workdir_common(repository, new_workdir, GIT_DIRECTORY_WHITELIST,
1213 ['HEAD'])
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001214
1215
1216def clone_file(repository, new_workdir, link, operation):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001217 if not os.path.exists(os.path.join(repository, link)):
1218 return
1219 link_dir = os.path.dirname(os.path.join(new_workdir, link))
1220 if not os.path.exists(link_dir):
1221 os.makedirs(link_dir)
1222 src = os.path.join(repository, link)
1223 if os.path.islink(src):
1224 src = os.path.realpath(src)
1225 operation(src, os.path.join(new_workdir, link))