iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 1 | # Copyright 2014 The Chromium Authors. All rights reserved. |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 2 | # 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 Tambre | c2f74c1 | 2019-03-19 05:55:53 +0000 | [diff] [blame] | 7 | |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 8 | import multiprocessing.pool |
Josip Sokcevic | de6c456 | 2020-03-26 00:39:42 +0000 | [diff] [blame] | 9 | import sys |
| 10 | import threading |
| 11 | |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 12 | from multiprocessing.pool import IMapIterator |
Josip Sokcevic | de6c456 | 2020-03-26 00:39:42 +0000 | [diff] [blame] | 13 | |
Aravind Vasudevan | b816418 | 2023-08-25 21:49:12 +0000 | [diff] [blame] | 14 | from third_party import colorama |
| 15 | |
| 16 | |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 17 | def wrapper(func): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 18 | def wrap(self, timeout=None): |
| 19 | return func(self, timeout=timeout or threading.TIMEOUT_MAX) |
Josip Sokcevic | de6c456 | 2020-03-26 00:39:42 +0000 | [diff] [blame] | 20 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 21 | return wrap |
| 22 | |
| 23 | |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 24 | IMapIterator.next = wrapper(IMapIterator.next) |
| 25 | IMapIterator.__next__ = IMapIterator.next |
| 26 | # TODO(iannucci): Monkeypatch all other 'wait' methods too. |
| 27 | |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 28 | import binascii |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 29 | import collections |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 30 | import contextlib |
| 31 | import functools |
| 32 | import logging |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 33 | import os |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 34 | import re |
iannucci@chromium.org | 596cd5c | 2016-04-04 21:34:39 +0000 | [diff] [blame] | 35 | import setup_color |
sammc@chromium.org | 900a33f | 2015-09-29 06:57:09 +0000 | [diff] [blame] | 36 | import shutil |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 37 | import signal |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 38 | import tempfile |
iannucci@chromium.org | 3f23cdf | 2014-04-15 20:02:44 +0000 | [diff] [blame] | 39 | import textwrap |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 40 | |
| 41 | import subprocess2 |
| 42 | |
Raul Tambre | c2f74c1 | 2019-03-19 05:55:53 +0000 | [diff] [blame] | 43 | from io import BytesIO |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 44 | |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 45 | ROOT = os.path.abspath(os.path.dirname(__file__)) |
iannucci@chromium.org | 0d9e59c | 2016-01-09 08:08:41 +0000 | [diff] [blame] | 46 | IS_WIN = sys.platform == 'win32' |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 47 | TEST_MODE = False |
| 48 | |
Dan Jacques | 209a681 | 2017-07-12 11:40:20 -0700 | [diff] [blame] | 49 | |
| 50 | def win_find_git(): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 51 | 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 Jacques | 209a681 | 2017-07-12 11:40:20 -0700 | [diff] [blame] | 57 | |
| 58 | |
| 59 | GIT_EXE = 'git' if not IS_WIN else win_find_git() |
| 60 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 61 | FREEZE = 'FREEZE' |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 62 | FREEZE_SECTIONS = {'indexed': 'soft', 'unindexed': 'mixed'} |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 63 | FREEZE_MATCHER = re.compile(r'%s.(%s)' % (FREEZE, '|'.join(FREEZE_SECTIONS))) |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 64 | |
Dan Jacques | 2f8b0c1 | 2017-04-05 12:57:21 -0700 | [diff] [blame] | 65 | # NOTE: This list is DEPRECATED in favor of the Infra Git wrapper: |
Josip Sokcevic | 9c0dc30 | 2020-11-20 18:41:25 +0000 | [diff] [blame] | 66 | # https://chromium.googlesource.com/infra/infra/+/HEAD/go/src/infra/tools/git |
Dan Jacques | 2f8b0c1 | 2017-04-05 12:57:21 -0700 | [diff] [blame] | 67 | # |
| 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.org | de219ec | 2014-07-28 17:39:08 +0000 | [diff] [blame] | 73 | # 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'. |
| 80 | GIT_TRANSIENT_ERRORS = ( |
| 81 | # crbug.com/285832 |
iannucci@chromium.org | 6e95d40 | 2014-08-29 22:10:55 +0000 | [diff] [blame] | 82 | r'!.*\[remote rejected\].*\(error in hook\)', |
dnj@chromium.org | de219ec | 2014-07-28 17:39:08 +0000 | [diff] [blame] | 83 | |
| 84 | # crbug.com/289932 |
iannucci@chromium.org | 6e95d40 | 2014-08-29 22:10:55 +0000 | [diff] [blame] | 85 | r'!.*\[remote rejected\].*\(failed to lock\)', |
dnj@chromium.org | de219ec | 2014-07-28 17:39:08 +0000 | [diff] [blame] | 86 | |
| 87 | # crbug.com/307156 |
iannucci@chromium.org | 6e95d40 | 2014-08-29 22:10:55 +0000 | [diff] [blame] | 88 | r'!.*\[remote rejected\].*\(error in Gerrit backend\)', |
dnj@chromium.org | de219ec | 2014-07-28 17:39:08 +0000 | [diff] [blame] | 89 | |
| 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.org | de219ec | 2014-07-28 17:39:08 +0000 | [diff] [blame] | 111 | # crbug.com/388876 |
| 112 | r'Connection timed out', |
dnj@chromium.org | 45cddd6 | 2014-11-06 19:36:42 +0000 | [diff] [blame] | 113 | |
| 114 | # crbug.com/430343 |
| 115 | # TODO(dnj): Resync with Chromite. |
| 116 | r'The requested URL returned error: 5\d+', |
Arikon | b3a2148 | 2016-07-22 10:12:24 -0700 | [diff] [blame] | 117 | r'Connection reset by peer', |
Arikon | b3a2148 | 2016-07-22 10:12:24 -0700 | [diff] [blame] | 118 | r'Unable to look up', |
Arikon | b3a2148 | 2016-07-22 10:12:24 -0700 | [diff] [blame] | 119 | r'Couldn\'t resolve host', |
dnj@chromium.org | de219ec | 2014-07-28 17:39:08 +0000 | [diff] [blame] | 120 | ) |
| 121 | |
| 122 | GIT_TRANSIENT_ERRORS_RE = re.compile('|'.join(GIT_TRANSIENT_ERRORS), |
| 123 | re.IGNORECASE) |
| 124 | |
raphael.kubo.da.costa@intel.com | 58d05b0 | 2015-06-24 08:54:41 +0000 | [diff] [blame] | 125 | # 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. |
| 128 | MIN_UPSTREAM_TRACK_GIT_VERSION = (2, 3) |
dnj@chromium.org | de219ec | 2014-07-28 17:39:08 +0000 | [diff] [blame] | 129 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 130 | |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 131 | class BadCommitRefException(Exception): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 132 | 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.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 135 | |
| 136 | |
| 137 | def memoize_one(**kwargs): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 138 | """Memoizes a single-argument pure function. |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 139 | |
| 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 Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 153 | assert 'threadsafe' in kwargs, 'Must specify threadsafe={True,False}' |
| 154 | threadsafe = kwargs['threadsafe'] |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 155 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 156 | if threadsafe: |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 157 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 158 | def withlock(lock, f): |
| 159 | def inner(*args, **kwargs): |
| 160 | with lock: |
| 161 | return f(*args, **kwargs) |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 162 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 163 | return inner |
| 164 | else: |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 165 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 166 | 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.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 201 | |
| 202 | |
| 203 | def _ScopedPool_initer(orig, orig_args): # pragma: no cover |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 204 | """Initializer method for ScopedPool's subprocesses. |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 205 | |
| 206 | This helps ScopedPool handle Ctrl-C's correctly. |
| 207 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 208 | signal.signal(signal.SIGINT, signal.SIG_IGN) |
| 209 | if orig: |
| 210 | orig(*orig_args) |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 211 | |
| 212 | |
| 213 | @contextlib.contextmanager |
| 214 | def ScopedPool(*args, **kwargs): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 215 | """Context Manager which returns a multiprocessing.pool instance which |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 216 | 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 Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 224 | 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.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 231 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 232 | try: |
| 233 | yield pool |
| 234 | pool.close() |
| 235 | except: |
| 236 | pool.terminate() |
| 237 | raise |
| 238 | finally: |
| 239 | pool.join() |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 240 | |
| 241 | |
| 242 | class ProgressPrinter(object): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 243 | """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.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 246 | |
| 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.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 260 | fout (file-like) - The stream to print status messages to. |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 261 | period (float) - The time in seconds for the printer thread to wait |
| 262 | between printing. |
| 263 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 264 | 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.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 269 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 270 | 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.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 276 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 277 | def _emit(self, s): |
| 278 | if self.enabled: |
| 279 | self._stream.write('\r' + s) |
| 280 | self._stream.flush() |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 281 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 282 | 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.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 288 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 289 | def inc(self, amount=1): |
| 290 | self._count += amount |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 291 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 292 | def __enter__(self): |
| 293 | self._thread.start() |
| 294 | return self.inc |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 295 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 296 | 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.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 302 | |
| 303 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 304 | def once(function): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 305 | """@Decorates |function| so that it only performs its action once, no matter |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 306 | how many times the decorated |function| is called.""" |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 307 | 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 Lemur | 12a537f | 2019-10-03 21:57:15 +0000 | [diff] [blame] | 315 | |
| 316 | |
| 317 | def unicode_repr(s): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 318 | result = repr(s) |
| 319 | return result[1:] if result.startswith('u') else result |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 320 | |
| 321 | |
| 322 | ## Git functions |
| 323 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 324 | |
agable | 7aa2ddd | 2016-06-21 07:47:00 -0700 | [diff] [blame] | 325 | def die(message, *args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 326 | print(textwrap.dedent(message % args), file=sys.stderr) |
| 327 | sys.exit(1) |
agable | 7aa2ddd | 2016-06-21 07:47:00 -0700 | [diff] [blame] | 328 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 329 | |
Mark Mentovai | f548d08 | 2017-03-08 13:32:00 -0500 | [diff] [blame] | 330 | def blame(filename, revision=None, porcelain=False, abbrev=None, *_args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 331 | 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.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 340 | |
| 341 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 342 | def branch_config(branch, option, default=None): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 343 | return get_config('branch.%s.%s' % (branch, option), default=default) |
iannucci@chromium.org | 0d9e59c | 2016-01-09 08:08:41 +0000 | [diff] [blame] | 344 | |
| 345 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 346 | def branch_config_map(option): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 347 | """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.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 354 | |
| 355 | |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 356 | def branches(use_limit=True, *args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 357 | NO_BRANCH = ('* (no branch', '* (detached', '* (HEAD detached') |
iannucci@chromium.org | 3f23cdf | 2014-04-15 20:02:44 +0000 | [diff] [blame] | 358 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 359 | key = 'depot-tools.branch-limit' |
| 360 | limit = get_config_int(key, 20) |
iannucci@chromium.org | 3f23cdf | 2014-04-15 20:02:44 +0000 | [diff] [blame] | 361 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 362 | raw_branches = run('branch', *args).splitlines() |
iannucci@chromium.org | 3f23cdf | 2014-04-15 20:02:44 +0000 | [diff] [blame] | 363 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 364 | num = len(raw_branches) |
iannucci@chromium.org | 3f23cdf | 2014-04-15 20:02:44 +0000 | [diff] [blame] | 365 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 366 | if use_limit and num > limit: |
| 367 | die( |
| 368 | """\ |
agable | 7aa2ddd | 2016-06-21 07:47:00 -0700 | [diff] [blame] | 369 | 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.org | 3f23cdf | 2014-04-15 20:02:44 +0000 | [diff] [blame] | 372 | git config %s <new_limit> |
agable | 7aa2ddd | 2016-06-21 07:47:00 -0700 | [diff] [blame] | 373 | |
| 374 | You may also try cleaning up your old branches by running: |
| 375 | git cl archive |
| 376 | """, num, limit, key) |
iannucci@chromium.org | 3f23cdf | 2014-04-15 20:02:44 +0000 | [diff] [blame] | 377 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 378 | for line in raw_branches: |
| 379 | if line.startswith(NO_BRANCH): |
| 380 | continue |
| 381 | yield line.split()[-1] |
iannucci@chromium.org | 8bc9b5c | 2014-03-12 01:36:18 +0000 | [diff] [blame] | 382 | |
| 383 | |
agable | 7aa2ddd | 2016-06-21 07:47:00 -0700 | [diff] [blame] | 384 | def get_config(option, default=None): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 385 | try: |
| 386 | return run('config', '--get', option) or default |
| 387 | except subprocess2.CalledProcessError: |
| 388 | return default |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 389 | |
| 390 | |
agable | 7aa2ddd | 2016-06-21 07:47:00 -0700 | [diff] [blame] | 391 | def get_config_int(option, default=0): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 392 | assert isinstance(default, int) |
| 393 | try: |
| 394 | return int(get_config(option, default)) |
| 395 | except ValueError: |
| 396 | return default |
agable | 7aa2ddd | 2016-06-21 07:47:00 -0700 | [diff] [blame] | 397 | |
| 398 | |
| 399 | def get_config_list(option): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 400 | try: |
| 401 | return run('config', '--get-all', option).split() |
| 402 | except subprocess2.CalledProcessError: |
| 403 | return [] |
iannucci@chromium.org | 8bc9b5c | 2014-03-12 01:36:18 +0000 | [diff] [blame] | 404 | |
| 405 | |
agable | 7aa2ddd | 2016-06-21 07:47:00 -0700 | [diff] [blame] | 406 | def get_config_regexp(pattern): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 407 | 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() |
agable | 7aa2ddd | 2016-06-21 07:47:00 -0700 | [diff] [blame] | 413 | |
| 414 | |
Aravind Vasudevan | b816418 | 2023-08-25 21:49:12 +0000 | [diff] [blame] | 415 | def is_fsmonitor_enabled(): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 416 | """Returns true if core.fsmonitor is enabled in git config.""" |
| 417 | fsmonitor = get_config('core.fsmonitor', 'False') |
| 418 | return fsmonitor.strip().lower() == 'true' |
Aravind Vasudevan | b816418 | 2023-08-25 21:49:12 +0000 | [diff] [blame] | 419 | |
| 420 | |
| 421 | def warn_submodule(): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 422 | """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 Vasudevan | b816418 | 2023-08-25 21:49:12 +0000 | [diff] [blame] | 434 | |
| 435 | |
iannucci@chromium.org | 8bc9b5c | 2014-03-12 01:36:18 +0000 | [diff] [blame] | 436 | def current_branch(): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 437 | try: |
| 438 | return run('rev-parse', '--abbrev-ref', 'HEAD') |
| 439 | except subprocess2.CalledProcessError: |
| 440 | return None |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 441 | |
| 442 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 443 | def del_branch_config(branch, option, scope='local'): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 444 | del_config('branch.%s.%s' % (branch, option), scope=scope) |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 445 | |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 446 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 447 | def del_config(option, scope='local'): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 448 | try: |
| 449 | run('config', '--' + scope, '--unset', option) |
| 450 | except subprocess2.CalledProcessError: |
| 451 | pass |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 452 | |
| 453 | |
mgiuca@chromium.org | 01d2cde | 2016-02-05 03:25:41 +0000 | [diff] [blame] | 454 | def diff(oldrev, newrev, *args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 455 | return run('diff', oldrev, newrev, *args) |
mgiuca@chromium.org | 01d2cde | 2016-02-05 03:25:41 +0000 | [diff] [blame] | 456 | |
| 457 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 458 | def freeze(): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 459 | 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 |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 464 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 465 | root_path = repo_root() |
iannucci | eaca033 | 2016-08-03 16:46:50 -0700 | [diff] [blame] | 466 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 467 | # unindexed tracks all the files which are unindexed but we want to add to |
| 468 | # the `FREEZE.unindexed` commit. |
| 469 | unindexed = [] |
Robert Iannucci | 4e87f5b | 2023-07-13 19:51:33 +0000 | [diff] [blame] | 470 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 471 | # will be set to true if there are any indexed files to commit. |
| 472 | have_indexed_files = False |
Robert Iannucci | 4e87f5b | 2023-07-13 19:51:33 +0000 | [diff] [blame] | 473 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 474 | 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 Vasudevan | c71efb5 | 2023-08-29 23:02:15 +0000 | [diff] [blame] | 482 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 483 | # 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 Vasudevan | c71efb5 | 2023-08-29 23:02:15 +0000 | [diff] [blame] | 491 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 492 | if s.lstat == '?' and limit_mb > 0: |
| 493 | untracked_bytes += os.lstat(os.path.join(root_path, f)).st_size |
Robert Iannucci | 4e87f5b | 2023-07-13 19:51:33 +0000 | [diff] [blame] | 494 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 495 | if limit_mb > 0 and untracked_bytes > limit_mb * MB: |
| 496 | die( |
| 497 | """\ |
Bruce Dawson | 4bff3fd | 2018-01-04 14:44:23 -0800 | [diff] [blame] | 498 | You appear to have too much untracked+unignored data in your git |
| 499 | checkout: %.1f / %d MB. |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 500 | |
Bruce Dawson | 4bff3fd | 2018-01-04 14:44:23 -0800 | [diff] [blame] | 501 | Run `git status` to see what it is. |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 502 | |
Bruce Dawson | 4bff3fd | 2018-01-04 14:44:23 -0800 | [diff] [blame] | 503 | In addition to making many git commands slower, this will prevent |
| 504 | depot_tools from freezing your in-progress changes. |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 505 | |
Bruce Dawson | 4bff3fd | 2018-01-04 14:44:23 -0800 | [diff] [blame] | 506 | 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. |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 509 | |
Quinten Yearsley | 925cedb | 2020-04-13 17:49:39 +0000 | [diff] [blame] | 510 | If this data is intended as part of your commit, you may adjust the |
Bruce Dawson | 4bff3fd | 2018-01-04 14:44:23 -0800 | [diff] [blame] | 511 | freeze limit by running: |
| 512 | git config %s <new_limit> |
| 513 | Where <new_limit> is an integer threshold in megabytes.""", |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 514 | untracked_bytes / (MB * 1.0), limit_mb, key) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 515 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 516 | 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.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 522 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 523 | 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 |
agable | 96e179b | 2016-06-24 10:32:51 -0700 | [diff] [blame] | 534 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 535 | try: |
| 536 | run('commit', '--no-verify', '-m', f'{FREEZE}.unindexed') |
| 537 | took_action = True |
| 538 | except subprocess2.CalledProcessError: |
| 539 | pass |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 540 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 541 | 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.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 547 | |
| 548 | |
Gavin Mak | 2cbe95c | 2023-03-06 22:39:56 +0000 | [diff] [blame] | 549 | def get_branch_tree(use_limit=False): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 550 | """Get the dictionary of {branch: parent}, compatible with topo_iter. |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 551 | |
| 552 | Returns a tuple of (skipped, <branch_tree dict>) where skipped is a set of |
| 553 | branches without upstream branches defined. |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 554 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 555 | skipped = set() |
| 556 | branch_tree = {} |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 557 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 558 | 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.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 564 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 565 | return skipped, branch_tree |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 566 | |
| 567 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 568 | def get_or_create_merge_base(branch, parent=None): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 569 | """Finds the configured merge base for branch. |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 570 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 571 | If parent is supplied, it's used instead of calling upstream(branch). |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 572 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 573 | 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.org | edeaa81 | 2014-03-26 21:27:47 +0000 | [diff] [blame] | 579 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 580 | if base_upstream != parent: |
| 581 | base = None |
| 582 | base_upstream = None |
iannucci@chromium.org | 10fbe87 | 2014-05-16 22:31:13 +0000 | [diff] [blame] | 583 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 584 | def is_ancestor(a, b): |
| 585 | return run_with_retcode('merge-base', '--is-ancestor', a, b) == 0 |
iannucci@chromium.org | edeaa81 | 2014-03-26 21:27:47 +0000 | [diff] [blame] | 586 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 587 | 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.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 598 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 599 | if not base: |
| 600 | base = actual_merge_base |
| 601 | manual_merge_base(branch, base, parent) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 602 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 603 | return base |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 604 | |
| 605 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 606 | def hash_multi(*reflike): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 607 | return run('rev-parse', *reflike).splitlines() |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 608 | |
| 609 | |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 610 | def hash_one(reflike, short=False): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 611 | args = ['rev-parse', reflike] |
| 612 | if short: |
| 613 | args.insert(1, '--short') |
| 614 | return run(*args) |
iannucci@chromium.org | 8bc9b5c | 2014-03-12 01:36:18 +0000 | [diff] [blame] | 615 | |
| 616 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 617 | def in_rebase(): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 618 | 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.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 621 | |
| 622 | |
| 623 | def intern_f(f, kind='blob'): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 624 | """Interns a file object into the git object store. |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 625 | |
| 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 Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 632 | ret = run('hash-object', '-t', kind, '-w', '--stdin', stdin=f) |
| 633 | f.close() |
| 634 | return ret |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 635 | |
| 636 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 637 | def is_dormant(branch): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 638 | # TODO(iannucci): Do an oldness check? |
| 639 | return branch_config(branch, 'dormant', 'false') != 'false' |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 640 | |
| 641 | |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 642 | def is_unmerged(stat_value): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 643 | return ('U' in (stat_value.lstat, stat_value.rstat) |
| 644 | or ((stat_value.lstat == stat_value.rstat) |
| 645 | and stat_value.lstat in 'AD')) |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 646 | |
| 647 | |
iannucci@chromium.org | 10fbe87 | 2014-05-16 22:31:13 +0000 | [diff] [blame] | 648 | def manual_merge_base(branch, base, parent): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 649 | set_branch_config(branch, 'base', base) |
| 650 | set_branch_config(branch, 'base-upstream', parent) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 651 | |
| 652 | |
| 653 | def mktree(treedict): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 654 | """Makes a git tree object and returns its hash. |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 655 | |
| 656 | See |tree()| for the values of mode, type, and ref. |
| 657 | |
| 658 | Args: |
| 659 | treedict - { name: (mode, type, ref) } |
| 660 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 661 | 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.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 666 | |
| 667 | |
| 668 | def parse_commitrefs(*commitrefs): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 669 | """Returns binary encoded commit hashes for one or more commitrefs. |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 670 | |
| 671 | A commitref is anything which can resolve to a commit. Popular examples: |
| 672 | * 'HEAD' |
Josip Sokcevic | 9c0dc30 | 2020-11-20 18:41:25 +0000 | [diff] [blame] | 673 | * 'origin/main' |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 674 | * 'cool_branch~2' |
| 675 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 676 | try: |
| 677 | return [binascii.unhexlify(h) for h in hash_multi(*commitrefs)] |
| 678 | except subprocess2.CalledProcessError: |
| 679 | raise BadCommitRefException(commitrefs) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 680 | |
| 681 | |
sbc@chromium.org | 384039b | 2014-10-13 21:01:00 +0000 | [diff] [blame] | 682 | RebaseRet = collections.namedtuple('RebaseRet', 'success stdout stderr') |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 683 | |
| 684 | |
Robert Iannucci | d3acb16 | 2021-05-04 21:37:40 +0000 | [diff] [blame] | 685 | def rebase(parent, start, branch, abort=False, allow_gc=False): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 686 | """Rebases |start|..|branch| onto the branch |parent|. |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 687 | |
Robert Iannucci | d3acb16 | 2021-05-04 21:37:40 +0000 | [diff] [blame] | 688 | 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.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 691 | 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 Iannucci | d3acb16 | 2021-05-04 21:37:40 +0000 | [diff] [blame] | 697 | 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.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 701 | |
| 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 Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 708 | 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.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 729 | |
| 730 | |
| 731 | def remove_merge_base(branch): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 732 | del_branch_config(branch, 'base') |
| 733 | del_branch_config(branch, 'base-upstream') |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 734 | |
| 735 | |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 736 | def repo_root(): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 737 | """Returns the absolute path to the repository root.""" |
| 738 | return run('rev-parse', '--show-toplevel') |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 739 | |
| 740 | |
Jeffrey Yasskin | 6b52dc2 | 2019-12-06 18:32:21 +0000 | [diff] [blame] | 741 | def upstream_default(): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 742 | """Returns the default branch name of the origin repository.""" |
| 743 | try: |
Josip Sokcevic | 0642373 | 2021-03-31 19:04:42 +0000 | [diff] [blame] | 744 | ret = run('rev-parse', '--abbrev-ref', 'origin/HEAD') |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 745 | # 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 Yasskin | 6b52dc2 | 2019-12-06 18:32:21 +0000 | [diff] [blame] | 756 | |
| 757 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 758 | def root(): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 759 | return get_config('depot-tools.upstream', upstream_default()) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 760 | |
| 761 | |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 762 | @contextlib.contextmanager |
| 763 | def less(): # pragma: no cover |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 764 | """Runs 'less' as context manager yielding its stdin as a PIPE. |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 765 | |
| 766 | Automatically checks if sys.stdout is a non-TTY stream. If so, it avoids |
| 767 | running less and just yields sys.stdout. |
Edward Lemur | 0d462e9 | 2020-01-08 20:11:31 +0000 | [diff] [blame] | 768 | |
| 769 | The returned PIPE is opened on binary mode. |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 770 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 771 | 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.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 776 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 777 | # 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 Lemur | b800fde | 2020-01-10 23:04:44 +0000 | [diff] [blame] | 782 | try: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 783 | 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.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 792 | |
| 793 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 794 | def run(*cmd, **kwargs): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 795 | """The same as run_with_stderr, except it only returns stdout.""" |
| 796 | return run_with_stderr(*cmd, **kwargs)[0] |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 797 | |
| 798 | |
agable@chromium.org | d629fb4 | 2014-10-01 09:40:10 +0000 | [diff] [blame] | 799 | def run_with_retcode(*cmd, **kwargs): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 800 | """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.org | d629fb4 | 2014-10-01 09:40:10 +0000 | [diff] [blame] | 807 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 808 | def run_stream(*cmd, **kwargs): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 809 | """Runs a git command. Returns stdout as a PIPE (file-like object). |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 810 | |
| 811 | stderr is dropped to avoid races if the process outputs to both stdout and |
| 812 | stderr. |
| 813 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 814 | 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.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 820 | |
| 821 | |
tandrii@chromium.org | 6c14310 | 2015-06-11 19:21:02 +0000 | [diff] [blame] | 822 | @contextlib.contextmanager |
| 823 | def run_stream_with_retcode(*cmd, **kwargs): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 824 | """Runs a git command as context manager yielding stdout as a PIPE. |
tandrii@chromium.org | 6c14310 | 2015-06-11 19:21:02 +0000 | [diff] [blame] | 825 | |
| 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 Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 831 | 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.org | 6c14310 | 2015-06-11 19:21:02 +0000 | [diff] [blame] | 843 | |
| 844 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 845 | def run_with_stderr(*cmd, **kwargs): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 846 | """Runs a git command. |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 847 | |
| 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 Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 854 | 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.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 862 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 863 | 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.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 870 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 871 | if autostrip: |
| 872 | ret = (ret or b'').strip() |
| 873 | err = (err or b'').strip() |
Edward Lemur | 12a537f | 2019-10-03 21:57:15 +0000 | [diff] [blame] | 874 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 875 | if decode: |
| 876 | ret = ret.decode('utf-8', 'replace') |
| 877 | err = err.decode('utf-8', 'replace') |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 878 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 879 | return ret, err |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 880 | |
| 881 | |
| 882 | def set_branch_config(branch, option, value, scope='local'): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 883 | set_config('branch.%s.%s' % (branch, option), value, scope=scope) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 884 | |
| 885 | |
| 886 | def set_config(option, value, scope='local'): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 887 | run('config', '--' + scope, option, value) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 888 | |
agable@chromium.org | d629fb4 | 2014-10-01 09:40:10 +0000 | [diff] [blame] | 889 | |
sbc@chromium.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 890 | def get_dirty_files(): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 891 | # 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.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 894 | |
| 895 | |
| 896 | def is_dirty_git_tree(cmd): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 897 | w = lambda s: sys.stderr.write(s + "\n") |
iannucci | e38699b | 2016-08-15 17:32:31 -0700 | [diff] [blame] | 898 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 899 | 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.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 910 | |
| 911 | |
Greg NISBET | 923bcf8 | 2023-08-10 22:50:46 +0000 | [diff] [blame] | 912 | def status(ignore_submodules=None): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 913 | """Returns a parsed version of git-status. |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 914 | |
Greg NISBET | 923bcf8 | 2023-08-10 22:50:46 +0000 | [diff] [blame] | 915 | Args: |
| 916 | ignore_submodules (str|None): "all", "none", or None. |
| 917 | None is equivalent to "none". |
| 918 | |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 919 | 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 Vasudevan | c71efb5 | 2023-08-29 23:02:15 +0000 | [diff] [blame] | 922 | * rstat is the right status code letter from git-status |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 923 | * src is the current name of the file, or the original name of the file |
| 924 | if lstat == 'R' |
| 925 | """ |
Greg NISBET | 923bcf8 | 2023-08-10 22:50:46 +0000 | [diff] [blame] | 926 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 927 | ignore_submodules = ignore_submodules or 'none' |
| 928 | assert ignore_submodules in ( |
| 929 | 'all', |
| 930 | 'none'), f'ignore_submodules value {ignore_submodules} is invalid' |
Greg NISBET | 923bcf8 | 2023-08-10 22:50:46 +0000 | [diff] [blame] | 931 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 932 | stat_entry = collections.namedtuple('stat_entry', 'lstat rstat src') |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 933 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 934 | 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) |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 945 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 946 | 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)) |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 959 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 960 | return parser( |
| 961 | tokenizer( |
| 962 | run_stream('status', |
| 963 | '-z', |
| 964 | f'--ignore-submodules={ignore_submodules}', |
| 965 | bufsize=-1))) |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 966 | |
| 967 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 968 | def squash_current_branch(header=None, merge_base=None): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 969 | 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.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 977 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 978 | 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 |
Josip Sokcevic | 4a44284 | 2023-09-13 20:42:53 +0000 | [diff] [blame^] | 983 | |
| 984 | # git reset --soft will stage all changes so we can just commit those. |
| 985 | # Note: Just before reset --soft is called, we may have git submodules |
| 986 | # checked to an old commit (not latest state). We don't want to include |
| 987 | # those in our commit. |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 988 | run('commit', |
| 989 | '--no-verify', |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 990 | '-F', |
| 991 | '-', |
| 992 | indata=log_msg.encode('utf-8')) |
| 993 | return True |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 994 | |
| 995 | |
iannucci@chromium.org | 8bc9b5c | 2014-03-12 01:36:18 +0000 | [diff] [blame] | 996 | def tags(*args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 997 | return run('tag', *args).splitlines() |
iannucci@chromium.org | 8bc9b5c | 2014-03-12 01:36:18 +0000 | [diff] [blame] | 998 | |
| 999 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 1000 | def thaw(): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1001 | took_action = False |
| 1002 | with run_stream('rev-list', 'HEAD') as stream: |
| 1003 | for sha in stream: |
| 1004 | sha = sha.strip().decode('utf-8') |
| 1005 | msg = run('show', '--format=%f%b', '-s', 'HEAD') |
| 1006 | match = FREEZE_MATCHER.match(msg) |
| 1007 | if not match: |
| 1008 | if not took_action: |
| 1009 | return 'Nothing to thaw.' |
| 1010 | break |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 1011 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1012 | run('reset', '--' + FREEZE_SECTIONS[match.group(1)], sha) |
| 1013 | took_action = True |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 1014 | |
| 1015 | |
| 1016 | def topo_iter(branch_tree, top_down=True): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1017 | """Generates (branch, parent) in topographical order for a branch tree. |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 1018 | |
| 1019 | Given a tree: |
| 1020 | |
| 1021 | A1 |
| 1022 | B1 B2 |
| 1023 | C1 C2 C3 |
| 1024 | D1 |
| 1025 | |
| 1026 | branch_tree would look like: { |
| 1027 | 'D1': 'C3', |
| 1028 | 'C3': 'B2', |
| 1029 | 'B2': 'A1', |
| 1030 | 'C1': 'B1', |
| 1031 | 'C2': 'B1', |
| 1032 | 'B1': 'A1', |
| 1033 | } |
| 1034 | |
| 1035 | It is OK to have multiple 'root' nodes in your graph. |
| 1036 | |
| 1037 | if top_down is True, items are yielded from A->D. Otherwise they're yielded |
| 1038 | from D->A. Within a layer the branches will be yielded in sorted order. |
| 1039 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1040 | branch_tree = branch_tree.copy() |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 1041 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1042 | # TODO(iannucci): There is probably a more efficient way to do these. |
| 1043 | if top_down: |
| 1044 | while branch_tree: |
| 1045 | this_pass = [(b, p) for b, p in branch_tree.items() |
| 1046 | if p not in branch_tree] |
| 1047 | assert this_pass, "Branch tree has cycles: %r" % branch_tree |
| 1048 | for branch, parent in sorted(this_pass): |
| 1049 | yield branch, parent |
| 1050 | del branch_tree[branch] |
| 1051 | else: |
| 1052 | parent_to_branches = collections.defaultdict(set) |
| 1053 | for branch, parent in branch_tree.items(): |
| 1054 | parent_to_branches[parent].add(branch) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 1055 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1056 | while branch_tree: |
| 1057 | this_pass = [(b, p) for b, p in branch_tree.items() |
| 1058 | if not parent_to_branches[b]] |
| 1059 | assert this_pass, "Branch tree has cycles: %r" % branch_tree |
| 1060 | for branch, parent in sorted(this_pass): |
| 1061 | yield branch, parent |
| 1062 | parent_to_branches[parent].discard(branch) |
| 1063 | del branch_tree[branch] |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 1064 | |
| 1065 | |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 1066 | def tree(treeref, recurse=False): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1067 | """Returns a dict representation of a git tree object. |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 1068 | |
| 1069 | Args: |
| 1070 | treeref (str) - a git ref which resolves to a tree (commits count as trees). |
qyearsley | 12fa6ff | 2016-08-24 09:18:40 -0700 | [diff] [blame] | 1071 | recurse (bool) - include all of the tree's descendants too. File names will |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 1072 | take the form of 'some/path/to/file'. |
| 1073 | |
| 1074 | Return format: |
| 1075 | { 'file_name': (mode, type, ref) } |
| 1076 | |
| 1077 | mode is an integer where: |
| 1078 | * 0040000 - Directory |
| 1079 | * 0100644 - Regular non-executable file |
| 1080 | * 0100664 - Regular non-executable group-writeable file |
| 1081 | * 0100755 - Regular executable file |
| 1082 | * 0120000 - Symbolic link |
| 1083 | * 0160000 - Gitlink |
| 1084 | |
| 1085 | type is a string where it's one of 'blob', 'commit', 'tree', 'tag'. |
| 1086 | |
| 1087 | ref is the hex encoded hash of the entry. |
| 1088 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1089 | ret = {} |
| 1090 | opts = ['ls-tree', '--full-tree'] |
| 1091 | if recurse: |
| 1092 | opts.append('-r') |
| 1093 | opts.append(treeref) |
| 1094 | try: |
| 1095 | for line in run(*opts).splitlines(): |
| 1096 | mode, typ, ref, name = line.split(None, 3) |
| 1097 | ret[name] = (mode, typ, ref) |
| 1098 | except subprocess2.CalledProcessError: |
| 1099 | return None |
| 1100 | return ret |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 1101 | |
| 1102 | |
Mun Yong Jang | 781e71e | 2017-10-25 15:46:20 -0700 | [diff] [blame] | 1103 | def get_remote_url(remote='origin'): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1104 | try: |
| 1105 | return run('config', 'remote.%s.url' % remote) |
| 1106 | except subprocess2.CalledProcessError: |
| 1107 | return None |
Mun Yong Jang | 781e71e | 2017-10-25 15:46:20 -0700 | [diff] [blame] | 1108 | |
| 1109 | |
iannucci@chromium.org | 8bc9b5c | 2014-03-12 01:36:18 +0000 | [diff] [blame] | 1110 | def upstream(branch): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1111 | try: |
| 1112 | return run('rev-parse', '--abbrev-ref', '--symbolic-full-name', |
| 1113 | branch + '@{upstream}') |
| 1114 | except subprocess2.CalledProcessError: |
| 1115 | return None |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 1116 | |
agable@chromium.org | d629fb4 | 2014-10-01 09:40:10 +0000 | [diff] [blame] | 1117 | |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 1118 | def get_git_version(): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1119 | """Returns a tuple that contains the numeric components of the current git |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 1120 | version.""" |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1121 | version_string = run('--version') |
| 1122 | version_match = re.search(r'(\d+.)+(\d+)', version_string) |
| 1123 | version = version_match.group() if version_match else '' |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 1124 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1125 | return tuple(int(x) for x in version.split('.')) |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 1126 | |
| 1127 | |
calamity@chromium.org | 745ffa6 | 2014-09-08 01:03:19 +0000 | [diff] [blame] | 1128 | def get_branches_info(include_tracking_status): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1129 | format_string = ( |
| 1130 | '--format=%(refname:short):%(objectname:short):%(upstream:short):') |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 1131 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1132 | # This is not covered by the depot_tools CQ which only has git version 1.8. |
| 1133 | if (include_tracking_status and get_git_version() >= |
| 1134 | MIN_UPSTREAM_TRACK_GIT_VERSION): # pragma: no cover |
| 1135 | format_string += '%(upstream:track)' |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 1136 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1137 | info_map = {} |
| 1138 | data = run('for-each-ref', format_string, 'refs/heads') |
| 1139 | BranchesInfo = collections.namedtuple('BranchesInfo', |
| 1140 | 'hash upstream commits behind') |
| 1141 | for line in data.splitlines(): |
| 1142 | (branch, branch_hash, upstream_branch, |
| 1143 | tracking_status) = line.split(':') |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 1144 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1145 | commits = None |
| 1146 | if include_tracking_status: |
| 1147 | base = get_or_create_merge_base(branch) |
| 1148 | if base: |
| 1149 | commits_list = run('rev-list', '--count', branch, '^%s' % base, |
| 1150 | '--') |
| 1151 | commits = int(commits_list) or None |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 1152 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1153 | behind_match = re.search(r'behind (\d+)', tracking_status) |
| 1154 | behind = int(behind_match.group(1)) if behind_match else None |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 1155 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1156 | info_map[branch] = BranchesInfo(hash=branch_hash, |
| 1157 | upstream=upstream_branch, |
| 1158 | commits=commits, |
| 1159 | behind=behind) |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 1160 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1161 | # Set None for upstreams which are not branches (e.g empty upstream, remotes |
| 1162 | # and deleted upstream branches). |
| 1163 | missing_upstreams = {} |
| 1164 | for info in info_map.values(): |
| 1165 | if (info.upstream not in info_map |
| 1166 | and info.upstream not in missing_upstreams): |
| 1167 | missing_upstreams[info.upstream] = None |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 1168 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1169 | result = info_map.copy() |
| 1170 | result.update(missing_upstreams) |
| 1171 | return result |
sammc@chromium.org | 900a33f | 2015-09-29 06:57:09 +0000 | [diff] [blame] | 1172 | |
| 1173 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1174 | def make_workdir_common(repository, |
| 1175 | new_workdir, |
| 1176 | files_to_symlink, |
| 1177 | files_to_copy, |
| 1178 | symlink=None): |
| 1179 | if not symlink: |
| 1180 | symlink = os.symlink |
| 1181 | os.makedirs(new_workdir) |
| 1182 | for entry in files_to_symlink: |
| 1183 | clone_file(repository, new_workdir, entry, symlink) |
| 1184 | for entry in files_to_copy: |
| 1185 | clone_file(repository, new_workdir, entry, shutil.copy) |
sammc@chromium.org | 900a33f | 2015-09-29 06:57:09 +0000 | [diff] [blame] | 1186 | |
| 1187 | |
| 1188 | def make_workdir(repository, new_workdir): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1189 | GIT_DIRECTORY_WHITELIST = [ |
| 1190 | 'config', |
| 1191 | 'info', |
| 1192 | 'hooks', |
| 1193 | 'logs/refs', |
| 1194 | 'objects', |
| 1195 | 'packed-refs', |
| 1196 | 'refs', |
| 1197 | 'remotes', |
| 1198 | 'rr-cache', |
| 1199 | 'shallow', |
| 1200 | ] |
| 1201 | make_workdir_common(repository, new_workdir, GIT_DIRECTORY_WHITELIST, |
| 1202 | ['HEAD']) |
sammc@chromium.org | 900a33f | 2015-09-29 06:57:09 +0000 | [diff] [blame] | 1203 | |
| 1204 | |
| 1205 | def clone_file(repository, new_workdir, link, operation): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1206 | if not os.path.exists(os.path.join(repository, link)): |
| 1207 | return |
| 1208 | link_dir = os.path.dirname(os.path.join(new_workdir, link)) |
| 1209 | if not os.path.exists(link_dir): |
| 1210 | os.makedirs(link_dir) |
| 1211 | src = os.path.join(repository, link) |
| 1212 | if os.path.islink(src): |
| 1213 | src = os.path.realpath(src) |
| 1214 | operation(src, os.path.join(new_workdir, link)) |