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 | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 25 | import signal |
| 26 | import sys |
| 27 | import tempfile |
iannucci@chromium.org | 3f23cdf | 2014-04-15 20:02:44 +0000 | [diff] [blame] | 28 | import textwrap |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 29 | import threading |
| 30 | |
| 31 | import subprocess2 |
| 32 | |
techtonik@gmail.com | a5a945a | 2014-08-15 20:01:53 +0000 | [diff] [blame] | 33 | ROOT = os.path.abspath(os.path.dirname(__file__)) |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 34 | |
techtonik@gmail.com | a5a945a | 2014-08-15 20:01:53 +0000 | [diff] [blame] | 35 | GIT_EXE = ROOT+'\\git.bat' if sys.platform.startswith('win') else 'git' |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 36 | TEST_MODE = False |
| 37 | |
| 38 | FREEZE = 'FREEZE' |
| 39 | FREEZE_SECTIONS = { |
| 40 | 'indexed': 'soft', |
| 41 | 'unindexed': 'mixed' |
| 42 | } |
| 43 | FREEZE_MATCHER = re.compile(r'%s.(%s)' % (FREEZE, '|'.join(FREEZE_SECTIONS))) |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 44 | |
| 45 | |
dnj@chromium.org | de219ec | 2014-07-28 17:39:08 +0000 | [diff] [blame] | 46 | # Retry a git operation if git returns a error response with any of these |
| 47 | # messages. It's all observed 'bad' GoB responses so far. |
| 48 | # |
| 49 | # This list is inspired/derived from the one in ChromiumOS's Chromite: |
| 50 | # <CHROMITE>/lib/git.py::GIT_TRANSIENT_ERRORS |
| 51 | # |
| 52 | # It was last imported from '7add3ac29564d98ac35ce426bc295e743e7c0c02'. |
| 53 | GIT_TRANSIENT_ERRORS = ( |
| 54 | # crbug.com/285832 |
iannucci@chromium.org | 6e95d40 | 2014-08-29 22:10:55 +0000 | [diff] [blame] | 55 | r'!.*\[remote rejected\].*\(error in hook\)', |
dnj@chromium.org | de219ec | 2014-07-28 17:39:08 +0000 | [diff] [blame] | 56 | |
| 57 | # crbug.com/289932 |
iannucci@chromium.org | 6e95d40 | 2014-08-29 22:10:55 +0000 | [diff] [blame] | 58 | r'!.*\[remote rejected\].*\(failed to lock\)', |
dnj@chromium.org | de219ec | 2014-07-28 17:39:08 +0000 | [diff] [blame] | 59 | |
| 60 | # crbug.com/307156 |
iannucci@chromium.org | 6e95d40 | 2014-08-29 22:10:55 +0000 | [diff] [blame] | 61 | r'!.*\[remote rejected\].*\(error in Gerrit backend\)', |
dnj@chromium.org | de219ec | 2014-07-28 17:39:08 +0000 | [diff] [blame] | 62 | |
| 63 | # crbug.com/285832 |
| 64 | r'remote error: Internal Server Error', |
| 65 | |
| 66 | # crbug.com/294449 |
| 67 | r'fatal: Couldn\'t find remote ref ', |
| 68 | |
| 69 | # crbug.com/220543 |
| 70 | r'git fetch_pack: expected ACK/NAK, got', |
| 71 | |
| 72 | # crbug.com/189455 |
| 73 | r'protocol error: bad pack header', |
| 74 | |
| 75 | # crbug.com/202807 |
| 76 | r'The remote end hung up unexpectedly', |
| 77 | |
| 78 | # crbug.com/298189 |
| 79 | r'TLS packet with unexpected length was received', |
| 80 | |
| 81 | # crbug.com/187444 |
| 82 | r'RPC failed; result=\d+, HTTP code = \d+', |
| 83 | |
| 84 | # crbug.com/315421 |
| 85 | r'The requested URL returned error: 500 while accessing', |
| 86 | |
| 87 | # crbug.com/388876 |
| 88 | r'Connection timed out', |
| 89 | ) |
| 90 | |
| 91 | GIT_TRANSIENT_ERRORS_RE = re.compile('|'.join(GIT_TRANSIENT_ERRORS), |
| 92 | re.IGNORECASE) |
| 93 | |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 94 | # First version where the for-each-ref command's format string supported the |
| 95 | # upstream:track token. |
| 96 | MIN_UPSTREAM_TRACK_GIT_VERSION = (1, 9) |
dnj@chromium.org | de219ec | 2014-07-28 17:39:08 +0000 | [diff] [blame] | 97 | |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 98 | class BadCommitRefException(Exception): |
| 99 | def __init__(self, refs): |
| 100 | msg = ('one of %s does not seem to be a valid commitref.' % |
| 101 | str(refs)) |
| 102 | super(BadCommitRefException, self).__init__(msg) |
| 103 | |
| 104 | |
| 105 | def memoize_one(**kwargs): |
| 106 | """Memoizes a single-argument pure function. |
| 107 | |
| 108 | Values of None are not cached. |
| 109 | |
| 110 | Kwargs: |
| 111 | threadsafe (bool) - REQUIRED. Specifies whether to use locking around |
| 112 | cache manipulation functions. This is a kwarg so that users of memoize_one |
| 113 | are forced to explicitly and verbosely pick True or False. |
| 114 | |
| 115 | Adds three methods to the decorated function: |
| 116 | * get(key, default=None) - Gets the value for this key from the cache. |
| 117 | * set(key, value) - Sets the value for this key from the cache. |
| 118 | * clear() - Drops the entire contents of the cache. Useful for unittests. |
| 119 | * update(other) - Updates the contents of the cache from another dict. |
| 120 | """ |
| 121 | assert 'threadsafe' in kwargs, 'Must specify threadsafe={True,False}' |
| 122 | threadsafe = kwargs['threadsafe'] |
| 123 | |
| 124 | if threadsafe: |
| 125 | def withlock(lock, f): |
| 126 | def inner(*args, **kwargs): |
| 127 | with lock: |
| 128 | return f(*args, **kwargs) |
| 129 | return inner |
| 130 | else: |
| 131 | def withlock(_lock, f): |
| 132 | return f |
| 133 | |
| 134 | def decorator(f): |
| 135 | # Instantiate the lock in decorator, in case users of memoize_one do: |
| 136 | # |
| 137 | # memoizer = memoize_one(threadsafe=True) |
| 138 | # |
| 139 | # @memoizer |
| 140 | # def fn1(val): ... |
| 141 | # |
| 142 | # @memoizer |
| 143 | # def fn2(val): ... |
| 144 | |
| 145 | lock = threading.Lock() if threadsafe else None |
| 146 | cache = {} |
| 147 | _get = withlock(lock, cache.get) |
| 148 | _set = withlock(lock, cache.__setitem__) |
| 149 | |
| 150 | @functools.wraps(f) |
| 151 | def inner(arg): |
| 152 | ret = _get(arg) |
| 153 | if ret is None: |
| 154 | ret = f(arg) |
| 155 | if ret is not None: |
| 156 | _set(arg, ret) |
| 157 | return ret |
| 158 | inner.get = _get |
| 159 | inner.set = _set |
| 160 | inner.clear = withlock(lock, cache.clear) |
| 161 | inner.update = withlock(lock, cache.update) |
| 162 | return inner |
| 163 | return decorator |
| 164 | |
| 165 | |
| 166 | def _ScopedPool_initer(orig, orig_args): # pragma: no cover |
| 167 | """Initializer method for ScopedPool's subprocesses. |
| 168 | |
| 169 | This helps ScopedPool handle Ctrl-C's correctly. |
| 170 | """ |
| 171 | signal.signal(signal.SIGINT, signal.SIG_IGN) |
| 172 | if orig: |
| 173 | orig(*orig_args) |
| 174 | |
| 175 | |
| 176 | @contextlib.contextmanager |
| 177 | def ScopedPool(*args, **kwargs): |
| 178 | """Context Manager which returns a multiprocessing.pool instance which |
| 179 | correctly deals with thrown exceptions. |
| 180 | |
| 181 | *args - Arguments to multiprocessing.pool |
| 182 | |
| 183 | Kwargs: |
| 184 | kind ('threads', 'procs') - The type of underlying coprocess to use. |
| 185 | **etc - Arguments to multiprocessing.pool |
| 186 | """ |
| 187 | if kwargs.pop('kind', None) == 'threads': |
| 188 | pool = multiprocessing.pool.ThreadPool(*args, **kwargs) |
| 189 | else: |
| 190 | orig, orig_args = kwargs.get('initializer'), kwargs.get('initargs', ()) |
| 191 | kwargs['initializer'] = _ScopedPool_initer |
| 192 | kwargs['initargs'] = orig, orig_args |
| 193 | pool = multiprocessing.pool.Pool(*args, **kwargs) |
| 194 | |
| 195 | try: |
| 196 | yield pool |
| 197 | pool.close() |
| 198 | except: |
| 199 | pool.terminate() |
| 200 | raise |
| 201 | finally: |
| 202 | pool.join() |
| 203 | |
| 204 | |
| 205 | class ProgressPrinter(object): |
| 206 | """Threaded single-stat status message printer.""" |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 207 | 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] | 208 | """Create a ProgressPrinter. |
| 209 | |
| 210 | Use it as a context manager which produces a simple 'increment' method: |
| 211 | |
| 212 | with ProgressPrinter('(%%(count)d/%d)' % 1000) as inc: |
| 213 | for i in xrange(1000): |
| 214 | # do stuff |
| 215 | if i % 10 == 0: |
| 216 | inc(10) |
| 217 | |
| 218 | Args: |
| 219 | fmt - String format with a single '%(count)d' where the counter value |
| 220 | should go. |
| 221 | enabled (bool) - If this is None, will default to True if |
| 222 | logging.getLogger() is set to INFO or more verbose. |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 223 | fout (file-like) - The stream to print status messages to. |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 224 | period (float) - The time in seconds for the printer thread to wait |
| 225 | between printing. |
| 226 | """ |
| 227 | self.fmt = fmt |
| 228 | if enabled is None: # pragma: no cover |
| 229 | self.enabled = logging.getLogger().isEnabledFor(logging.INFO) |
| 230 | else: |
| 231 | self.enabled = enabled |
| 232 | |
| 233 | self._count = 0 |
| 234 | self._dead = False |
| 235 | self._dead_cond = threading.Condition() |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 236 | self._stream = fout |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 237 | self._thread = threading.Thread(target=self._run) |
| 238 | self._period = period |
| 239 | |
| 240 | def _emit(self, s): |
| 241 | if self.enabled: |
| 242 | self._stream.write('\r' + s) |
| 243 | self._stream.flush() |
| 244 | |
| 245 | def _run(self): |
| 246 | with self._dead_cond: |
| 247 | while not self._dead: |
| 248 | self._emit(self.fmt % {'count': self._count}) |
| 249 | self._dead_cond.wait(self._period) |
| 250 | self._emit((self.fmt + '\n') % {'count': self._count}) |
| 251 | |
| 252 | def inc(self, amount=1): |
| 253 | self._count += amount |
| 254 | |
| 255 | def __enter__(self): |
| 256 | self._thread.start() |
| 257 | return self.inc |
| 258 | |
| 259 | def __exit__(self, _exc_type, _exc_value, _traceback): |
| 260 | self._dead = True |
| 261 | with self._dead_cond: |
| 262 | self._dead_cond.notifyAll() |
| 263 | self._thread.join() |
| 264 | del self._thread |
| 265 | |
| 266 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 267 | def once(function): |
| 268 | """@Decorates |function| so that it only performs its action once, no matter |
| 269 | how many times the decorated |function| is called.""" |
| 270 | def _inner_gen(): |
| 271 | yield function() |
| 272 | while True: |
| 273 | yield |
| 274 | return _inner_gen().next |
| 275 | |
| 276 | |
| 277 | ## Git functions |
| 278 | |
| 279 | |
| 280 | def branch_config(branch, option, default=None): |
| 281 | return config('branch.%s.%s' % (branch, option), default=default) |
| 282 | |
| 283 | |
| 284 | def branch_config_map(option): |
| 285 | """Return {branch: <|option| value>} for all branches.""" |
| 286 | try: |
| 287 | reg = re.compile(r'^branch\.(.*)\.%s$' % option) |
| 288 | lines = run('config', '--get-regexp', reg.pattern).splitlines() |
| 289 | return {reg.match(k).group(1): v for k, v in (l.split() for l in lines)} |
| 290 | except subprocess2.CalledProcessError: |
| 291 | return {} |
| 292 | |
| 293 | |
iannucci@chromium.org | 8bc9b5c | 2014-03-12 01:36:18 +0000 | [diff] [blame] | 294 | def branches(*args): |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 295 | NO_BRANCH = ('* (no branch', '* (detached from ') |
iannucci@chromium.org | 3f23cdf | 2014-04-15 20:02:44 +0000 | [diff] [blame] | 296 | |
| 297 | key = 'depot-tools.branch-limit' |
| 298 | limit = 20 |
| 299 | try: |
| 300 | limit = int(config(key, limit)) |
| 301 | except ValueError: |
| 302 | pass |
| 303 | |
| 304 | raw_branches = run('branch', *args).splitlines() |
| 305 | |
| 306 | num = len(raw_branches) |
| 307 | if num > limit: |
| 308 | print >> sys.stderr, textwrap.dedent("""\ |
| 309 | Your git repo has too many branches (%d/%d) for this tool to work well. |
| 310 | |
| 311 | You may adjust this limit by running: |
| 312 | git config %s <new_limit> |
| 313 | """ % (num, limit, key)) |
| 314 | sys.exit(1) |
| 315 | |
| 316 | for line in raw_branches: |
iannucci@chromium.org | 8bc9b5c | 2014-03-12 01:36:18 +0000 | [diff] [blame] | 317 | if line.startswith(NO_BRANCH): |
| 318 | continue |
| 319 | yield line.split()[-1] |
| 320 | |
| 321 | |
iannucci@chromium.org | edeaa81 | 2014-03-26 21:27:47 +0000 | [diff] [blame] | 322 | def run_with_retcode(*cmd, **kwargs): |
| 323 | """Run a command but only return the status code.""" |
| 324 | try: |
| 325 | run(*cmd, **kwargs) |
| 326 | return 0 |
| 327 | except subprocess2.CalledProcessError as cpe: |
| 328 | return cpe.returncode |
| 329 | |
| 330 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 331 | def config(option, default=None): |
| 332 | try: |
| 333 | return run('config', '--get', option) or default |
| 334 | except subprocess2.CalledProcessError: |
| 335 | return default |
| 336 | |
| 337 | |
iannucci@chromium.org | 8bc9b5c | 2014-03-12 01:36:18 +0000 | [diff] [blame] | 338 | def config_list(option): |
| 339 | try: |
| 340 | return run('config', '--get-all', option).split() |
| 341 | except subprocess2.CalledProcessError: |
| 342 | return [] |
| 343 | |
| 344 | |
| 345 | def current_branch(): |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 346 | try: |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 347 | return run('rev-parse', '--abbrev-ref', 'HEAD') |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 348 | except subprocess2.CalledProcessError: |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 349 | return None |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 350 | |
| 351 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 352 | def del_branch_config(branch, option, scope='local'): |
| 353 | del_config('branch.%s.%s' % (branch, option), scope=scope) |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 354 | |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 355 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 356 | def del_config(option, scope='local'): |
| 357 | try: |
| 358 | run('config', '--' + scope, '--unset', option) |
| 359 | except subprocess2.CalledProcessError: |
| 360 | pass |
| 361 | |
| 362 | |
| 363 | def freeze(): |
| 364 | took_action = False |
| 365 | |
| 366 | try: |
| 367 | run('commit', '-m', FREEZE + '.indexed') |
| 368 | took_action = True |
| 369 | except subprocess2.CalledProcessError: |
| 370 | pass |
| 371 | |
| 372 | try: |
| 373 | run('add', '-A') |
| 374 | run('commit', '-m', FREEZE + '.unindexed') |
| 375 | took_action = True |
| 376 | except subprocess2.CalledProcessError: |
| 377 | pass |
| 378 | |
| 379 | if not took_action: |
| 380 | return 'Nothing to freeze.' |
| 381 | |
| 382 | |
| 383 | def get_branch_tree(): |
| 384 | """Get the dictionary of {branch: parent}, compatible with topo_iter. |
| 385 | |
| 386 | Returns a tuple of (skipped, <branch_tree dict>) where skipped is a set of |
| 387 | branches without upstream branches defined. |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 388 | """ |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 389 | skipped = set() |
| 390 | branch_tree = {} |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 391 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 392 | for branch in branches(): |
| 393 | parent = upstream(branch) |
| 394 | if not parent: |
| 395 | skipped.add(branch) |
| 396 | continue |
| 397 | branch_tree[branch] = parent |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 398 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 399 | return skipped, branch_tree |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 400 | |
| 401 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 402 | def get_or_create_merge_base(branch, parent=None): |
| 403 | """Finds the configured merge base for branch. |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 404 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 405 | 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] | 406 | """ |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 407 | base = branch_config(branch, 'base') |
iannucci@chromium.org | 10fbe87 | 2014-05-16 22:31:13 +0000 | [diff] [blame] | 408 | base_upstream = branch_config(branch, 'base-upstream') |
iannucci@chromium.org | edeaa81 | 2014-03-26 21:27:47 +0000 | [diff] [blame] | 409 | parent = parent or upstream(branch) |
iannucci@chromium.org | 10fbe87 | 2014-05-16 22:31:13 +0000 | [diff] [blame] | 410 | if not parent: |
| 411 | return None |
iannucci@chromium.org | edeaa81 | 2014-03-26 21:27:47 +0000 | [diff] [blame] | 412 | actual_merge_base = run('merge-base', parent, branch) |
| 413 | |
iannucci@chromium.org | 10fbe87 | 2014-05-16 22:31:13 +0000 | [diff] [blame] | 414 | if base_upstream != parent: |
| 415 | base = None |
| 416 | base_upstream = None |
| 417 | |
iannucci@chromium.org | edeaa81 | 2014-03-26 21:27:47 +0000 | [diff] [blame] | 418 | def is_ancestor(a, b): |
| 419 | return run_with_retcode('merge-base', '--is-ancestor', a, b) == 0 |
| 420 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 421 | if base: |
iannucci@chromium.org | edeaa81 | 2014-03-26 21:27:47 +0000 | [diff] [blame] | 422 | if not is_ancestor(base, branch): |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 423 | logging.debug('Found WRONG pre-set merge-base for %s: %s', branch, base) |
| 424 | base = None |
iannucci@chromium.org | edeaa81 | 2014-03-26 21:27:47 +0000 | [diff] [blame] | 425 | elif is_ancestor(base, actual_merge_base): |
| 426 | logging.debug('Found OLD pre-set merge-base for %s: %s', branch, base) |
| 427 | base = None |
| 428 | else: |
| 429 | 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] | 430 | |
| 431 | if not base: |
iannucci@chromium.org | edeaa81 | 2014-03-26 21:27:47 +0000 | [diff] [blame] | 432 | base = actual_merge_base |
iannucci@chromium.org | 10fbe87 | 2014-05-16 22:31:13 +0000 | [diff] [blame] | 433 | manual_merge_base(branch, base, parent) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 434 | |
| 435 | return base |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 436 | |
| 437 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 438 | def hash_multi(*reflike): |
| 439 | return run('rev-parse', *reflike).splitlines() |
iannucci@chromium.org | 97345eb | 2014-03-13 07:55:15 +0000 | [diff] [blame] | 440 | |
| 441 | |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 442 | def hash_one(reflike, short=False): |
| 443 | args = ['rev-parse', reflike] |
| 444 | if short: |
| 445 | args.insert(1, '--short') |
| 446 | return run(*args) |
iannucci@chromium.org | 8bc9b5c | 2014-03-12 01:36:18 +0000 | [diff] [blame] | 447 | |
| 448 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 449 | def in_rebase(): |
| 450 | git_dir = run('rev-parse', '--git-dir') |
| 451 | return ( |
| 452 | os.path.exists(os.path.join(git_dir, 'rebase-merge')) or |
| 453 | os.path.exists(os.path.join(git_dir, 'rebase-apply'))) |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 454 | |
| 455 | |
| 456 | def intern_f(f, kind='blob'): |
| 457 | """Interns a file object into the git object store. |
| 458 | |
| 459 | Args: |
| 460 | f (file-like object) - The file-like object to intern |
| 461 | kind (git object type) - One of 'blob', 'commit', 'tree', 'tag'. |
| 462 | |
| 463 | Returns the git hash of the interned object (hex encoded). |
| 464 | """ |
| 465 | ret = run('hash-object', '-t', kind, '-w', '--stdin', stdin=f) |
| 466 | f.close() |
| 467 | return ret |
| 468 | |
| 469 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 470 | def is_dormant(branch): |
| 471 | # TODO(iannucci): Do an oldness check? |
| 472 | return branch_config(branch, 'dormant', 'false') != 'false' |
| 473 | |
| 474 | |
iannucci@chromium.org | 10fbe87 | 2014-05-16 22:31:13 +0000 | [diff] [blame] | 475 | def manual_merge_base(branch, base, parent): |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 476 | set_branch_config(branch, 'base', base) |
iannucci@chromium.org | 10fbe87 | 2014-05-16 22:31:13 +0000 | [diff] [blame] | 477 | set_branch_config(branch, 'base-upstream', parent) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 478 | |
| 479 | |
| 480 | def mktree(treedict): |
| 481 | """Makes a git tree object and returns its hash. |
| 482 | |
| 483 | See |tree()| for the values of mode, type, and ref. |
| 484 | |
| 485 | Args: |
| 486 | treedict - { name: (mode, type, ref) } |
| 487 | """ |
| 488 | with tempfile.TemporaryFile() as f: |
| 489 | for name, (mode, typ, ref) in treedict.iteritems(): |
| 490 | f.write('%s %s %s\t%s\0' % (mode, typ, ref, name)) |
| 491 | f.seek(0) |
| 492 | return run('mktree', '-z', stdin=f) |
| 493 | |
| 494 | |
| 495 | def parse_commitrefs(*commitrefs): |
| 496 | """Returns binary encoded commit hashes for one or more commitrefs. |
| 497 | |
| 498 | A commitref is anything which can resolve to a commit. Popular examples: |
| 499 | * 'HEAD' |
| 500 | * 'origin/master' |
| 501 | * 'cool_branch~2' |
| 502 | """ |
| 503 | try: |
| 504 | return map(binascii.unhexlify, hash_multi(*commitrefs)) |
| 505 | except subprocess2.CalledProcessError: |
| 506 | raise BadCommitRefException(commitrefs) |
| 507 | |
| 508 | |
| 509 | RebaseRet = collections.namedtuple('RebaseRet', 'success message') |
| 510 | |
| 511 | |
| 512 | def rebase(parent, start, branch, abort=False): |
| 513 | """Rebases |start|..|branch| onto the branch |parent|. |
| 514 | |
| 515 | Args: |
| 516 | parent - The new parent ref for the rebased commits. |
| 517 | start - The commit to start from |
| 518 | branch - The branch to rebase |
| 519 | abort - If True, will call git-rebase --abort in the event that the rebase |
| 520 | doesn't complete successfully. |
| 521 | |
| 522 | Returns a namedtuple with fields: |
| 523 | success - a boolean indicating that the rebase command completed |
| 524 | successfully. |
| 525 | message - if the rebase failed, this contains the stdout of the failed |
| 526 | rebase. |
| 527 | """ |
| 528 | try: |
| 529 | args = ['--onto', parent, start, branch] |
| 530 | if TEST_MODE: |
| 531 | args.insert(0, '--committer-date-is-author-date') |
| 532 | run('rebase', *args) |
| 533 | return RebaseRet(True, '') |
| 534 | except subprocess2.CalledProcessError as cpe: |
| 535 | if abort: |
| 536 | run('rebase', '--abort') |
iannucci@chromium.org | 56a624a | 2014-03-26 21:23:09 +0000 | [diff] [blame] | 537 | return RebaseRet(False, cpe.stdout) |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 538 | |
| 539 | |
| 540 | def remove_merge_base(branch): |
| 541 | del_branch_config(branch, 'base') |
iannucci@chromium.org | 10fbe87 | 2014-05-16 22:31:13 +0000 | [diff] [blame] | 542 | del_branch_config(branch, 'base-upstream') |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 543 | |
| 544 | |
| 545 | def root(): |
| 546 | return config('depot-tools.upstream', 'origin/master') |
| 547 | |
| 548 | |
| 549 | def run(*cmd, **kwargs): |
| 550 | """The same as run_with_stderr, except it only returns stdout.""" |
| 551 | return run_with_stderr(*cmd, **kwargs)[0] |
| 552 | |
| 553 | |
| 554 | def run_stream(*cmd, **kwargs): |
| 555 | """Runs a git command. Returns stdout as a PIPE (file-like object). |
| 556 | |
| 557 | stderr is dropped to avoid races if the process outputs to both stdout and |
| 558 | stderr. |
| 559 | """ |
| 560 | kwargs.setdefault('stderr', subprocess2.VOID) |
| 561 | kwargs.setdefault('stdout', subprocess2.PIPE) |
iannucci@chromium.org | 2198002 | 2014-04-11 04:51:49 +0000 | [diff] [blame] | 562 | cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 563 | proc = subprocess2.Popen(cmd, **kwargs) |
| 564 | return proc.stdout |
| 565 | |
| 566 | |
| 567 | def run_with_stderr(*cmd, **kwargs): |
| 568 | """Runs a git command. |
| 569 | |
| 570 | Returns (stdout, stderr) as a pair of strings. |
| 571 | |
| 572 | kwargs |
| 573 | autostrip (bool) - Strip the output. Defaults to True. |
| 574 | indata (str) - Specifies stdin data for the process. |
| 575 | """ |
| 576 | kwargs.setdefault('stdin', subprocess2.PIPE) |
| 577 | kwargs.setdefault('stdout', subprocess2.PIPE) |
| 578 | kwargs.setdefault('stderr', subprocess2.PIPE) |
| 579 | autostrip = kwargs.pop('autostrip', True) |
| 580 | indata = kwargs.pop('indata', None) |
| 581 | |
iannucci@chromium.org | 2198002 | 2014-04-11 04:51:49 +0000 | [diff] [blame] | 582 | cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 583 | proc = subprocess2.Popen(cmd, **kwargs) |
| 584 | ret, err = proc.communicate(indata) |
| 585 | retcode = proc.wait() |
| 586 | if retcode != 0: |
| 587 | raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(), ret, err) |
| 588 | |
| 589 | if autostrip: |
| 590 | ret = (ret or '').strip() |
| 591 | err = (err or '').strip() |
| 592 | |
| 593 | return ret, err |
| 594 | |
| 595 | |
| 596 | def set_branch_config(branch, option, value, scope='local'): |
| 597 | set_config('branch.%s.%s' % (branch, option), value, scope=scope) |
| 598 | |
| 599 | |
| 600 | def set_config(option, value, scope='local'): |
| 601 | run('config', '--' + scope, option, value) |
| 602 | |
| 603 | def squash_current_branch(header=None, merge_base=None): |
| 604 | header = header or 'git squash commit.' |
| 605 | merge_base = merge_base or get_or_create_merge_base(current_branch()) |
| 606 | log_msg = header + '\n' |
| 607 | if log_msg: |
| 608 | log_msg += '\n' |
| 609 | log_msg += run('log', '--reverse', '--format=%H%n%B', '%s..HEAD' % merge_base) |
| 610 | run('reset', '--soft', merge_base) |
| 611 | run('commit', '-a', '-F', '-', indata=log_msg) |
| 612 | |
| 613 | |
iannucci@chromium.org | 8bc9b5c | 2014-03-12 01:36:18 +0000 | [diff] [blame] | 614 | def tags(*args): |
| 615 | return run('tag', *args).splitlines() |
| 616 | |
| 617 | |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 618 | def thaw(): |
| 619 | took_action = False |
| 620 | for sha in (s.strip() for s in run_stream('rev-list', 'HEAD').xreadlines()): |
| 621 | msg = run('show', '--format=%f%b', '-s', 'HEAD') |
| 622 | match = FREEZE_MATCHER.match(msg) |
| 623 | if not match: |
| 624 | if not took_action: |
| 625 | return 'Nothing to thaw.' |
| 626 | break |
| 627 | |
| 628 | run('reset', '--' + FREEZE_SECTIONS[match.group(1)], sha) |
| 629 | took_action = True |
| 630 | |
| 631 | |
| 632 | def topo_iter(branch_tree, top_down=True): |
| 633 | """Generates (branch, parent) in topographical order for a branch tree. |
| 634 | |
| 635 | Given a tree: |
| 636 | |
| 637 | A1 |
| 638 | B1 B2 |
| 639 | C1 C2 C3 |
| 640 | D1 |
| 641 | |
| 642 | branch_tree would look like: { |
| 643 | 'D1': 'C3', |
| 644 | 'C3': 'B2', |
| 645 | 'B2': 'A1', |
| 646 | 'C1': 'B1', |
| 647 | 'C2': 'B1', |
| 648 | 'B1': 'A1', |
| 649 | } |
| 650 | |
| 651 | It is OK to have multiple 'root' nodes in your graph. |
| 652 | |
| 653 | if top_down is True, items are yielded from A->D. Otherwise they're yielded |
| 654 | from D->A. Within a layer the branches will be yielded in sorted order. |
| 655 | """ |
| 656 | branch_tree = branch_tree.copy() |
| 657 | |
| 658 | # TODO(iannucci): There is probably a more efficient way to do these. |
| 659 | if top_down: |
| 660 | while branch_tree: |
| 661 | this_pass = [(b, p) for b, p in branch_tree.iteritems() |
| 662 | if p not in branch_tree] |
| 663 | assert this_pass, "Branch tree has cycles: %r" % branch_tree |
| 664 | for branch, parent in sorted(this_pass): |
| 665 | yield branch, parent |
| 666 | del branch_tree[branch] |
| 667 | else: |
| 668 | parent_to_branches = collections.defaultdict(set) |
| 669 | for branch, parent in branch_tree.iteritems(): |
| 670 | parent_to_branches[parent].add(branch) |
| 671 | |
| 672 | while branch_tree: |
| 673 | this_pass = [(b, p) for b, p in branch_tree.iteritems() |
| 674 | if not parent_to_branches[b]] |
| 675 | assert this_pass, "Branch tree has cycles: %r" % branch_tree |
| 676 | for branch, parent in sorted(this_pass): |
| 677 | yield branch, parent |
| 678 | parent_to_branches[parent].discard(branch) |
| 679 | del branch_tree[branch] |
| 680 | |
| 681 | |
iannucci@chromium.org | aa74cf6 | 2013-11-19 20:00:49 +0000 | [diff] [blame] | 682 | def tree(treeref, recurse=False): |
| 683 | """Returns a dict representation of a git tree object. |
| 684 | |
| 685 | Args: |
| 686 | treeref (str) - a git ref which resolves to a tree (commits count as trees). |
| 687 | recurse (bool) - include all of the tree's decendants too. File names will |
| 688 | take the form of 'some/path/to/file'. |
| 689 | |
| 690 | Return format: |
| 691 | { 'file_name': (mode, type, ref) } |
| 692 | |
| 693 | mode is an integer where: |
| 694 | * 0040000 - Directory |
| 695 | * 0100644 - Regular non-executable file |
| 696 | * 0100664 - Regular non-executable group-writeable file |
| 697 | * 0100755 - Regular executable file |
| 698 | * 0120000 - Symbolic link |
| 699 | * 0160000 - Gitlink |
| 700 | |
| 701 | type is a string where it's one of 'blob', 'commit', 'tree', 'tag'. |
| 702 | |
| 703 | ref is the hex encoded hash of the entry. |
| 704 | """ |
| 705 | ret = {} |
| 706 | opts = ['ls-tree', '--full-tree'] |
| 707 | if recurse: |
| 708 | opts.append('-r') |
| 709 | opts.append(treeref) |
| 710 | try: |
| 711 | for line in run(*opts).splitlines(): |
| 712 | mode, typ, ref, name = line.split(None, 3) |
| 713 | ret[name] = (mode, typ, ref) |
| 714 | except subprocess2.CalledProcessError: |
| 715 | return None |
| 716 | return ret |
| 717 | |
| 718 | |
iannucci@chromium.org | 8bc9b5c | 2014-03-12 01:36:18 +0000 | [diff] [blame] | 719 | def upstream(branch): |
| 720 | try: |
| 721 | return run('rev-parse', '--abbrev-ref', '--symbolic-full-name', |
| 722 | branch+'@{upstream}') |
| 723 | except subprocess2.CalledProcessError: |
| 724 | return None |
calamity@chromium.org | 9d2c880 | 2014-09-03 02:04:46 +0000 | [diff] [blame] | 725 | |
| 726 | def get_git_version(): |
| 727 | """Returns a tuple that contains the numeric components of the current git |
| 728 | version.""" |
| 729 | version_string = run('--version') |
| 730 | version_match = re.search(r'(\d+.)+(\d+)', version_string) |
| 731 | version = version_match.group() if version_match else '' |
| 732 | |
| 733 | return tuple(int(x) for x in version.split('.')) |
| 734 | |
| 735 | |
| 736 | def get_all_tracking_info(): |
| 737 | format_string = ( |
| 738 | '--format=%(refname:short):%(objectname:short):%(upstream:short):') |
| 739 | |
| 740 | # This is not covered by the depot_tools CQ which only has git version 1.8. |
| 741 | if get_git_version() >= MIN_UPSTREAM_TRACK_GIT_VERSION: # pragma: no cover |
| 742 | format_string += '%(upstream:track)' |
| 743 | |
| 744 | info_map = {} |
| 745 | data = run('for-each-ref', format_string, 'refs/heads') |
| 746 | TrackingInfo = collections.namedtuple( |
| 747 | 'TrackingInfo', 'hash upstream ahead behind') |
| 748 | for line in data.splitlines(): |
| 749 | (branch, branch_hash, upstream_branch, tracking_status) = line.split(':') |
| 750 | |
| 751 | ahead_match = re.search(r'ahead (\d+)', tracking_status) |
| 752 | ahead = int(ahead_match.group(1)) if ahead_match else None |
| 753 | |
| 754 | behind_match = re.search(r'behind (\d+)', tracking_status) |
| 755 | behind = int(behind_match.group(1)) if behind_match else None |
| 756 | |
| 757 | info_map[branch] = TrackingInfo( |
| 758 | hash=branch_hash, upstream=upstream_branch, ahead=ahead, behind=behind) |
| 759 | |
| 760 | # Set None for upstreams which are not branches (e.g empty upstream, remotes |
| 761 | # and deleted upstream branches). |
| 762 | missing_upstreams = {} |
| 763 | for info in info_map.values(): |
| 764 | if info.upstream not in info_map and info.upstream not in missing_upstreams: |
| 765 | missing_upstreams[info.upstream] = None |
| 766 | |
| 767 | return dict(info_map.items() + missing_upstreams.items()) |