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