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 | |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 14 | def wrapper(func): |
| 15 | def wrap(self, timeout=None): |
Josip Sokcevic | de6c456 | 2020-03-26 00:39:42 +0000 | [diff] [blame] | 16 | default_timeout = (1 << 31 if sys.version_info.major == 2 else |
| 17 | threading.TIMEOUT_MAX) |
| 18 | return func(self, timeout=timeout or default_timeout) |
| 19 | |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 20 | return wrap |
| 21 | IMapIterator.next = wrapper(IMapIterator.next) |
| 22 | IMapIterator.__next__ = IMapIterator.next |
| 23 | # TODO(iannucci): Monkeypatch all other 'wait' methods too. |
| 24 | |
| 25 | |
| 26 | import binascii |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 27 | import collections |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 28 | import contextlib |
| 29 | import functools |
| 30 | import logging |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 31 | import os |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 32 | import re |
iannucci@chromium.org | 596cd5c | 2016-04-04 21:34:39 +0000 | [diff] [blame] | 33 | import setup_color |
sammc@chromium.org | 900a33f | 2015-09-29 06:57:09 +0000 | [diff] [blame] | 34 | import shutil |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 35 | import signal |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 36 | import tempfile |
iannucci@chromium.org | 3f23cdf | 2014-04-15 20:02:44 +0000 | [diff] [blame] | 37 | import textwrap |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 38 | |
| 39 | import subprocess2 |
| 40 | |
Raul Tambre | c2f74c1 | 2019-03-19 05:55:53 +0000 | [diff] [blame] | 41 | from io import BytesIO |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 42 | |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 43 | |
| 44 | ROOT = os.path.abspath(os.path.dirname(__file__)) |
iannucci@chromium.org | 0d9e59c | 2016-01-09 08:08:41 +0000 | [diff] [blame] | 45 | IS_WIN = sys.platform == 'win32' |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 46 | TEST_MODE = False |
| 47 | |
Dan Jacques | 209a681 | 2017-07-12 11:40:20 -0700 | [diff] [blame] | 48 | |
| 49 | def win_find_git(): |
| 50 | for elem in os.environ.get('PATH', '').split(os.pathsep): |
| 51 | for candidate in ('git.exe', 'git.bat'): |
| 52 | path = os.path.join(elem, candidate) |
| 53 | if os.path.isfile(path): |
| 54 | return path |
| 55 | raise ValueError('Could not find Git on PATH.') |
| 56 | |
| 57 | |
| 58 | GIT_EXE = 'git' if not IS_WIN else win_find_git() |
| 59 | |
| 60 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 61 | FREEZE = 'FREEZE' |
| 62 | FREEZE_SECTIONS = { |
| 63 | 'indexed': 'soft', |
| 64 | 'unindexed': 'mixed' |
| 65 | } |
| 66 | FREEZE_MATCHER = re.compile(r'%s.(%s)' % (FREEZE, '|'.join(FREEZE_SECTIONS))) |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 67 | |
| 68 | |
Dan Jacques | 2f8b0c1 | 2017-04-05 12:57:21 -0700 | [diff] [blame] | 69 | # NOTE: This list is DEPRECATED in favor of the Infra Git wrapper: |
Josip Sokcevic | 9c0dc30 | 2020-11-20 18:41:25 +0000 | [diff] [blame] | 70 | # https://chromium.googlesource.com/infra/infra/+/HEAD/go/src/infra/tools/git |
Dan Jacques | 2f8b0c1 | 2017-04-05 12:57:21 -0700 | [diff] [blame] | 71 | # |
| 72 | # New entries should be added to the Git wrapper, NOT to this list. "git_retry" |
| 73 | # is, similarly, being deprecated in favor of the Git wrapper. |
| 74 | # |
| 75 | # --- |
| 76 | # |
dnj@chromium.org | de219ec | 2014-07-28 17:39:08 +0000 | [diff] [blame] | 77 | # Retry a git operation if git returns a error response with any of these |
| 78 | # messages. It's all observed 'bad' GoB responses so far. |
| 79 | # |
| 80 | # This list is inspired/derived from the one in ChromiumOS's Chromite: |
| 81 | # <CHROMITE>/lib/git.py::GIT_TRANSIENT_ERRORS |
| 82 | # |
| 83 | # It was last imported from '7add3ac29564d98ac35ce426bc295e743e7c0c02'. |
| 84 | GIT_TRANSIENT_ERRORS = ( |
| 85 | # crbug.com/285832 |
iannucci@chromium.org | 6e95d40 | 2014-08-29 22:10:55 +0000 | [diff] [blame] | 86 | r'!.*\[remote rejected\].*\(error in hook\)', |
dnj@chromium.org | de219ec | 2014-07-28 17:39:08 +0000 | [diff] [blame] | 87 | |
| 88 | # crbug.com/289932 |
iannucci@chromium.org | 6e95d40 | 2014-08-29 22:10:55 +0000 | [diff] [blame] | 89 | r'!.*\[remote rejected\].*\(failed to lock\)', |
dnj@chromium.org | de219ec | 2014-07-28 17:39:08 +0000 | [diff] [blame] | 90 | |
| 91 | # crbug.com/307156 |
iannucci@chromium.org | 6e95d40 | 2014-08-29 22:10:55 +0000 | [diff] [blame] | 92 | r'!.*\[remote rejected\].*\(error in Gerrit backend\)', |
dnj@chromium.org | de219ec | 2014-07-28 17:39:08 +0000 | [diff] [blame] | 93 | |
| 94 | # crbug.com/285832 |
| 95 | r'remote error: Internal Server Error', |
| 96 | |
| 97 | # crbug.com/294449 |
| 98 | r'fatal: Couldn\'t find remote ref ', |
| 99 | |
| 100 | # crbug.com/220543 |
| 101 | r'git fetch_pack: expected ACK/NAK, got', |
| 102 | |
| 103 | # crbug.com/189455 |
| 104 | r'protocol error: bad pack header', |
| 105 | |
| 106 | # crbug.com/202807 |
| 107 | r'The remote end hung up unexpectedly', |
| 108 | |
| 109 | # crbug.com/298189 |
| 110 | r'TLS packet with unexpected length was received', |
| 111 | |
| 112 | # crbug.com/187444 |
| 113 | r'RPC failed; result=\d+, HTTP code = \d+', |
| 114 | |
dnj@chromium.org | de219ec | 2014-07-28 17:39:08 +0000 | [diff] [blame] | 115 | # crbug.com/388876 |
| 116 | r'Connection timed out', |
dnj@chromium.org | 45cddd6 | 2014-11-06 19:36:42 +0000 | [diff] [blame] | 117 | |
| 118 | # crbug.com/430343 |
| 119 | # TODO(dnj): Resync with Chromite. |
| 120 | r'The requested URL returned error: 5\d+', |
Arikon | b3a2148 | 2016-07-22 10:12:24 -0700 | [diff] [blame] | 121 | |
| 122 | r'Connection reset by peer', |
| 123 | |
| 124 | r'Unable to look up', |
| 125 | |
| 126 | r'Couldn\'t resolve host', |
dnj@chromium.org | de219ec | 2014-07-28 17:39:08 +0000 | [diff] [blame] | 127 | ) |
| 128 | |
| 129 | GIT_TRANSIENT_ERRORS_RE = re.compile('|'.join(GIT_TRANSIENT_ERRORS), |
| 130 | re.IGNORECASE) |
| 131 | |
raphael.kubo.da.costa@intel.com | 58d05b0 | 2015-06-24 08:54:41 +0000 | [diff] [blame] | 132 | # git's for-each-ref command first supported the upstream:track token in its |
| 133 | # format string in version 1.9.0, but some usages were broken until 2.3.0. |
| 134 | # See git commit b6160d95 for more information. |
| 135 | MIN_UPSTREAM_TRACK_GIT_VERSION = (2, 3) |
dnj@chromium.org | de219ec | 2014-07-28 17:39:08 +0000 | [diff] [blame] | 136 | |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 137 | class BadCommitRefException(Exception): |
| 138 | def __init__(self, refs): |
| 139 | msg = ('one of %s does not seem to be a valid commitref.' % |
| 140 | str(refs)) |
| 141 | super(BadCommitRefException, self).__init__(msg) |
| 142 | |
| 143 | |
| 144 | def memoize_one(**kwargs): |
| 145 | """Memoizes a single-argument pure function. |
| 146 | |
| 147 | Values of None are not cached. |
| 148 | |
| 149 | Kwargs: |
| 150 | threadsafe (bool) - REQUIRED. Specifies whether to use locking around |
| 151 | cache manipulation functions. This is a kwarg so that users of memoize_one |
| 152 | are forced to explicitly and verbosely pick True or False. |
| 153 | |
| 154 | Adds three methods to the decorated function: |
| 155 | * get(key, default=None) - Gets the value for this key from the cache. |
| 156 | * set(key, value) - Sets the value for this key from the cache. |
| 157 | * clear() - Drops the entire contents of the cache. Useful for unittests. |
| 158 | * update(other) - Updates the contents of the cache from another dict. |
| 159 | """ |
| 160 | assert 'threadsafe' in kwargs, 'Must specify threadsafe={True,False}' |
| 161 | threadsafe = kwargs['threadsafe'] |
| 162 | |
| 163 | if threadsafe: |
| 164 | def withlock(lock, f): |
| 165 | def inner(*args, **kwargs): |
| 166 | with lock: |
| 167 | return f(*args, **kwargs) |
| 168 | return inner |
| 169 | else: |
| 170 | def withlock(_lock, f): |
| 171 | return f |
| 172 | |
| 173 | def decorator(f): |
| 174 | # Instantiate the lock in decorator, in case users of memoize_one do: |
| 175 | # |
| 176 | # memoizer = memoize_one(threadsafe=True) |
| 177 | # |
| 178 | # @memoizer |
| 179 | # def fn1(val): ... |
| 180 | # |
| 181 | # @memoizer |
| 182 | # def fn2(val): ... |
| 183 | |
| 184 | lock = threading.Lock() if threadsafe else None |
| 185 | cache = {} |
| 186 | _get = withlock(lock, cache.get) |
| 187 | _set = withlock(lock, cache.__setitem__) |
| 188 | |
| 189 | @functools.wraps(f) |
| 190 | def inner(arg): |
| 191 | ret = _get(arg) |
| 192 | if ret is None: |
| 193 | ret = f(arg) |
| 194 | if ret is not None: |
| 195 | _set(arg, ret) |
| 196 | return ret |
| 197 | inner.get = _get |
| 198 | inner.set = _set |
| 199 | inner.clear = withlock(lock, cache.clear) |
| 200 | inner.update = withlock(lock, cache.update) |
| 201 | return inner |
| 202 | return decorator |
| 203 | |
| 204 | |
| 205 | def _ScopedPool_initer(orig, orig_args): # pragma: no cover |
| 206 | """Initializer method for ScopedPool's subprocesses. |
| 207 | |
| 208 | This helps ScopedPool handle Ctrl-C's correctly. |
| 209 | """ |
| 210 | signal.signal(signal.SIGINT, signal.SIG_IGN) |
| 211 | if orig: |
| 212 | orig(*orig_args) |
| 213 | |
| 214 | |
| 215 | @contextlib.contextmanager |
| 216 | def ScopedPool(*args, **kwargs): |
| 217 | """Context Manager which returns a multiprocessing.pool instance which |
| 218 | correctly deals with thrown exceptions. |
| 219 | |
| 220 | *args - Arguments to multiprocessing.pool |
| 221 | |
| 222 | Kwargs: |
| 223 | kind ('threads', 'procs') - The type of underlying coprocess to use. |
| 224 | **etc - Arguments to multiprocessing.pool |
| 225 | """ |
| 226 | if kwargs.pop('kind', None) == 'threads': |
| 227 | pool = multiprocessing.pool.ThreadPool(*args, **kwargs) |
| 228 | else: |
| 229 | orig, orig_args = kwargs.get('initializer'), kwargs.get('initargs', ()) |
| 230 | kwargs['initializer'] = _ScopedPool_initer |
| 231 | kwargs['initargs'] = orig, orig_args |
| 232 | pool = multiprocessing.pool.Pool(*args, **kwargs) |
| 233 | |
| 234 | try: |
| 235 | yield pool |
| 236 | pool.close() |
| 237 | except: |
| 238 | pool.terminate() |
| 239 | raise |
| 240 | finally: |
| 241 | pool.join() |
| 242 | |
| 243 | |
| 244 | class ProgressPrinter(object): |
| 245 | """Threaded single-stat status message printer.""" |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 246 | def __init__(self, fmt, enabled=None, fout=sys.stderr, period=0.5): |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 247 | """Create a ProgressPrinter. |
| 248 | |
| 249 | Use it as a context manager which produces a simple 'increment' method: |
| 250 | |
| 251 | with ProgressPrinter('(%%(count)d/%d)' % 1000) as inc: |
| 252 | for i in xrange(1000): |
| 253 | # do stuff |
| 254 | if i % 10 == 0: |
| 255 | inc(10) |
| 256 | |
| 257 | Args: |
| 258 | fmt - String format with a single '%(count)d' where the counter value |
| 259 | should go. |
| 260 | enabled (bool) - If this is None, will default to True if |
| 261 | logging.getLogger() is set to INFO or more verbose. |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 262 | fout (file-like) - The stream to print status messages to. |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 263 | period (float) - The time in seconds for the printer thread to wait |
| 264 | between printing. |
| 265 | """ |
| 266 | self.fmt = fmt |
| 267 | if enabled is None: # pragma: no cover |
| 268 | self.enabled = logging.getLogger().isEnabledFor(logging.INFO) |
| 269 | else: |
| 270 | self.enabled = enabled |
| 271 | |
| 272 | self._count = 0 |
| 273 | self._dead = False |
| 274 | self._dead_cond = threading.Condition() |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 275 | self._stream = fout |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 276 | self._thread = threading.Thread(target=self._run) |
| 277 | self._period = period |
| 278 | |
| 279 | def _emit(self, s): |
| 280 | if self.enabled: |
| 281 | self._stream.write('\r' + s) |
| 282 | self._stream.flush() |
| 283 | |
| 284 | def _run(self): |
| 285 | with self._dead_cond: |
| 286 | while not self._dead: |
| 287 | self._emit(self.fmt % {'count': self._count}) |
| 288 | self._dead_cond.wait(self._period) |
| 289 | self._emit((self.fmt + '\n') % {'count': self._count}) |
| 290 | |
| 291 | def inc(self, amount=1): |
| 292 | self._count += amount |
| 293 | |
| 294 | def __enter__(self): |
| 295 | self._thread.start() |
| 296 | return self.inc |
| 297 | |
| 298 | def __exit__(self, _exc_type, _exc_value, _traceback): |
| 299 | self._dead = True |
| 300 | with self._dead_cond: |
| 301 | self._dead_cond.notifyAll() |
| 302 | self._thread.join() |
| 303 | del self._thread |
| 304 | |
| 305 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 306 | def once(function): |
| 307 | """@Decorates |function| so that it only performs its action once, no matter |
| 308 | how many times the decorated |function| is called.""" |
Edward Lemur | 12a537f | 2019-10-03 21:57:15 +0000 | [diff] [blame] | 309 | has_run = [False] |
| 310 | def _wrapper(*args, **kwargs): |
| 311 | if not has_run[0]: |
| 312 | has_run[0] = True |
| 313 | function(*args, **kwargs) |
| 314 | return _wrapper |
| 315 | |
| 316 | |
| 317 | def unicode_repr(s): |
| 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 | |
agable | 7aa2ddd | 2016-06-21 07:47:00 -0700 | [diff] [blame] | 324 | def die(message, *args): |
Raul Tambre | c2f74c1 | 2019-03-19 05:55:53 +0000 | [diff] [blame] | 325 | print(textwrap.dedent(message % args), file=sys.stderr) |
agable | 7aa2ddd | 2016-06-21 07:47:00 -0700 | [diff] [blame] | 326 | sys.exit(1) |
| 327 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 328 | |
Mark Mentovai | f548d08 | 2017-03-08 13:32:00 -0500 | [diff] [blame] | 329 | def blame(filename, revision=None, porcelain=False, abbrev=None, *_args): |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 330 | command = ['blame'] |
| 331 | if porcelain: |
| 332 | command.append('-p') |
| 333 | if revision is not None: |
| 334 | command.append(revision) |
Mark Mentovai | f548d08 | 2017-03-08 13:32:00 -0500 | [diff] [blame] | 335 | if abbrev is not None: |
| 336 | command.append('--abbrev=%d' % abbrev) |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 337 | command.extend(['--', filename]) |
| 338 | return run(*command) |
| 339 | |
| 340 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 341 | def branch_config(branch, option, default=None): |
agable | 7aa2ddd | 2016-06-21 07:47:00 -0700 | [diff] [blame] | 342 | return get_config('branch.%s.%s' % (branch, option), default=default) |
iannucci@chromium.org | 0d9e59c | 2016-01-09 08:08:41 +0000 | [diff] [blame] | 343 | |
| 344 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 345 | def branch_config_map(option): |
| 346 | """Return {branch: <|option| value>} for all branches.""" |
| 347 | try: |
| 348 | reg = re.compile(r'^branch\.(.*)\.%s$' % option) |
agable | 7aa2ddd | 2016-06-21 07:47:00 -0700 | [diff] [blame] | 349 | lines = get_config_regexp(reg.pattern) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 350 | return {reg.match(k).group(1): v for k, v in (l.split() for l in lines)} |
| 351 | except subprocess2.CalledProcessError: |
| 352 | return {} |
| 353 | |
| 354 | |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 355 | def branches(use_limit=True, *args): |
akuegel@chromium.org | 58888e1 | 2015-06-09 15:26:37 +0000 | [diff] [blame] | 356 | NO_BRANCH = ('* (no branch', '* (detached', '* (HEAD detached') |
iannucci@chromium.org | 3f23cdf | 2014-04-15 20:02:44 +0000 | [diff] [blame] | 357 | |
| 358 | key = 'depot-tools.branch-limit' |
agable | 7aa2ddd | 2016-06-21 07:47:00 -0700 | [diff] [blame] | 359 | limit = get_config_int(key, 20) |
iannucci@chromium.org | 3f23cdf | 2014-04-15 20:02:44 +0000 | [diff] [blame] | 360 | |
| 361 | raw_branches = run('branch', *args).splitlines() |
| 362 | |
| 363 | num = len(raw_branches) |
iannucci@chromium.org | 3f23cdf | 2014-04-15 20:02:44 +0000 | [diff] [blame] | 364 | |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 365 | if use_limit and num > limit: |
agable | 7aa2ddd | 2016-06-21 07:47:00 -0700 | [diff] [blame] | 366 | die("""\ |
| 367 | Your git repo has too many branches (%d/%d) for this tool to work well. |
| 368 | |
| 369 | You may adjust this limit by running: |
iannucci@chromium.org | 3f23cdf | 2014-04-15 20:02:44 +0000 | [diff] [blame] | 370 | git config %s <new_limit> |
agable | 7aa2ddd | 2016-06-21 07:47:00 -0700 | [diff] [blame] | 371 | |
| 372 | You may also try cleaning up your old branches by running: |
| 373 | git cl archive |
| 374 | """, num, limit, key) |
iannucci@chromium.org | 3f23cdf | 2014-04-15 20:02:44 +0000 | [diff] [blame] | 375 | |
| 376 | for line in raw_branches: |
iannucci@chromium.org | 8bc9b5c | 2014-03-12 01:36:18 +0000 | [diff] [blame] | 377 | if line.startswith(NO_BRANCH): |
| 378 | continue |
| 379 | yield line.split()[-1] |
| 380 | |
| 381 | |
agable | 7aa2ddd | 2016-06-21 07:47:00 -0700 | [diff] [blame] | 382 | def get_config(option, default=None): |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 383 | try: |
| 384 | return run('config', '--get', option) or default |
| 385 | except subprocess2.CalledProcessError: |
| 386 | return default |
| 387 | |
| 388 | |
agable | 7aa2ddd | 2016-06-21 07:47:00 -0700 | [diff] [blame] | 389 | def get_config_int(option, default=0): |
| 390 | assert isinstance(default, int) |
| 391 | try: |
| 392 | return int(get_config(option, default)) |
| 393 | except ValueError: |
| 394 | return default |
| 395 | |
| 396 | |
| 397 | def get_config_list(option): |
iannucci@chromium.org | 8bc9b5c | 2014-03-12 01:36:18 +0000 | [diff] [blame] | 398 | try: |
| 399 | return run('config', '--get-all', option).split() |
| 400 | except subprocess2.CalledProcessError: |
| 401 | return [] |
| 402 | |
| 403 | |
agable | 7aa2ddd | 2016-06-21 07:47:00 -0700 | [diff] [blame] | 404 | def get_config_regexp(pattern): |
| 405 | if IS_WIN: # pragma: no cover |
| 406 | # this madness is because we call git.bat which calls git.exe which calls |
| 407 | # bash.exe (or something to that effect). Each layer divides the number of |
| 408 | # ^'s by 2. |
| 409 | pattern = pattern.replace('^', '^' * 8) |
| 410 | return run('config', '--get-regexp', pattern).splitlines() |
| 411 | |
| 412 | |
iannucci@chromium.org | 8bc9b5c | 2014-03-12 01:36:18 +0000 | [diff] [blame] | 413 | def current_branch(): |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 414 | try: |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 415 | return run('rev-parse', '--abbrev-ref', 'HEAD') |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 416 | except subprocess2.CalledProcessError: |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 417 | return None |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 418 | |
| 419 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 420 | def del_branch_config(branch, option, scope='local'): |
| 421 | del_config('branch.%s.%s' % (branch, option), scope=scope) |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 422 | |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 423 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 424 | def del_config(option, scope='local'): |
| 425 | try: |
| 426 | run('config', '--' + scope, '--unset', option) |
| 427 | except subprocess2.CalledProcessError: |
| 428 | pass |
| 429 | |
| 430 | |
mgiuca@chromium.org | 01d2cde | 2016-02-05 03:25:41 +0000 | [diff] [blame] | 431 | def diff(oldrev, newrev, *args): |
| 432 | return run('diff', oldrev, newrev, *args) |
| 433 | |
| 434 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 435 | def freeze(): |
| 436 | took_action = False |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 437 | key = 'depot-tools.freeze-size-limit' |
| 438 | MB = 2**20 |
| 439 | limit_mb = get_config_int(key, 100) |
| 440 | untracked_bytes = 0 |
| 441 | |
iannucci | eaca033 | 2016-08-03 16:46:50 -0700 | [diff] [blame] | 442 | root_path = repo_root() |
| 443 | |
Robert Iannucci | 4e87f5b | 2023-07-13 19:51:33 +0000 | [diff] [blame] | 444 | # unindexed tracks all the files which are unindexed but we want to add to |
| 445 | # the `FREEZE.unindexed` commit. |
| 446 | unindexed = [] |
| 447 | |
| 448 | # will be set to true if there are any indexed files to commit. |
| 449 | have_indexed_files = False |
| 450 | |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 451 | for f, s in status(): |
| 452 | if is_unmerged(s): |
| 453 | die("Cannot freeze unmerged changes!") |
Robert Iannucci | 4e87f5b | 2023-07-13 19:51:33 +0000 | [diff] [blame] | 454 | if s.lstat not in ' ?': |
| 455 | # This covers all changes to indexed files. |
| 456 | # lstat = ' ' means that the file is tracked and modified, but wasn't |
| 457 | # added yet. |
| 458 | # lstat = '?' means that the file is untracked. |
| 459 | have_indexed_files = True |
| 460 | else: |
| 461 | unindexed.append(f.encode('utf-8')) |
| 462 | if s.lstat == '?' and limit_mb > 0: |
| 463 | untracked_bytes += os.lstat(os.path.join(root_path, f)).st_size |
| 464 | |
Bruce Dawson | 4bff3fd | 2018-01-04 14:44:23 -0800 | [diff] [blame] | 465 | if limit_mb > 0 and untracked_bytes > limit_mb * MB: |
| 466 | die("""\ |
| 467 | You appear to have too much untracked+unignored data in your git |
| 468 | checkout: %.1f / %d MB. |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 469 | |
Bruce Dawson | 4bff3fd | 2018-01-04 14:44:23 -0800 | [diff] [blame] | 470 | Run `git status` to see what it is. |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 471 | |
Bruce Dawson | 4bff3fd | 2018-01-04 14:44:23 -0800 | [diff] [blame] | 472 | In addition to making many git commands slower, this will prevent |
| 473 | depot_tools from freezing your in-progress changes. |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 474 | |
Bruce Dawson | 4bff3fd | 2018-01-04 14:44:23 -0800 | [diff] [blame] | 475 | You should add untracked data that you want to ignore to your repo's |
| 476 | .git/info/exclude |
| 477 | file. See `git help ignore` for the format of this file. |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 478 | |
Quinten Yearsley | 925cedb | 2020-04-13 17:49:39 +0000 | [diff] [blame] | 479 | 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] | 480 | freeze limit by running: |
| 481 | git config %s <new_limit> |
| 482 | Where <new_limit> is an integer threshold in megabytes.""", |
| 483 | untracked_bytes / (MB * 1.0), limit_mb, key) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 484 | |
Robert Iannucci | 4e87f5b | 2023-07-13 19:51:33 +0000 | [diff] [blame] | 485 | if have_indexed_files: |
| 486 | try: |
| 487 | run('commit', '--no-verify', '-m', f'{FREEZE}.indexed') |
| 488 | took_action = True |
| 489 | except subprocess2.CalledProcessError: |
| 490 | pass |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 491 | |
agable | 96e179b | 2016-06-24 10:32:51 -0700 | [diff] [blame] | 492 | add_errors = False |
Robert Iannucci | 4e87f5b | 2023-07-13 19:51:33 +0000 | [diff] [blame] | 493 | if unindexed: |
| 494 | try: |
| 495 | run('add', |
| 496 | '--pathspec-from-file', |
| 497 | '-', |
| 498 | '--ignore-errors', |
Robert Iannucci | 2f0147a | 2023-07-20 16:41:59 +0000 | [diff] [blame] | 499 | indata=b'\n'.join(unindexed), |
| 500 | cwd=root_path) |
Robert Iannucci | 4e87f5b | 2023-07-13 19:51:33 +0000 | [diff] [blame] | 501 | except subprocess2.CalledProcessError: |
| 502 | add_errors = True |
agable | 96e179b | 2016-06-24 10:32:51 -0700 | [diff] [blame] | 503 | |
Robert Iannucci | 4e87f5b | 2023-07-13 19:51:33 +0000 | [diff] [blame] | 504 | try: |
| 505 | run('commit', '--no-verify', '-m', f'{FREEZE}.unindexed') |
| 506 | took_action = True |
| 507 | except subprocess2.CalledProcessError: |
| 508 | pass |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 509 | |
agable | 96e179b | 2016-06-24 10:32:51 -0700 | [diff] [blame] | 510 | ret = [] |
| 511 | if add_errors: |
| 512 | ret.append('Failed to index some unindexed files.') |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 513 | if not took_action: |
agable | 96e179b | 2016-06-24 10:32:51 -0700 | [diff] [blame] | 514 | ret.append('Nothing to freeze.') |
| 515 | return ' '.join(ret) or None |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 516 | |
| 517 | |
Gavin Mak | 2cbe95c | 2023-03-06 22:39:56 +0000 | [diff] [blame] | 518 | def get_branch_tree(use_limit=False): |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 519 | """Get the dictionary of {branch: parent}, compatible with topo_iter. |
| 520 | |
| 521 | Returns a tuple of (skipped, <branch_tree dict>) where skipped is a set of |
| 522 | branches without upstream branches defined. |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 523 | """ |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 524 | skipped = set() |
| 525 | branch_tree = {} |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 526 | |
Gavin Mak | 2cbe95c | 2023-03-06 22:39:56 +0000 | [diff] [blame] | 527 | for branch in branches(use_limit=use_limit): |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 528 | parent = upstream(branch) |
| 529 | if not parent: |
| 530 | skipped.add(branch) |
| 531 | continue |
| 532 | branch_tree[branch] = parent |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 533 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 534 | return skipped, branch_tree |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 535 | |
| 536 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 537 | def get_or_create_merge_base(branch, parent=None): |
| 538 | """Finds the configured merge base for branch. |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 539 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 540 | 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] | 541 | """ |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 542 | base = branch_config(branch, 'base') |
iannucci@chromium.org | 10fbe87 | 2014-05-16 22:31:13 +0000 | [diff] [blame] | 543 | base_upstream = branch_config(branch, 'base-upstream') |
iannucci@chromium.org | edeaa81 | 2014-03-26 21:27:47 +0000 | [diff] [blame] | 544 | parent = parent or upstream(branch) |
sbc@chromium.org | 7970606 | 2015-01-14 21:18:12 +0000 | [diff] [blame] | 545 | if parent is None or branch is None: |
iannucci@chromium.org | 10fbe87 | 2014-05-16 22:31:13 +0000 | [diff] [blame] | 546 | return None |
Josip Sokcevic | a3d1aaf | 2021-07-16 18:26:45 +0000 | [diff] [blame] | 547 | actual_merge_base = run('merge-base', parent, branch) |
iannucci@chromium.org | edeaa81 | 2014-03-26 21:27:47 +0000 | [diff] [blame] | 548 | |
iannucci@chromium.org | 10fbe87 | 2014-05-16 22:31:13 +0000 | [diff] [blame] | 549 | if base_upstream != parent: |
| 550 | base = None |
| 551 | base_upstream = None |
| 552 | |
iannucci@chromium.org | edeaa81 | 2014-03-26 21:27:47 +0000 | [diff] [blame] | 553 | def is_ancestor(a, b): |
| 554 | return run_with_retcode('merge-base', '--is-ancestor', a, b) == 0 |
| 555 | |
clemensh@chromium.org | c3fe99d | 2016-04-19 08:39:55 +0000 | [diff] [blame] | 556 | if base and base != actual_merge_base: |
iannucci@chromium.org | edeaa81 | 2014-03-26 21:27:47 +0000 | [diff] [blame] | 557 | if not is_ancestor(base, branch): |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 558 | logging.debug('Found WRONG pre-set merge-base for %s: %s', branch, base) |
| 559 | base = None |
iannucci@chromium.org | edeaa81 | 2014-03-26 21:27:47 +0000 | [diff] [blame] | 560 | elif is_ancestor(base, actual_merge_base): |
| 561 | logging.debug('Found OLD pre-set merge-base for %s: %s', branch, base) |
| 562 | base = None |
| 563 | else: |
| 564 | 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] | 565 | |
| 566 | if not base: |
iannucci@chromium.org | edeaa81 | 2014-03-26 21:27:47 +0000 | [diff] [blame] | 567 | base = actual_merge_base |
iannucci@chromium.org | 10fbe87 | 2014-05-16 22:31:13 +0000 | [diff] [blame] | 568 | manual_merge_base(branch, base, parent) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 569 | |
| 570 | return base |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 571 | |
| 572 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 573 | def hash_multi(*reflike): |
| 574 | return run('rev-parse', *reflike).splitlines() |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 575 | |
| 576 | |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 577 | def hash_one(reflike, short=False): |
| 578 | args = ['rev-parse', reflike] |
| 579 | if short: |
| 580 | args.insert(1, '--short') |
| 581 | return run(*args) |
iannucci@chromium.org | 8bc9b5c | 2014-03-12 01:36:18 +0000 | [diff] [blame] | 582 | |
| 583 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 584 | def in_rebase(): |
| 585 | git_dir = run('rev-parse', '--git-dir') |
| 586 | return ( |
| 587 | os.path.exists(os.path.join(git_dir, 'rebase-merge')) or |
| 588 | os.path.exists(os.path.join(git_dir, 'rebase-apply'))) |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 589 | |
| 590 | |
| 591 | def intern_f(f, kind='blob'): |
| 592 | """Interns a file object into the git object store. |
| 593 | |
| 594 | Args: |
| 595 | f (file-like object) - The file-like object to intern |
| 596 | kind (git object type) - One of 'blob', 'commit', 'tree', 'tag'. |
| 597 | |
| 598 | Returns the git hash of the interned object (hex encoded). |
| 599 | """ |
| 600 | ret = run('hash-object', '-t', kind, '-w', '--stdin', stdin=f) |
| 601 | f.close() |
| 602 | return ret |
| 603 | |
| 604 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 605 | def is_dormant(branch): |
| 606 | # TODO(iannucci): Do an oldness check? |
| 607 | return branch_config(branch, 'dormant', 'false') != 'false' |
| 608 | |
| 609 | |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 610 | def is_unmerged(stat_value): |
| 611 | return ( |
| 612 | 'U' in (stat_value.lstat, stat_value.rstat) or |
| 613 | ((stat_value.lstat == stat_value.rstat) and stat_value.lstat in 'AD') |
| 614 | ) |
| 615 | |
| 616 | |
iannucci@chromium.org | 10fbe87 | 2014-05-16 22:31:13 +0000 | [diff] [blame] | 617 | def manual_merge_base(branch, base, parent): |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 618 | set_branch_config(branch, 'base', base) |
iannucci@chromium.org | 10fbe87 | 2014-05-16 22:31:13 +0000 | [diff] [blame] | 619 | set_branch_config(branch, 'base-upstream', parent) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 620 | |
| 621 | |
| 622 | def mktree(treedict): |
| 623 | """Makes a git tree object and returns its hash. |
| 624 | |
| 625 | See |tree()| for the values of mode, type, and ref. |
| 626 | |
| 627 | Args: |
| 628 | treedict - { name: (mode, type, ref) } |
| 629 | """ |
| 630 | with tempfile.TemporaryFile() as f: |
Edward Lemur | 12a537f | 2019-10-03 21:57:15 +0000 | [diff] [blame] | 631 | for name, (mode, typ, ref) in treedict.items(): |
Edward Lemur | 71681bf | 2019-10-09 23:46:20 +0000 | [diff] [blame] | 632 | f.write(('%s %s %s\t%s\0' % (mode, typ, ref, name)).encode('utf-8')) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 633 | f.seek(0) |
| 634 | return run('mktree', '-z', stdin=f) |
| 635 | |
| 636 | |
| 637 | def parse_commitrefs(*commitrefs): |
| 638 | """Returns binary encoded commit hashes for one or more commitrefs. |
| 639 | |
| 640 | A commitref is anything which can resolve to a commit. Popular examples: |
| 641 | * 'HEAD' |
Josip Sokcevic | 9c0dc30 | 2020-11-20 18:41:25 +0000 | [diff] [blame] | 642 | * 'origin/main' |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 643 | * 'cool_branch~2' |
| 644 | """ |
| 645 | try: |
Edward Lemur | 12a537f | 2019-10-03 21:57:15 +0000 | [diff] [blame] | 646 | return [binascii.unhexlify(h) for h in hash_multi(*commitrefs)] |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 647 | except subprocess2.CalledProcessError: |
| 648 | raise BadCommitRefException(commitrefs) |
| 649 | |
| 650 | |
sbc@chromium.org | 384039b | 2014-10-13 21:01:00 +0000 | [diff] [blame] | 651 | RebaseRet = collections.namedtuple('RebaseRet', 'success stdout stderr') |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 652 | |
| 653 | |
Robert Iannucci | d3acb16 | 2021-05-04 21:37:40 +0000 | [diff] [blame] | 654 | def rebase(parent, start, branch, abort=False, allow_gc=False): |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 655 | """Rebases |start|..|branch| onto the branch |parent|. |
| 656 | |
Robert Iannucci | d3acb16 | 2021-05-04 21:37:40 +0000 | [diff] [blame] | 657 | Sets 'gc.auto=0' for the duration of this call to prevent the rebase from |
| 658 | running a potentially slow garbage collection cycle. |
| 659 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 660 | Args: |
| 661 | parent - The new parent ref for the rebased commits. |
| 662 | start - The commit to start from |
| 663 | branch - The branch to rebase |
| 664 | abort - If True, will call git-rebase --abort in the event that the rebase |
| 665 | doesn't complete successfully. |
Robert Iannucci | d3acb16 | 2021-05-04 21:37:40 +0000 | [diff] [blame] | 666 | allow_gc - If True, sets "-c gc.auto=1" on the rebase call, rather than |
| 667 | "-c gc.auto=0". Usually if you're doing a series of rebases, |
| 668 | you'll only want to run a single gc pass at the end of all the |
| 669 | rebase activity. |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 670 | |
| 671 | Returns a namedtuple with fields: |
| 672 | success - a boolean indicating that the rebase command completed |
| 673 | successfully. |
| 674 | message - if the rebase failed, this contains the stdout of the failed |
| 675 | rebase. |
| 676 | """ |
| 677 | try: |
Robert Iannucci | d3acb16 | 2021-05-04 21:37:40 +0000 | [diff] [blame] | 678 | args = [ |
| 679 | '-c', 'gc.auto={}'.format('1' if allow_gc else '0'), |
| 680 | 'rebase', |
| 681 | ] |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 682 | if TEST_MODE: |
Robert Iannucci | d3acb16 | 2021-05-04 21:37:40 +0000 | [diff] [blame] | 683 | args.append('--committer-date-is-author-date') |
| 684 | args += [ |
| 685 | '--onto', parent, start, branch, |
| 686 | ] |
| 687 | run(*args) |
sbc@chromium.org | 384039b | 2014-10-13 21:01:00 +0000 | [diff] [blame] | 688 | return RebaseRet(True, '', '') |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 689 | except subprocess2.CalledProcessError as cpe: |
| 690 | if abort: |
iannucci@chromium.org | dabb78b | 2015-06-11 23:17:28 +0000 | [diff] [blame] | 691 | run_with_retcode('rebase', '--abort') # ignore failure |
Josip Sokcevic | 72f991f | 2020-04-23 18:53:30 +0000 | [diff] [blame] | 692 | return RebaseRet(False, cpe.stdout.decode('utf-8', 'replace'), |
| 693 | cpe.stderr.decode('utf-8', 'replace')) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 694 | |
| 695 | |
| 696 | def remove_merge_base(branch): |
| 697 | del_branch_config(branch, 'base') |
iannucci@chromium.org | 10fbe87 | 2014-05-16 22:31:13 +0000 | [diff] [blame] | 698 | del_branch_config(branch, 'base-upstream') |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 699 | |
| 700 | |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 701 | def repo_root(): |
| 702 | """Returns the absolute path to the repository root.""" |
| 703 | return run('rev-parse', '--show-toplevel') |
| 704 | |
| 705 | |
Jeffrey Yasskin | 6b52dc2 | 2019-12-06 18:32:21 +0000 | [diff] [blame] | 706 | def upstream_default(): |
| 707 | """Returns the default branch name of the origin repository.""" |
| 708 | try: |
Josip Sokcevic | 0642373 | 2021-03-31 19:04:42 +0000 | [diff] [blame] | 709 | ret = run('rev-parse', '--abbrev-ref', 'origin/HEAD') |
| 710 | # Detect if the repository migrated to main branch |
| 711 | if ret == 'origin/master': |
| 712 | try: |
| 713 | ret = run('rev-parse', '--abbrev-ref', 'origin/main') |
| 714 | run('remote', 'set-head', '-a', 'origin') |
| 715 | ret = run('rev-parse', '--abbrev-ref', 'origin/HEAD') |
| 716 | except subprocess2.CalledProcessError: |
| 717 | pass |
| 718 | return ret |
Jeffrey Yasskin | 6b52dc2 | 2019-12-06 18:32:21 +0000 | [diff] [blame] | 719 | except subprocess2.CalledProcessError: |
Josip Sokcevic | 7e133ff | 2021-07-13 17:44:53 +0000 | [diff] [blame] | 720 | return 'origin/main' |
Jeffrey Yasskin | 6b52dc2 | 2019-12-06 18:32:21 +0000 | [diff] [blame] | 721 | |
| 722 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 723 | def root(): |
Jeffrey Yasskin | 6b52dc2 | 2019-12-06 18:32:21 +0000 | [diff] [blame] | 724 | return get_config('depot-tools.upstream', upstream_default()) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 725 | |
| 726 | |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 727 | @contextlib.contextmanager |
| 728 | def less(): # pragma: no cover |
| 729 | """Runs 'less' as context manager yielding its stdin as a PIPE. |
| 730 | |
| 731 | Automatically checks if sys.stdout is a non-TTY stream. If so, it avoids |
| 732 | running less and just yields sys.stdout. |
Edward Lemur | 0d462e9 | 2020-01-08 20:11:31 +0000 | [diff] [blame] | 733 | |
| 734 | The returned PIPE is opened on binary mode. |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 735 | """ |
iannucci@chromium.org | 596cd5c | 2016-04-04 21:34:39 +0000 | [diff] [blame] | 736 | if not setup_color.IS_TTY: |
Edward Lemur | 5e94b80 | 2019-11-26 21:44:08 +0000 | [diff] [blame] | 737 | # On Python 3, sys.stdout doesn't accept bytes, and sys.stdout.buffer must |
| 738 | # be used. |
| 739 | yield getattr(sys.stdout, 'buffer', sys.stdout) |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 740 | return |
| 741 | |
| 742 | # Run with the same options that git uses (see setup_pager in git repo). |
| 743 | # -F: Automatically quit if the output is less than one screen. |
| 744 | # -R: Don't escape ANSI color codes. |
| 745 | # -X: Don't clear the screen before starting. |
| 746 | cmd = ('less', '-FRX') |
| 747 | try: |
| 748 | proc = subprocess2.Popen(cmd, stdin=subprocess2.PIPE) |
| 749 | yield proc.stdin |
| 750 | finally: |
Edward Lemur | b800fde | 2020-01-10 23:04:44 +0000 | [diff] [blame] | 751 | try: |
| 752 | proc.stdin.close() |
| 753 | except BrokenPipeError: |
| 754 | # BrokenPipeError is raised if proc has already completed, |
| 755 | pass |
mgiuca@chromium.org | 8193756 | 2016-02-03 08:00:53 +0000 | [diff] [blame] | 756 | proc.wait() |
| 757 | |
| 758 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 759 | def run(*cmd, **kwargs): |
| 760 | """The same as run_with_stderr, except it only returns stdout.""" |
| 761 | return run_with_stderr(*cmd, **kwargs)[0] |
| 762 | |
| 763 | |
agable@chromium.org | d629fb4 | 2014-10-01 09:40:10 +0000 | [diff] [blame] | 764 | def run_with_retcode(*cmd, **kwargs): |
| 765 | """Run a command but only return the status code.""" |
| 766 | try: |
| 767 | run(*cmd, **kwargs) |
| 768 | return 0 |
| 769 | except subprocess2.CalledProcessError as cpe: |
| 770 | return cpe.returncode |
| 771 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 772 | def run_stream(*cmd, **kwargs): |
| 773 | """Runs a git command. Returns stdout as a PIPE (file-like object). |
| 774 | |
| 775 | stderr is dropped to avoid races if the process outputs to both stdout and |
| 776 | stderr. |
| 777 | """ |
Edward Lesmes | cf06cad | 2020-12-14 22:03:23 +0000 | [diff] [blame] | 778 | kwargs.setdefault('stderr', subprocess2.DEVNULL) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 779 | kwargs.setdefault('stdout', subprocess2.PIPE) |
iannucci@chromium.org | 0d9e59c | 2016-01-09 08:08:41 +0000 | [diff] [blame] | 780 | kwargs.setdefault('shell', False) |
iannucci@chromium.org | 2198002 | 2014-04-11 04:51:49 +0000 | [diff] [blame] | 781 | cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 782 | proc = subprocess2.Popen(cmd, **kwargs) |
| 783 | return proc.stdout |
| 784 | |
| 785 | |
tandrii@chromium.org | 6c14310 | 2015-06-11 19:21:02 +0000 | [diff] [blame] | 786 | @contextlib.contextmanager |
| 787 | def run_stream_with_retcode(*cmd, **kwargs): |
| 788 | """Runs a git command as context manager yielding stdout as a PIPE. |
| 789 | |
| 790 | stderr is dropped to avoid races if the process outputs to both stdout and |
| 791 | stderr. |
| 792 | |
| 793 | Raises subprocess2.CalledProcessError on nonzero return code. |
| 794 | """ |
Edward Lesmes | cf06cad | 2020-12-14 22:03:23 +0000 | [diff] [blame] | 795 | kwargs.setdefault('stderr', subprocess2.DEVNULL) |
tandrii@chromium.org | 6c14310 | 2015-06-11 19:21:02 +0000 | [diff] [blame] | 796 | kwargs.setdefault('stdout', subprocess2.PIPE) |
iannucci@chromium.org | 0d9e59c | 2016-01-09 08:08:41 +0000 | [diff] [blame] | 797 | kwargs.setdefault('shell', False) |
tandrii@chromium.org | 6c14310 | 2015-06-11 19:21:02 +0000 | [diff] [blame] | 798 | cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd |
| 799 | try: |
| 800 | proc = subprocess2.Popen(cmd, **kwargs) |
| 801 | yield proc.stdout |
| 802 | finally: |
| 803 | retcode = proc.wait() |
| 804 | if retcode != 0: |
| 805 | raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(), |
Josip Sokcevic | 72f991f | 2020-04-23 18:53:30 +0000 | [diff] [blame] | 806 | b'', b'') |
tandrii@chromium.org | 6c14310 | 2015-06-11 19:21:02 +0000 | [diff] [blame] | 807 | |
| 808 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 809 | def run_with_stderr(*cmd, **kwargs): |
| 810 | """Runs a git command. |
| 811 | |
| 812 | Returns (stdout, stderr) as a pair of strings. |
| 813 | |
| 814 | kwargs |
| 815 | autostrip (bool) - Strip the output. Defaults to True. |
| 816 | indata (str) - Specifies stdin data for the process. |
| 817 | """ |
| 818 | kwargs.setdefault('stdin', subprocess2.PIPE) |
| 819 | kwargs.setdefault('stdout', subprocess2.PIPE) |
| 820 | kwargs.setdefault('stderr', subprocess2.PIPE) |
iannucci@chromium.org | 0d9e59c | 2016-01-09 08:08:41 +0000 | [diff] [blame] | 821 | kwargs.setdefault('shell', False) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 822 | autostrip = kwargs.pop('autostrip', True) |
| 823 | indata = kwargs.pop('indata', None) |
Edward Lemur | 12a537f | 2019-10-03 21:57:15 +0000 | [diff] [blame] | 824 | decode = kwargs.pop('decode', True) |
Orr Bernstein | b7e16d2 | 2023-07-14 11:00:55 +0000 | [diff] [blame] | 825 | accepted_retcodes = kwargs.pop('accepted_retcodes', [0]) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 826 | |
iannucci@chromium.org | 2198002 | 2014-04-11 04:51:49 +0000 | [diff] [blame] | 827 | cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 828 | proc = subprocess2.Popen(cmd, **kwargs) |
| 829 | ret, err = proc.communicate(indata) |
| 830 | retcode = proc.wait() |
Orr Bernstein | b7e16d2 | 2023-07-14 11:00:55 +0000 | [diff] [blame] | 831 | if retcode not in accepted_retcodes: |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 832 | raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(), ret, err) |
| 833 | |
| 834 | if autostrip: |
Edward Lemur | 12a537f | 2019-10-03 21:57:15 +0000 | [diff] [blame] | 835 | ret = (ret or b'').strip() |
| 836 | err = (err or b'').strip() |
| 837 | |
| 838 | if decode: |
| 839 | ret = ret.decode('utf-8', 'replace') |
| 840 | err = err.decode('utf-8', 'replace') |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 841 | |
| 842 | return ret, err |
| 843 | |
| 844 | |
| 845 | def set_branch_config(branch, option, value, scope='local'): |
| 846 | set_config('branch.%s.%s' % (branch, option), value, scope=scope) |
| 847 | |
| 848 | |
| 849 | def set_config(option, value, scope='local'): |
| 850 | run('config', '--' + scope, option, value) |
| 851 | |
agable@chromium.org | d629fb4 | 2014-10-01 09:40:10 +0000 | [diff] [blame] | 852 | |
sbc@chromium.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 853 | def get_dirty_files(): |
| 854 | # Make sure index is up-to-date before running diff-index. |
| 855 | run_with_retcode('update-index', '--refresh', '-q') |
Eli Ribble | 54434e7 | 2019-05-24 00:41:15 +0000 | [diff] [blame] | 856 | return run('diff-index', '--ignore-submodules', '--name-status', 'HEAD') |
sbc@chromium.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 857 | |
| 858 | |
| 859 | def is_dirty_git_tree(cmd): |
iannucci | e38699b | 2016-08-15 17:32:31 -0700 | [diff] [blame] | 860 | w = lambda s: sys.stderr.write(s+"\n") |
| 861 | |
sbc@chromium.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 862 | dirty = get_dirty_files() |
| 863 | if dirty: |
Josip Sokcevic | fcf9fc4 | 2022-09-27 21:59:01 +0000 | [diff] [blame] | 864 | w('Cannot %s with a dirty tree. Commit%s or stash your changes first.' % |
| 865 | (cmd, '' if cmd == 'upload' else ', freeze')) |
iannucci | e38699b | 2016-08-15 17:32:31 -0700 | [diff] [blame] | 866 | w('Uncommitted files: (git diff-index --name-status HEAD)') |
| 867 | w(dirty[:4096]) |
sbc@chromium.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 868 | if len(dirty) > 4096: # pragma: no cover |
iannucci | e38699b | 2016-08-15 17:32:31 -0700 | [diff] [blame] | 869 | w('... (run "git diff-index --name-status HEAD" to see full output).') |
sbc@chromium.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 870 | return True |
| 871 | return False |
| 872 | |
| 873 | |
Greg NISBET | 923bcf8 | 2023-08-10 22:50:46 +0000 | [diff] [blame^] | 874 | def status(ignore_submodules=None): |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 875 | """Returns a parsed version of git-status. |
| 876 | |
Greg NISBET | 923bcf8 | 2023-08-10 22:50:46 +0000 | [diff] [blame^] | 877 | Args: |
| 878 | ignore_submodules (str|None): "all", "none", or None. |
| 879 | None is equivalent to "none". |
| 880 | |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 881 | Returns a generator of (current_name, (lstat, rstat, src)) pairs where: |
| 882 | * current_name is the name of the file |
| 883 | * lstat is the left status code letter from git-status |
| 884 | * rstat is the left status code letter from git-status |
| 885 | * src is the current name of the file, or the original name of the file |
| 886 | if lstat == 'R' |
| 887 | """ |
Greg NISBET | 923bcf8 | 2023-08-10 22:50:46 +0000 | [diff] [blame^] | 888 | |
| 889 | ignore_submodules = ignore_submodules or 'none' |
| 890 | assert ignore_submodules in ( |
| 891 | 'all', 'none'), f'ignore_submodules value {ignore_submodules} is invalid' |
| 892 | |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 893 | stat_entry = collections.namedtuple('stat_entry', 'lstat rstat src') |
| 894 | |
| 895 | def tokenizer(stream): |
Raul Tambre | c2f74c1 | 2019-03-19 05:55:53 +0000 | [diff] [blame] | 896 | acc = BytesIO() |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 897 | c = None |
Edward Lemur | 12a537f | 2019-10-03 21:57:15 +0000 | [diff] [blame] | 898 | while c != b'': |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 899 | c = stream.read(1) |
Edward Lemur | 12a537f | 2019-10-03 21:57:15 +0000 | [diff] [blame] | 900 | if c in (None, b'', b'\0'): |
Aravind Vasudevan | c5f0cbb | 2022-01-24 23:56:57 +0000 | [diff] [blame] | 901 | if len(acc.getvalue()) > 0: |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 902 | yield acc.getvalue() |
Raul Tambre | c2f74c1 | 2019-03-19 05:55:53 +0000 | [diff] [blame] | 903 | acc = BytesIO() |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 904 | else: |
| 905 | acc.write(c) |
| 906 | |
| 907 | def parser(tokens): |
| 908 | while True: |
Edward Lemur | 12a537f | 2019-10-03 21:57:15 +0000 | [diff] [blame] | 909 | try: |
| 910 | status_dest = next(tokens).decode('utf-8') |
| 911 | except StopIteration: |
| 912 | return |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 913 | stat, dest = status_dest[:2], status_dest[3:] |
| 914 | lstat, rstat = stat |
| 915 | if lstat == 'R': |
Edward Lemur | 12a537f | 2019-10-03 21:57:15 +0000 | [diff] [blame] | 916 | src = next(tokens).decode('utf-8') |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 917 | else: |
| 918 | src = dest |
| 919 | yield (dest, stat_entry(lstat, rstat, src)) |
| 920 | |
Greg NISBET | 923bcf8 | 2023-08-10 22:50:46 +0000 | [diff] [blame^] | 921 | return parser( |
| 922 | tokenizer( |
| 923 | run_stream('status', |
| 924 | '-z', |
| 925 | f'--ignore-submodules={ignore_submodules}', |
| 926 | bufsize=-1))) |
agable | 02b3c98 | 2016-06-22 07:51:22 -0700 | [diff] [blame] | 927 | |
| 928 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 929 | def squash_current_branch(header=None, merge_base=None): |
Alan Cutter | 0001782 | 2016-12-20 17:39:59 +1100 | [diff] [blame] | 930 | header = header or 'git squash commit for %s.' % current_branch() |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 931 | merge_base = merge_base or get_or_create_merge_base(current_branch()) |
| 932 | log_msg = header + '\n' |
| 933 | if log_msg: |
| 934 | log_msg += '\n' |
| 935 | log_msg += run('log', '--reverse', '--format=%H%n%B', '%s..HEAD' % merge_base) |
| 936 | run('reset', '--soft', merge_base) |
sbc@chromium.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 937 | |
| 938 | if not get_dirty_files(): |
| 939 | # Sometimes the squash can result in the same tree, meaning that there is |
| 940 | # nothing to commit at this point. |
Raul Tambre | c2f74c1 | 2019-03-19 05:55:53 +0000 | [diff] [blame] | 941 | print('Nothing to commit; squashed branch is empty') |
sbc@chromium.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 942 | return False |
Edward Lemur | 71681bf | 2019-10-09 23:46:20 +0000 | [diff] [blame] | 943 | run('commit', '--no-verify', '-a', '-F', '-', indata=log_msg.encode('utf-8')) |
sbc@chromium.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 944 | return True |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 945 | |
| 946 | |
iannucci@chromium.org | 8bc9b5c | 2014-03-12 01:36:18 +0000 | [diff] [blame] | 947 | def tags(*args): |
| 948 | return run('tag', *args).splitlines() |
| 949 | |
| 950 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 951 | def thaw(): |
| 952 | took_action = False |
Bruce Dawson | 4082f88 | 2023-05-15 17:14:17 +0000 | [diff] [blame] | 953 | with run_stream('rev-list', 'HEAD') as stream: |
| 954 | for sha in stream: |
| 955 | sha = sha.strip().decode('utf-8') |
| 956 | msg = run('show', '--format=%f%b', '-s', 'HEAD') |
| 957 | match = FREEZE_MATCHER.match(msg) |
| 958 | if not match: |
| 959 | if not took_action: |
| 960 | return 'Nothing to thaw.' |
| 961 | break |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 962 | |
Bruce Dawson | 4082f88 | 2023-05-15 17:14:17 +0000 | [diff] [blame] | 963 | run('reset', '--' + FREEZE_SECTIONS[match.group(1)], sha) |
| 964 | took_action = True |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 965 | |
| 966 | |
| 967 | def topo_iter(branch_tree, top_down=True): |
| 968 | """Generates (branch, parent) in topographical order for a branch tree. |
| 969 | |
| 970 | Given a tree: |
| 971 | |
| 972 | A1 |
| 973 | B1 B2 |
| 974 | C1 C2 C3 |
| 975 | D1 |
| 976 | |
| 977 | branch_tree would look like: { |
| 978 | 'D1': 'C3', |
| 979 | 'C3': 'B2', |
| 980 | 'B2': 'A1', |
| 981 | 'C1': 'B1', |
| 982 | 'C2': 'B1', |
| 983 | 'B1': 'A1', |
| 984 | } |
| 985 | |
| 986 | It is OK to have multiple 'root' nodes in your graph. |
| 987 | |
| 988 | if top_down is True, items are yielded from A->D. Otherwise they're yielded |
| 989 | from D->A. Within a layer the branches will be yielded in sorted order. |
| 990 | """ |
| 991 | branch_tree = branch_tree.copy() |
| 992 | |
| 993 | # TODO(iannucci): There is probably a more efficient way to do these. |
| 994 | if top_down: |
| 995 | while branch_tree: |
Edward Lemur | 12a537f | 2019-10-03 21:57:15 +0000 | [diff] [blame] | 996 | this_pass = [(b, p) for b, p in branch_tree.items() |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 997 | if p not in branch_tree] |
| 998 | assert this_pass, "Branch tree has cycles: %r" % branch_tree |
| 999 | for branch, parent in sorted(this_pass): |
| 1000 | yield branch, parent |
| 1001 | del branch_tree[branch] |
| 1002 | else: |
| 1003 | parent_to_branches = collections.defaultdict(set) |
Edward Lemur | 12a537f | 2019-10-03 21:57:15 +0000 | [diff] [blame] | 1004 | for branch, parent in branch_tree.items(): |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 1005 | parent_to_branches[parent].add(branch) |
| 1006 | |
| 1007 | while branch_tree: |
Edward Lemur | 12a537f | 2019-10-03 21:57:15 +0000 | [diff] [blame] | 1008 | this_pass = [(b, p) for b, p in branch_tree.items() |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 1009 | if not parent_to_branches[b]] |
| 1010 | assert this_pass, "Branch tree has cycles: %r" % branch_tree |
| 1011 | for branch, parent in sorted(this_pass): |
| 1012 | yield branch, parent |
| 1013 | parent_to_branches[parent].discard(branch) |
| 1014 | del branch_tree[branch] |
| 1015 | |
| 1016 | |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 1017 | def tree(treeref, recurse=False): |
| 1018 | """Returns a dict representation of a git tree object. |
| 1019 | |
| 1020 | Args: |
| 1021 | 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] | 1022 | 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] | 1023 | take the form of 'some/path/to/file'. |
| 1024 | |
| 1025 | Return format: |
| 1026 | { 'file_name': (mode, type, ref) } |
| 1027 | |
| 1028 | mode is an integer where: |
| 1029 | * 0040000 - Directory |
| 1030 | * 0100644 - Regular non-executable file |
| 1031 | * 0100664 - Regular non-executable group-writeable file |
| 1032 | * 0100755 - Regular executable file |
| 1033 | * 0120000 - Symbolic link |
| 1034 | * 0160000 - Gitlink |
| 1035 | |
| 1036 | type is a string where it's one of 'blob', 'commit', 'tree', 'tag'. |
| 1037 | |
| 1038 | ref is the hex encoded hash of the entry. |
| 1039 | """ |
| 1040 | ret = {} |
| 1041 | opts = ['ls-tree', '--full-tree'] |
| 1042 | if recurse: |
| 1043 | opts.append('-r') |
| 1044 | opts.append(treeref) |
| 1045 | try: |
| 1046 | for line in run(*opts).splitlines(): |
| 1047 | mode, typ, ref, name = line.split(None, 3) |
| 1048 | ret[name] = (mode, typ, ref) |
| 1049 | except subprocess2.CalledProcessError: |
| 1050 | return None |
| 1051 | return ret |
| 1052 | |
| 1053 | |
Mun Yong Jang | 781e71e | 2017-10-25 15:46:20 -0700 | [diff] [blame] | 1054 | def get_remote_url(remote='origin'): |
| 1055 | try: |
| 1056 | return run('config', 'remote.%s.url' % remote) |
| 1057 | except subprocess2.CalledProcessError: |
| 1058 | return None |
| 1059 | |
| 1060 | |
iannucci@chromium.org | 8bc9b5c | 2014-03-12 01:36:18 +0000 | [diff] [blame] | 1061 | def upstream(branch): |
| 1062 | try: |
| 1063 | return run('rev-parse', '--abbrev-ref', '--symbolic-full-name', |
| 1064 | branch+'@{upstream}') |
| 1065 | except subprocess2.CalledProcessError: |
| 1066 | return None |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 1067 | |
agable@chromium.org | d629fb4 | 2014-10-01 09:40:10 +0000 | [diff] [blame] | 1068 | |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 1069 | def get_git_version(): |
| 1070 | """Returns a tuple that contains the numeric components of the current git |
| 1071 | version.""" |
| 1072 | version_string = run('--version') |
| 1073 | version_match = re.search(r'(\d+.)+(\d+)', version_string) |
| 1074 | version = version_match.group() if version_match else '' |
| 1075 | |
| 1076 | return tuple(int(x) for x in version.split('.')) |
| 1077 | |
| 1078 | |
calamity@chromium.org | 745ffa6 | 2014-09-08 01:03:19 +0000 | [diff] [blame] | 1079 | def get_branches_info(include_tracking_status): |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 1080 | format_string = ( |
| 1081 | '--format=%(refname:short):%(objectname:short):%(upstream:short):') |
| 1082 | |
| 1083 | # This is not covered by the depot_tools CQ which only has git version 1.8. |
calamity@chromium.org | 745ffa6 | 2014-09-08 01:03:19 +0000 | [diff] [blame] | 1084 | if (include_tracking_status and |
| 1085 | get_git_version() >= MIN_UPSTREAM_TRACK_GIT_VERSION): # pragma: no cover |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 1086 | format_string += '%(upstream:track)' |
| 1087 | |
| 1088 | info_map = {} |
| 1089 | data = run('for-each-ref', format_string, 'refs/heads') |
calamity@chromium.org | 745ffa6 | 2014-09-08 01:03:19 +0000 | [diff] [blame] | 1090 | BranchesInfo = collections.namedtuple( |
Gavin Mak | 8d7201b | 2020-09-17 19:21:38 +0000 | [diff] [blame] | 1091 | 'BranchesInfo', 'hash upstream commits behind') |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 1092 | for line in data.splitlines(): |
| 1093 | (branch, branch_hash, upstream_branch, tracking_status) = line.split(':') |
| 1094 | |
Gavin Mak | 8d7201b | 2020-09-17 19:21:38 +0000 | [diff] [blame] | 1095 | commits = None |
Antonio Sartori | e0dff20 | 2021-02-18 06:33:50 +0000 | [diff] [blame] | 1096 | if include_tracking_status: |
| 1097 | base = get_or_create_merge_base(branch) |
| 1098 | if base: |
| 1099 | commits_list = run('rev-list', '--count', branch, '^%s' % base, '--') |
| 1100 | commits = int(commits_list) or None |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 1101 | |
| 1102 | behind_match = re.search(r'behind (\d+)', tracking_status) |
| 1103 | behind = int(behind_match.group(1)) if behind_match else None |
| 1104 | |
calamity@chromium.org | 745ffa6 | 2014-09-08 01:03:19 +0000 | [diff] [blame] | 1105 | info_map[branch] = BranchesInfo( |
Robert Iannucci | d3acb16 | 2021-05-04 21:37:40 +0000 | [diff] [blame] | 1106 | hash=branch_hash, upstream=upstream_branch, commits=commits, |
Gavin Mak | 8d7201b | 2020-09-17 19:21:38 +0000 | [diff] [blame] | 1107 | behind=behind) |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 1108 | |
| 1109 | # Set None for upstreams which are not branches (e.g empty upstream, remotes |
| 1110 | # and deleted upstream branches). |
| 1111 | missing_upstreams = {} |
| 1112 | for info in info_map.values(): |
| 1113 | if info.upstream not in info_map and info.upstream not in missing_upstreams: |
| 1114 | missing_upstreams[info.upstream] = None |
| 1115 | |
Edward Lemur | 12a537f | 2019-10-03 21:57:15 +0000 | [diff] [blame] | 1116 | result = info_map.copy() |
| 1117 | result.update(missing_upstreams) |
| 1118 | return result |
sammc@chromium.org | 900a33f | 2015-09-29 06:57:09 +0000 | [diff] [blame] | 1119 | |
| 1120 | |
| 1121 | def make_workdir_common(repository, new_workdir, files_to_symlink, |
scottmg@chromium.org | d4218d4 | 2015-10-07 23:49:20 +0000 | [diff] [blame] | 1122 | files_to_copy, symlink=None): |
| 1123 | if not symlink: |
| 1124 | symlink = os.symlink |
sammc@chromium.org | 900a33f | 2015-09-29 06:57:09 +0000 | [diff] [blame] | 1125 | os.makedirs(new_workdir) |
| 1126 | for entry in files_to_symlink: |
scottmg@chromium.org | d4218d4 | 2015-10-07 23:49:20 +0000 | [diff] [blame] | 1127 | clone_file(repository, new_workdir, entry, symlink) |
sammc@chromium.org | 900a33f | 2015-09-29 06:57:09 +0000 | [diff] [blame] | 1128 | for entry in files_to_copy: |
| 1129 | clone_file(repository, new_workdir, entry, shutil.copy) |
| 1130 | |
| 1131 | |
| 1132 | def make_workdir(repository, new_workdir): |
| 1133 | GIT_DIRECTORY_WHITELIST = [ |
| 1134 | 'config', |
| 1135 | 'info', |
| 1136 | 'hooks', |
| 1137 | 'logs/refs', |
| 1138 | 'objects', |
| 1139 | 'packed-refs', |
| 1140 | 'refs', |
| 1141 | 'remotes', |
| 1142 | 'rr-cache', |
Richard He | 42033b2 | 2020-05-22 03:03:45 +0000 | [diff] [blame] | 1143 | 'shallow', |
sammc@chromium.org | 900a33f | 2015-09-29 06:57:09 +0000 | [diff] [blame] | 1144 | ] |
| 1145 | make_workdir_common(repository, new_workdir, GIT_DIRECTORY_WHITELIST, |
| 1146 | ['HEAD']) |
| 1147 | |
| 1148 | |
| 1149 | def clone_file(repository, new_workdir, link, operation): |
| 1150 | if not os.path.exists(os.path.join(repository, link)): |
| 1151 | return |
| 1152 | link_dir = os.path.dirname(os.path.join(new_workdir, link)) |
| 1153 | if not os.path.exists(link_dir): |
| 1154 | os.makedirs(link_dir) |
Henrique Ferreiro | fd4ad24 | 2018-01-10 12:19:18 +0100 | [diff] [blame] | 1155 | src = os.path.join(repository, link) |
| 1156 | if os.path.islink(src): |
Henrique Ferreiro | aea45d2 | 2018-02-19 09:48:36 +0100 | [diff] [blame] | 1157 | src = os.path.realpath(src) |
Henrique Ferreiro | fd4ad24 | 2018-01-10 12:19:18 +0100 | [diff] [blame] | 1158 | operation(src, os.path.join(new_workdir, link)) |