blob: 592e9313e7eeb8fb9703263022f0dc4dcb8bdfd5 [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():
426 print(colorama.Fore.RED)
427 print('WARNING: You have fsmonitor enabled. There is a major issue '
428 'resulting in git diff-index returning wrong results. Please '
429 'disable it by running:')
430 print(' git config core.fsmonitor false')
431 print('We will remove this warning once https://crbug.com/1475405 is '
432 'fixed.')
433 print(colorama.Style.RESET_ALL)
Aravind Vasudevanb8164182023-08-25 21:49:12 +0000434
435
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000436def current_branch():
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000437 try:
438 return run('rev-parse', '--abbrev-ref', 'HEAD')
439 except subprocess2.CalledProcessError:
440 return None
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000441
442
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000443def del_branch_config(branch, option, scope='local'):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000444 del_config('branch.%s.%s' % (branch, option), scope=scope)
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000445
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000446
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000447def del_config(option, scope='local'):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000448 try:
449 run('config', '--' + scope, '--unset', option)
450 except subprocess2.CalledProcessError:
451 pass
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000452
453
mgiuca@chromium.org01d2cde2016-02-05 03:25:41 +0000454def diff(oldrev, newrev, *args):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000455 return run('diff', oldrev, newrev, *args)
mgiuca@chromium.org01d2cde2016-02-05 03:25:41 +0000456
457
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000458def freeze():
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000459 took_action = False
460 key = 'depot-tools.freeze-size-limit'
461 MB = 2**20
462 limit_mb = get_config_int(key, 100)
463 untracked_bytes = 0
agable02b3c982016-06-22 07:51:22 -0700464
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000465 root_path = repo_root()
iannuccieaca0332016-08-03 16:46:50 -0700466
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000467 # unindexed tracks all the files which are unindexed but we want to add to
468 # the `FREEZE.unindexed` commit.
469 unindexed = []
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000470
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000471 # will be set to true if there are any indexed files to commit.
472 have_indexed_files = False
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000473
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000474 for f, s in status(ignore_submodules='all'):
475 if is_unmerged(s):
476 die("Cannot freeze unmerged changes!")
477 if s.lstat not in ' ?':
478 # This covers all changes to indexed files.
479 # lstat = ' ' means that the file is tracked and modified, but
480 # wasn't added yet. lstat = '?' means that the file is untracked.
481 have_indexed_files = True
Aravind Vasudevanc71efb52023-08-29 23:02:15 +0000482
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000483 # If the file has both indexed and unindexed changes.
484 # rstat shows the status of the working tree. If the file also has
485 # changes in the working tree, it should be tracked both in indexed
486 # and unindexed changes.
487 if s.rstat != ' ':
488 unindexed.append(f.encode('utf-8'))
489 else:
490 unindexed.append(f.encode('utf-8'))
Aravind Vasudevanc71efb52023-08-29 23:02:15 +0000491
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000492 if s.lstat == '?' and limit_mb > 0:
493 untracked_bytes += os.lstat(os.path.join(root_path, f)).st_size
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000494
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000495 if limit_mb > 0 and untracked_bytes > limit_mb * MB:
496 die(
497 """\
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800498 You appear to have too much untracked+unignored data in your git
499 checkout: %.1f / %d MB.
agable02b3c982016-06-22 07:51:22 -0700500
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800501 Run `git status` to see what it is.
agable02b3c982016-06-22 07:51:22 -0700502
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800503 In addition to making many git commands slower, this will prevent
504 depot_tools from freezing your in-progress changes.
agable02b3c982016-06-22 07:51:22 -0700505
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800506 You should add untracked data that you want to ignore to your repo's
507 .git/info/exclude
508 file. See `git help ignore` for the format of this file.
agable02b3c982016-06-22 07:51:22 -0700509
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000510 If this data is intended as part of your commit, you may adjust the
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800511 freeze limit by running:
512 git config %s <new_limit>
513 Where <new_limit> is an integer threshold in megabytes.""",
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000514 untracked_bytes / (MB * 1.0), limit_mb, key)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000515
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000516 if have_indexed_files:
517 try:
518 run('commit', '--no-verify', '-m', f'{FREEZE}.indexed')
519 took_action = True
520 except subprocess2.CalledProcessError:
521 pass
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000522
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000523 add_errors = False
524 if unindexed:
525 try:
526 run('add',
527 '--pathspec-from-file',
528 '-',
529 '--ignore-errors',
530 indata=b'\n'.join(unindexed),
531 cwd=root_path)
532 except subprocess2.CalledProcessError:
533 add_errors = True
agable96e179b2016-06-24 10:32:51 -0700534
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000535 try:
536 run('commit', '--no-verify', '-m', f'{FREEZE}.unindexed')
537 took_action = True
538 except subprocess2.CalledProcessError:
539 pass
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000540
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000541 ret = []
542 if add_errors:
543 ret.append('Failed to index some unindexed files.')
544 if not took_action:
545 ret.append('Nothing to freeze.')
546 return ' '.join(ret) or None
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000547
548
Gavin Mak2cbe95c2023-03-06 22:39:56 +0000549def get_branch_tree(use_limit=False):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000550 """Get the dictionary of {branch: parent}, compatible with topo_iter.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000551
552 Returns a tuple of (skipped, <branch_tree dict>) where skipped is a set of
553 branches without upstream branches defined.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000554 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000555 skipped = set()
556 branch_tree = {}
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000557
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000558 for branch in branches(use_limit=use_limit):
559 parent = upstream(branch)
560 if not parent:
561 skipped.add(branch)
562 continue
563 branch_tree[branch] = parent
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000564
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000565 return skipped, branch_tree
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000566
567
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000568def get_or_create_merge_base(branch, parent=None):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000569 """Finds the configured merge base for branch.
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000570
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000571 If parent is supplied, it's used instead of calling upstream(branch).
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000572 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000573 base = branch_config(branch, 'base')
574 base_upstream = branch_config(branch, 'base-upstream')
575 parent = parent or upstream(branch)
576 if parent is None or branch is None:
577 return None
578 actual_merge_base = run('merge-base', parent, branch)
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000579
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000580 if base_upstream != parent:
581 base = None
582 base_upstream = None
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000583
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000584 def is_ancestor(a, b):
585 return run_with_retcode('merge-base', '--is-ancestor', a, b) == 0
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000586
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000587 if base and base != actual_merge_base:
588 if not is_ancestor(base, branch):
589 logging.debug('Found WRONG pre-set merge-base for %s: %s', branch,
590 base)
591 base = None
592 elif is_ancestor(base, actual_merge_base):
593 logging.debug('Found OLD pre-set merge-base for %s: %s', branch,
594 base)
595 base = None
596 else:
597 logging.debug('Found pre-set merge-base for %s: %s', branch, base)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000598
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000599 if not base:
600 base = actual_merge_base
601 manual_merge_base(branch, base, parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000602
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000603 return base
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000604
605
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000606def hash_multi(*reflike):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000607 return run('rev-parse', *reflike).splitlines()
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000608
609
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000610def hash_one(reflike, short=False):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000611 args = ['rev-parse', reflike]
612 if short:
613 args.insert(1, '--short')
614 return run(*args)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000615
616
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000617def in_rebase():
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000618 git_dir = run('rev-parse', '--git-dir')
619 return (os.path.exists(os.path.join(git_dir, 'rebase-merge'))
620 or os.path.exists(os.path.join(git_dir, 'rebase-apply')))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000621
622
623def intern_f(f, kind='blob'):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000624 """Interns a file object into the git object store.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000625
626 Args:
627 f (file-like object) - The file-like object to intern
628 kind (git object type) - One of 'blob', 'commit', 'tree', 'tag'.
629
630 Returns the git hash of the interned object (hex encoded).
631 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000632 ret = run('hash-object', '-t', kind, '-w', '--stdin', stdin=f)
633 f.close()
634 return ret
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000635
636
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000637def is_dormant(branch):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000638 # TODO(iannucci): Do an oldness check?
639 return branch_config(branch, 'dormant', 'false') != 'false'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000640
641
agable02b3c982016-06-22 07:51:22 -0700642def is_unmerged(stat_value):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000643 return ('U' in (stat_value.lstat, stat_value.rstat)
644 or ((stat_value.lstat == stat_value.rstat)
645 and stat_value.lstat in 'AD'))
agable02b3c982016-06-22 07:51:22 -0700646
647
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000648def manual_merge_base(branch, base, parent):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000649 set_branch_config(branch, 'base', base)
650 set_branch_config(branch, 'base-upstream', parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000651
652
653def mktree(treedict):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000654 """Makes a git tree object and returns its hash.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000655
656 See |tree()| for the values of mode, type, and ref.
657
658 Args:
659 treedict - { name: (mode, type, ref) }
660 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000661 with tempfile.TemporaryFile() as f:
662 for name, (mode, typ, ref) in treedict.items():
663 f.write(('%s %s %s\t%s\0' % (mode, typ, ref, name)).encode('utf-8'))
664 f.seek(0)
665 return run('mktree', '-z', stdin=f)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000666
667
668def parse_commitrefs(*commitrefs):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000669 """Returns binary encoded commit hashes for one or more commitrefs.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000670
671 A commitref is anything which can resolve to a commit. Popular examples:
672 * 'HEAD'
Josip Sokcevic9c0dc302020-11-20 18:41:25 +0000673 * 'origin/main'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000674 * 'cool_branch~2'
675 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000676 try:
677 return [binascii.unhexlify(h) for h in hash_multi(*commitrefs)]
678 except subprocess2.CalledProcessError:
679 raise BadCommitRefException(commitrefs)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000680
681
sbc@chromium.org384039b2014-10-13 21:01:00 +0000682RebaseRet = collections.namedtuple('RebaseRet', 'success stdout stderr')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000683
684
Robert Iannuccid3acb162021-05-04 21:37:40 +0000685def rebase(parent, start, branch, abort=False, allow_gc=False):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000686 """Rebases |start|..|branch| onto the branch |parent|.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000687
Robert Iannuccid3acb162021-05-04 21:37:40 +0000688 Sets 'gc.auto=0' for the duration of this call to prevent the rebase from
689 running a potentially slow garbage collection cycle.
690
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000691 Args:
692 parent - The new parent ref for the rebased commits.
693 start - The commit to start from
694 branch - The branch to rebase
695 abort - If True, will call git-rebase --abort in the event that the rebase
696 doesn't complete successfully.
Robert Iannuccid3acb162021-05-04 21:37:40 +0000697 allow_gc - If True, sets "-c gc.auto=1" on the rebase call, rather than
698 "-c gc.auto=0". Usually if you're doing a series of rebases,
699 you'll only want to run a single gc pass at the end of all the
700 rebase activity.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000701
702 Returns a namedtuple with fields:
703 success - a boolean indicating that the rebase command completed
704 successfully.
705 message - if the rebase failed, this contains the stdout of the failed
706 rebase.
707 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000708 try:
709 args = [
710 '-c',
711 'gc.auto={}'.format('1' if allow_gc else '0'),
712 'rebase',
713 ]
714 if TEST_MODE:
715 args.append('--committer-date-is-author-date')
716 args += [
717 '--onto',
718 parent,
719 start,
720 branch,
721 ]
722 run(*args)
723 return RebaseRet(True, '', '')
724 except subprocess2.CalledProcessError as cpe:
725 if abort:
726 run_with_retcode('rebase', '--abort') # ignore failure
727 return RebaseRet(False, cpe.stdout.decode('utf-8', 'replace'),
728 cpe.stderr.decode('utf-8', 'replace'))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000729
730
731def remove_merge_base(branch):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000732 del_branch_config(branch, 'base')
733 del_branch_config(branch, 'base-upstream')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000734
735
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000736def repo_root():
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000737 """Returns the absolute path to the repository root."""
738 return run('rev-parse', '--show-toplevel')
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000739
740
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000741def upstream_default():
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000742 """Returns the default branch name of the origin repository."""
743 try:
Josip Sokcevic06423732021-03-31 19:04:42 +0000744 ret = run('rev-parse', '--abbrev-ref', 'origin/HEAD')
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000745 # Detect if the repository migrated to main branch
746 if ret == 'origin/master':
747 try:
748 ret = run('rev-parse', '--abbrev-ref', 'origin/main')
749 run('remote', 'set-head', '-a', 'origin')
750 ret = run('rev-parse', '--abbrev-ref', 'origin/HEAD')
751 except subprocess2.CalledProcessError:
752 pass
753 return ret
754 except subprocess2.CalledProcessError:
755 return 'origin/main'
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000756
757
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000758def root():
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000759 return get_config('depot-tools.upstream', upstream_default())
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000760
761
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000762@contextlib.contextmanager
763def less(): # pragma: no cover
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000764 """Runs 'less' as context manager yielding its stdin as a PIPE.
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000765
766 Automatically checks if sys.stdout is a non-TTY stream. If so, it avoids
767 running less and just yields sys.stdout.
Edward Lemur0d462e92020-01-08 20:11:31 +0000768
769 The returned PIPE is opened on binary mode.
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000770 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000771 if not setup_color.IS_TTY:
772 # On Python 3, sys.stdout doesn't accept bytes, and sys.stdout.buffer
773 # must be used.
774 yield getattr(sys.stdout, 'buffer', sys.stdout)
775 return
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000776
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000777 # Run with the same options that git uses (see setup_pager in git repo).
778 # -F: Automatically quit if the output is less than one screen.
779 # -R: Don't escape ANSI color codes.
780 # -X: Don't clear the screen before starting.
781 cmd = ('less', '-FRX')
Edward Lemurb800fde2020-01-10 23:04:44 +0000782 try:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000783 proc = subprocess2.Popen(cmd, stdin=subprocess2.PIPE)
784 yield proc.stdin
785 finally:
786 try:
787 proc.stdin.close()
788 except BrokenPipeError:
789 # BrokenPipeError is raised if proc has already completed,
790 pass
791 proc.wait()
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000792
793
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000794def run(*cmd, **kwargs):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000795 """The same as run_with_stderr, except it only returns stdout."""
796 return run_with_stderr(*cmd, **kwargs)[0]
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000797
798
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000799def run_with_retcode(*cmd, **kwargs):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000800 """Run a command but only return the status code."""
801 try:
802 run(*cmd, **kwargs)
803 return 0
804 except subprocess2.CalledProcessError as cpe:
805 return cpe.returncode
806
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000807
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000808def run_stream(*cmd, **kwargs):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000809 """Runs a git command. Returns stdout as a PIPE (file-like object).
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000810
811 stderr is dropped to avoid races if the process outputs to both stdout and
812 stderr.
813 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000814 kwargs.setdefault('stderr', subprocess2.DEVNULL)
815 kwargs.setdefault('stdout', subprocess2.PIPE)
816 kwargs.setdefault('shell', False)
817 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
818 proc = subprocess2.Popen(cmd, **kwargs)
819 return proc.stdout
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000820
821
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000822@contextlib.contextmanager
823def run_stream_with_retcode(*cmd, **kwargs):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000824 """Runs a git command as context manager yielding stdout as a PIPE.
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000825
826 stderr is dropped to avoid races if the process outputs to both stdout and
827 stderr.
828
829 Raises subprocess2.CalledProcessError on nonzero return code.
830 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000831 kwargs.setdefault('stderr', subprocess2.DEVNULL)
832 kwargs.setdefault('stdout', subprocess2.PIPE)
833 kwargs.setdefault('shell', False)
834 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
835 try:
836 proc = subprocess2.Popen(cmd, **kwargs)
837 yield proc.stdout
838 finally:
839 retcode = proc.wait()
840 if retcode != 0:
841 raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(), b'',
842 b'')
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000843
844
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000845def run_with_stderr(*cmd, **kwargs):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000846 """Runs a git command.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000847
848 Returns (stdout, stderr) as a pair of strings.
849
850 kwargs
851 autostrip (bool) - Strip the output. Defaults to True.
852 indata (str) - Specifies stdin data for the process.
853 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000854 kwargs.setdefault('stdin', subprocess2.PIPE)
855 kwargs.setdefault('stdout', subprocess2.PIPE)
856 kwargs.setdefault('stderr', subprocess2.PIPE)
857 kwargs.setdefault('shell', False)
858 autostrip = kwargs.pop('autostrip', True)
859 indata = kwargs.pop('indata', None)
860 decode = kwargs.pop('decode', True)
861 accepted_retcodes = kwargs.pop('accepted_retcodes', [0])
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000862
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000863 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
864 proc = subprocess2.Popen(cmd, **kwargs)
865 ret, err = proc.communicate(indata)
866 retcode = proc.wait()
867 if retcode not in accepted_retcodes:
868 raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(), ret,
869 err)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000870
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000871 if autostrip:
872 ret = (ret or b'').strip()
873 err = (err or b'').strip()
Edward Lemur12a537f2019-10-03 21:57:15 +0000874
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000875 if decode:
876 ret = ret.decode('utf-8', 'replace')
877 err = err.decode('utf-8', 'replace')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000878
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000879 return ret, err
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000880
881
882def set_branch_config(branch, option, value, scope='local'):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000883 set_config('branch.%s.%s' % (branch, option), value, scope=scope)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000884
885
886def set_config(option, value, scope='local'):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000887 run('config', '--' + scope, option, value)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000888
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000889
sbc@chromium.org71437c02015-04-09 19:29:40 +0000890def get_dirty_files():
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000891 # Make sure index is up-to-date before running diff-index.
892 run_with_retcode('update-index', '--refresh', '-q')
893 return run('diff-index', '--ignore-submodules', '--name-status', 'HEAD')
sbc@chromium.org71437c02015-04-09 19:29:40 +0000894
895
896def is_dirty_git_tree(cmd):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000897 w = lambda s: sys.stderr.write(s + "\n")
iannuccie38699b2016-08-15 17:32:31 -0700898
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000899 dirty = get_dirty_files()
900 if dirty:
901 w('Cannot %s with a dirty tree. Commit%s or stash your changes first.' %
902 (cmd, '' if cmd == 'upload' else ', freeze'))
903 w('Uncommitted files: (git diff-index --name-status HEAD)')
904 w(dirty[:4096])
905 if len(dirty) > 4096: # pragma: no cover
906 w('... (run "git diff-index --name-status HEAD" to see full '
907 'output).')
908 return True
909 return False
sbc@chromium.org71437c02015-04-09 19:29:40 +0000910
911
Greg NISBET923bcf82023-08-10 22:50:46 +0000912def status(ignore_submodules=None):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000913 """Returns a parsed version of git-status.
agable02b3c982016-06-22 07:51:22 -0700914
Greg NISBET923bcf82023-08-10 22:50:46 +0000915 Args:
916 ignore_submodules (str|None): "all", "none", or None.
917 None is equivalent to "none".
918
agable02b3c982016-06-22 07:51:22 -0700919 Returns a generator of (current_name, (lstat, rstat, src)) pairs where:
920 * current_name is the name of the file
921 * lstat is the left status code letter from git-status
Aravind Vasudevanc71efb52023-08-29 23:02:15 +0000922 * rstat is the right status code letter from git-status
agable02b3c982016-06-22 07:51:22 -0700923 * src is the current name of the file, or the original name of the file
924 if lstat == 'R'
925 """
Greg NISBET923bcf82023-08-10 22:50:46 +0000926
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000927 ignore_submodules = ignore_submodules or 'none'
928 assert ignore_submodules in (
929 'all',
930 'none'), f'ignore_submodules value {ignore_submodules} is invalid'
Greg NISBET923bcf82023-08-10 22:50:46 +0000931
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000932 stat_entry = collections.namedtuple('stat_entry', 'lstat rstat src')
agable02b3c982016-06-22 07:51:22 -0700933
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000934 def tokenizer(stream):
935 acc = BytesIO()
936 c = None
937 while c != b'':
938 c = stream.read(1)
939 if c in (None, b'', b'\0'):
940 if len(acc.getvalue()) > 0:
941 yield acc.getvalue()
942 acc = BytesIO()
943 else:
944 acc.write(c)
agable02b3c982016-06-22 07:51:22 -0700945
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000946 def parser(tokens):
947 while True:
948 try:
949 status_dest = next(tokens).decode('utf-8')
950 except StopIteration:
951 return
952 stat, dest = status_dest[:2], status_dest[3:]
953 lstat, rstat = stat
954 if lstat == 'R':
955 src = next(tokens).decode('utf-8')
956 else:
957 src = dest
958 yield (dest, stat_entry(lstat, rstat, src))
agable02b3c982016-06-22 07:51:22 -0700959
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000960 return parser(
961 tokenizer(
962 run_stream('status',
963 '-z',
964 f'--ignore-submodules={ignore_submodules}',
965 bufsize=-1)))
agable02b3c982016-06-22 07:51:22 -0700966
967
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000968def squash_current_branch(header=None, merge_base=None):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000969 header = header or 'git squash commit for %s.' % current_branch()
970 merge_base = merge_base or get_or_create_merge_base(current_branch())
971 log_msg = header + '\n'
972 if log_msg:
973 log_msg += '\n'
974 log_msg += run('log', '--reverse', '--format=%H%n%B',
975 '%s..HEAD' % merge_base)
976 run('reset', '--soft', merge_base)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000977
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000978 if not get_dirty_files():
979 # Sometimes the squash can result in the same tree, meaning that there
980 # is nothing to commit at this point.
981 print('Nothing to commit; squashed branch is empty')
982 return False
983 run('commit',
984 '--no-verify',
985 '-a',
986 '-F',
987 '-',
988 indata=log_msg.encode('utf-8'))
989 return True
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000990
991
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000992def tags(*args):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000993 return run('tag', *args).splitlines()
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000994
995
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000996def thaw():
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000997 took_action = False
998 with run_stream('rev-list', 'HEAD') as stream:
999 for sha in stream:
1000 sha = sha.strip().decode('utf-8')
1001 msg = run('show', '--format=%f%b', '-s', 'HEAD')
1002 match = FREEZE_MATCHER.match(msg)
1003 if not match:
1004 if not took_action:
1005 return 'Nothing to thaw.'
1006 break
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001007
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001008 run('reset', '--' + FREEZE_SECTIONS[match.group(1)], sha)
1009 took_action = True
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001010
1011
1012def topo_iter(branch_tree, top_down=True):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001013 """Generates (branch, parent) in topographical order for a branch tree.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001014
1015 Given a tree:
1016
1017 A1
1018 B1 B2
1019 C1 C2 C3
1020 D1
1021
1022 branch_tree would look like: {
1023 'D1': 'C3',
1024 'C3': 'B2',
1025 'B2': 'A1',
1026 'C1': 'B1',
1027 'C2': 'B1',
1028 'B1': 'A1',
1029 }
1030
1031 It is OK to have multiple 'root' nodes in your graph.
1032
1033 if top_down is True, items are yielded from A->D. Otherwise they're yielded
1034 from D->A. Within a layer the branches will be yielded in sorted order.
1035 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001036 branch_tree = branch_tree.copy()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001037
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001038 # TODO(iannucci): There is probably a more efficient way to do these.
1039 if top_down:
1040 while branch_tree:
1041 this_pass = [(b, p) for b, p in branch_tree.items()
1042 if p not in branch_tree]
1043 assert this_pass, "Branch tree has cycles: %r" % branch_tree
1044 for branch, parent in sorted(this_pass):
1045 yield branch, parent
1046 del branch_tree[branch]
1047 else:
1048 parent_to_branches = collections.defaultdict(set)
1049 for branch, parent in branch_tree.items():
1050 parent_to_branches[parent].add(branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001051
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001052 while branch_tree:
1053 this_pass = [(b, p) for b, p in branch_tree.items()
1054 if not parent_to_branches[b]]
1055 assert this_pass, "Branch tree has cycles: %r" % branch_tree
1056 for branch, parent in sorted(this_pass):
1057 yield branch, parent
1058 parent_to_branches[parent].discard(branch)
1059 del branch_tree[branch]
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001060
1061
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +00001062def tree(treeref, recurse=False):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001063 """Returns a dict representation of a git tree object.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +00001064
1065 Args:
1066 treeref (str) - a git ref which resolves to a tree (commits count as trees).
qyearsley12fa6ff2016-08-24 09:18:40 -07001067 recurse (bool) - include all of the tree's descendants too. File names will
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +00001068 take the form of 'some/path/to/file'.
1069
1070 Return format:
1071 { 'file_name': (mode, type, ref) }
1072
1073 mode is an integer where:
1074 * 0040000 - Directory
1075 * 0100644 - Regular non-executable file
1076 * 0100664 - Regular non-executable group-writeable file
1077 * 0100755 - Regular executable file
1078 * 0120000 - Symbolic link
1079 * 0160000 - Gitlink
1080
1081 type is a string where it's one of 'blob', 'commit', 'tree', 'tag'.
1082
1083 ref is the hex encoded hash of the entry.
1084 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001085 ret = {}
1086 opts = ['ls-tree', '--full-tree']
1087 if recurse:
1088 opts.append('-r')
1089 opts.append(treeref)
1090 try:
1091 for line in run(*opts).splitlines():
1092 mode, typ, ref, name = line.split(None, 3)
1093 ret[name] = (mode, typ, ref)
1094 except subprocess2.CalledProcessError:
1095 return None
1096 return ret
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +00001097
1098
Mun Yong Jang781e71e2017-10-25 15:46:20 -07001099def get_remote_url(remote='origin'):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001100 try:
1101 return run('config', 'remote.%s.url' % remote)
1102 except subprocess2.CalledProcessError:
1103 return None
Mun Yong Jang781e71e2017-10-25 15:46:20 -07001104
1105
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +00001106def upstream(branch):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001107 try:
1108 return run('rev-parse', '--abbrev-ref', '--symbolic-full-name',
1109 branch + '@{upstream}')
1110 except subprocess2.CalledProcessError:
1111 return None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001112
agable@chromium.orgd629fb42014-10-01 09:40:10 +00001113
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001114def get_git_version():
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001115 """Returns a tuple that contains the numeric components of the current git
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001116 version."""
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001117 version_string = run('--version')
1118 version_match = re.search(r'(\d+.)+(\d+)', version_string)
1119 version = version_match.group() if version_match else ''
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001120
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001121 return tuple(int(x) for x in version.split('.'))
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001122
1123
calamity@chromium.org745ffa62014-09-08 01:03:19 +00001124def get_branches_info(include_tracking_status):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001125 format_string = (
1126 '--format=%(refname:short):%(objectname:short):%(upstream:short):')
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001127
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001128 # This is not covered by the depot_tools CQ which only has git version 1.8.
1129 if (include_tracking_status and get_git_version() >=
1130 MIN_UPSTREAM_TRACK_GIT_VERSION): # pragma: no cover
1131 format_string += '%(upstream:track)'
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001132
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001133 info_map = {}
1134 data = run('for-each-ref', format_string, 'refs/heads')
1135 BranchesInfo = collections.namedtuple('BranchesInfo',
1136 'hash upstream commits behind')
1137 for line in data.splitlines():
1138 (branch, branch_hash, upstream_branch,
1139 tracking_status) = line.split(':')
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001140
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001141 commits = None
1142 if include_tracking_status:
1143 base = get_or_create_merge_base(branch)
1144 if base:
1145 commits_list = run('rev-list', '--count', branch, '^%s' % base,
1146 '--')
1147 commits = int(commits_list) or None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001148
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001149 behind_match = re.search(r'behind (\d+)', tracking_status)
1150 behind = int(behind_match.group(1)) if behind_match else None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001151
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001152 info_map[branch] = BranchesInfo(hash=branch_hash,
1153 upstream=upstream_branch,
1154 commits=commits,
1155 behind=behind)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001156
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001157 # Set None for upstreams which are not branches (e.g empty upstream, remotes
1158 # and deleted upstream branches).
1159 missing_upstreams = {}
1160 for info in info_map.values():
1161 if (info.upstream not in info_map
1162 and info.upstream not in missing_upstreams):
1163 missing_upstreams[info.upstream] = None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001164
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001165 result = info_map.copy()
1166 result.update(missing_upstreams)
1167 return result
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001168
1169
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001170def make_workdir_common(repository,
1171 new_workdir,
1172 files_to_symlink,
1173 files_to_copy,
1174 symlink=None):
1175 if not symlink:
1176 symlink = os.symlink
1177 os.makedirs(new_workdir)
1178 for entry in files_to_symlink:
1179 clone_file(repository, new_workdir, entry, symlink)
1180 for entry in files_to_copy:
1181 clone_file(repository, new_workdir, entry, shutil.copy)
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001182
1183
1184def make_workdir(repository, new_workdir):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001185 GIT_DIRECTORY_WHITELIST = [
1186 'config',
1187 'info',
1188 'hooks',
1189 'logs/refs',
1190 'objects',
1191 'packed-refs',
1192 'refs',
1193 'remotes',
1194 'rr-cache',
1195 'shallow',
1196 ]
1197 make_workdir_common(repository, new_workdir, GIT_DIRECTORY_WHITELIST,
1198 ['HEAD'])
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001199
1200
1201def clone_file(repository, new_workdir, link, operation):
Mike Frysinger124bb8e2023-09-06 05:48:55 +00001202 if not os.path.exists(os.path.join(repository, link)):
1203 return
1204 link_dir = os.path.dirname(os.path.join(new_workdir, link))
1205 if not os.path.exists(link_dir):
1206 os.makedirs(link_dir)
1207 src = os.path.join(repository, link)
1208 if os.path.islink(src):
1209 src = os.path.realpath(src)
1210 operation(src, os.path.join(new_workdir, link))