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