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