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