blob: 7f2e13b62ee4f1620b76271382cd72ccc57ca303 [file] [log] [blame]
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001# Copyright 2014 The Chromium Authors. All rights reserved.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +00002# 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
7import multiprocessing.pool
8from multiprocessing.pool import IMapIterator
9def wrapper(func):
10 def wrap(self, timeout=None):
11 return func(self, timeout=timeout or 1e100)
12 return wrap
13IMapIterator.next = wrapper(IMapIterator.next)
14IMapIterator.__next__ = IMapIterator.next
15# TODO(iannucci): Monkeypatch all other 'wait' methods too.
16
17
18import binascii
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000019import collections
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000020import contextlib
21import functools
22import logging
iannucci@chromium.org97345eb2014-03-13 07:55:15 +000023import os
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000024import re
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000025import signal
26import sys
27import tempfile
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +000028import textwrap
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000029import threading
30
31import subprocess2
32
techtonik@gmail.coma5a945a2014-08-15 20:01:53 +000033ROOT = os.path.abspath(os.path.dirname(__file__))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000034
techtonik@gmail.coma5a945a2014-08-15 20:01:53 +000035GIT_EXE = ROOT+'\\git.bat' if sys.platform.startswith('win') else 'git'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000036TEST_MODE = False
37
38FREEZE = 'FREEZE'
39FREEZE_SECTIONS = {
40 'indexed': 'soft',
41 'unindexed': 'mixed'
42}
43FREEZE_MATCHER = re.compile(r'%s.(%s)' % (FREEZE, '|'.join(FREEZE_SECTIONS)))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000044
45
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000046# 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'.
53GIT_TRANSIENT_ERRORS = (
54 # crbug.com/285832
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000055 r'!.*\[remote rejected\].*\(error in hook\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000056
57 # crbug.com/289932
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000058 r'!.*\[remote rejected\].*\(failed to lock\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000059
60 # crbug.com/307156
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000061 r'!.*\[remote rejected\].*\(error in Gerrit backend\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000062
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
91GIT_TRANSIENT_ERRORS_RE = re.compile('|'.join(GIT_TRANSIENT_ERRORS),
92 re.IGNORECASE)
93
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000094# First version where the for-each-ref command's format string supported the
95# upstream:track token.
96MIN_UPSTREAM_TRACK_GIT_VERSION = (1, 9)
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000097
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000098class 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
105def 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
166def _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
177def 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
205class ProgressPrinter(object):
206 """Threaded single-stat status message printer."""
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000207 def __init__(self, fmt, enabled=None, fout=sys.stderr, period=0.5):
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000208 """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.org97345eb2014-03-13 07:55:15 +0000223 fout (file-like) - The stream to print status messages to.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000224 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.org97345eb2014-03-13 07:55:15 +0000236 self._stream = fout
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000237 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.orgc050a5b2014-03-26 06:18:50 +0000267def 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
280def branch_config(branch, option, default=None):
281 return config('branch.%s.%s' % (branch, option), default=default)
282
283
284def 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.org8bc9b5c2014-03-12 01:36:18 +0000294def branches(*args):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000295 NO_BRANCH = ('* (no branch', '* (detached from ')
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000296
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.org8bc9b5c2014-03-12 01:36:18 +0000317 if line.startswith(NO_BRANCH):
318 continue
319 yield line.split()[-1]
320
321
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000322def config(option, default=None):
323 try:
324 return run('config', '--get', option) or default
325 except subprocess2.CalledProcessError:
326 return default
327
328
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000329def config_list(option):
330 try:
331 return run('config', '--get-all', option).split()
332 except subprocess2.CalledProcessError:
333 return []
334
335
336def current_branch():
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000337 try:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000338 return run('rev-parse', '--abbrev-ref', 'HEAD')
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000339 except subprocess2.CalledProcessError:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000340 return None
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000341
342
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000343def del_branch_config(branch, option, scope='local'):
344 del_config('branch.%s.%s' % (branch, option), scope=scope)
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000345
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000346
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000347def del_config(option, scope='local'):
348 try:
349 run('config', '--' + scope, '--unset', option)
350 except subprocess2.CalledProcessError:
351 pass
352
353
354def freeze():
355 took_action = False
356
357 try:
358 run('commit', '-m', FREEZE + '.indexed')
359 took_action = True
360 except subprocess2.CalledProcessError:
361 pass
362
363 try:
364 run('add', '-A')
365 run('commit', '-m', FREEZE + '.unindexed')
366 took_action = True
367 except subprocess2.CalledProcessError:
368 pass
369
370 if not took_action:
371 return 'Nothing to freeze.'
372
373
374def get_branch_tree():
375 """Get the dictionary of {branch: parent}, compatible with topo_iter.
376
377 Returns a tuple of (skipped, <branch_tree dict>) where skipped is a set of
378 branches without upstream branches defined.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000379 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000380 skipped = set()
381 branch_tree = {}
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000382
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000383 for branch in branches():
384 parent = upstream(branch)
385 if not parent:
386 skipped.add(branch)
387 continue
388 branch_tree[branch] = parent
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000389
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000390 return skipped, branch_tree
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000391
392
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000393def get_or_create_merge_base(branch, parent=None):
394 """Finds the configured merge base for branch.
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000395
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000396 If parent is supplied, it's used instead of calling upstream(branch).
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000397 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000398 base = branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000399 base_upstream = branch_config(branch, 'base-upstream')
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000400 parent = parent or upstream(branch)
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000401 if not parent:
402 return None
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000403 actual_merge_base = run('merge-base', parent, branch)
404
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000405 if base_upstream != parent:
406 base = None
407 base_upstream = None
408
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000409 def is_ancestor(a, b):
410 return run_with_retcode('merge-base', '--is-ancestor', a, b) == 0
411
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000412 if base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000413 if not is_ancestor(base, branch):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000414 logging.debug('Found WRONG pre-set merge-base for %s: %s', branch, base)
415 base = None
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000416 elif is_ancestor(base, actual_merge_base):
417 logging.debug('Found OLD pre-set merge-base for %s: %s', branch, base)
418 base = None
419 else:
420 logging.debug('Found pre-set merge-base for %s: %s', branch, base)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000421
422 if not base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000423 base = actual_merge_base
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000424 manual_merge_base(branch, base, parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000425
426 return base
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000427
428
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000429def hash_multi(*reflike):
430 return run('rev-parse', *reflike).splitlines()
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000431
432
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000433def hash_one(reflike, short=False):
434 args = ['rev-parse', reflike]
435 if short:
436 args.insert(1, '--short')
437 return run(*args)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000438
439
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000440def in_rebase():
441 git_dir = run('rev-parse', '--git-dir')
442 return (
443 os.path.exists(os.path.join(git_dir, 'rebase-merge')) or
444 os.path.exists(os.path.join(git_dir, 'rebase-apply')))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000445
446
447def intern_f(f, kind='blob'):
448 """Interns a file object into the git object store.
449
450 Args:
451 f (file-like object) - The file-like object to intern
452 kind (git object type) - One of 'blob', 'commit', 'tree', 'tag'.
453
454 Returns the git hash of the interned object (hex encoded).
455 """
456 ret = run('hash-object', '-t', kind, '-w', '--stdin', stdin=f)
457 f.close()
458 return ret
459
460
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000461def is_dormant(branch):
462 # TODO(iannucci): Do an oldness check?
463 return branch_config(branch, 'dormant', 'false') != 'false'
464
465
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000466def manual_merge_base(branch, base, parent):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000467 set_branch_config(branch, 'base', base)
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000468 set_branch_config(branch, 'base-upstream', parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000469
470
471def mktree(treedict):
472 """Makes a git tree object and returns its hash.
473
474 See |tree()| for the values of mode, type, and ref.
475
476 Args:
477 treedict - { name: (mode, type, ref) }
478 """
479 with tempfile.TemporaryFile() as f:
480 for name, (mode, typ, ref) in treedict.iteritems():
481 f.write('%s %s %s\t%s\0' % (mode, typ, ref, name))
482 f.seek(0)
483 return run('mktree', '-z', stdin=f)
484
485
486def parse_commitrefs(*commitrefs):
487 """Returns binary encoded commit hashes for one or more commitrefs.
488
489 A commitref is anything which can resolve to a commit. Popular examples:
490 * 'HEAD'
491 * 'origin/master'
492 * 'cool_branch~2'
493 """
494 try:
495 return map(binascii.unhexlify, hash_multi(*commitrefs))
496 except subprocess2.CalledProcessError:
497 raise BadCommitRefException(commitrefs)
498
499
sbc@chromium.org384039b2014-10-13 21:01:00 +0000500RebaseRet = collections.namedtuple('RebaseRet', 'success stdout stderr')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000501
502
503def rebase(parent, start, branch, abort=False):
504 """Rebases |start|..|branch| onto the branch |parent|.
505
506 Args:
507 parent - The new parent ref for the rebased commits.
508 start - The commit to start from
509 branch - The branch to rebase
510 abort - If True, will call git-rebase --abort in the event that the rebase
511 doesn't complete successfully.
512
513 Returns a namedtuple with fields:
514 success - a boolean indicating that the rebase command completed
515 successfully.
516 message - if the rebase failed, this contains the stdout of the failed
517 rebase.
518 """
519 try:
520 args = ['--onto', parent, start, branch]
521 if TEST_MODE:
522 args.insert(0, '--committer-date-is-author-date')
523 run('rebase', *args)
sbc@chromium.org384039b2014-10-13 21:01:00 +0000524 return RebaseRet(True, '', '')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000525 except subprocess2.CalledProcessError as cpe:
526 if abort:
527 run('rebase', '--abort')
sbc@chromium.org384039b2014-10-13 21:01:00 +0000528 return RebaseRet(False, cpe.stdout, cpe.stderr)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000529
530
531def remove_merge_base(branch):
532 del_branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000533 del_branch_config(branch, 'base-upstream')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000534
535
536def root():
537 return config('depot-tools.upstream', 'origin/master')
538
539
540def run(*cmd, **kwargs):
541 """The same as run_with_stderr, except it only returns stdout."""
542 return run_with_stderr(*cmd, **kwargs)[0]
543
544
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000545def run_with_retcode(*cmd, **kwargs):
546 """Run a command but only return the status code."""
547 try:
548 run(*cmd, **kwargs)
549 return 0
550 except subprocess2.CalledProcessError as cpe:
551 return cpe.returncode
552
553
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000554def 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.org21980022014-04-11 04:51:49 +0000562 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000563 proc = subprocess2.Popen(cmd, **kwargs)
564 return proc.stdout
565
566
567def 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.org21980022014-04-11 04:51:49 +0000582 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000583 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
596def set_branch_config(branch, option, value, scope='local'):
597 set_config('branch.%s.%s' % (branch, option), value, scope=scope)
598
599
600def set_config(option, value, scope='local'):
601 run('config', '--' + scope, option, value)
602
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000603
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000604def squash_current_branch(header=None, merge_base=None):
605 header = header or 'git squash commit.'
606 merge_base = merge_base or get_or_create_merge_base(current_branch())
607 log_msg = header + '\n'
608 if log_msg:
609 log_msg += '\n'
610 log_msg += run('log', '--reverse', '--format=%H%n%B', '%s..HEAD' % merge_base)
611 run('reset', '--soft', merge_base)
612 run('commit', '-a', '-F', '-', indata=log_msg)
613
614
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000615def tags(*args):
616 return run('tag', *args).splitlines()
617
618
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000619def thaw():
620 took_action = False
621 for sha in (s.strip() for s in run_stream('rev-list', 'HEAD').xreadlines()):
622 msg = run('show', '--format=%f%b', '-s', 'HEAD')
623 match = FREEZE_MATCHER.match(msg)
624 if not match:
625 if not took_action:
626 return 'Nothing to thaw.'
627 break
628
629 run('reset', '--' + FREEZE_SECTIONS[match.group(1)], sha)
630 took_action = True
631
632
633def topo_iter(branch_tree, top_down=True):
634 """Generates (branch, parent) in topographical order for a branch tree.
635
636 Given a tree:
637
638 A1
639 B1 B2
640 C1 C2 C3
641 D1
642
643 branch_tree would look like: {
644 'D1': 'C3',
645 'C3': 'B2',
646 'B2': 'A1',
647 'C1': 'B1',
648 'C2': 'B1',
649 'B1': 'A1',
650 }
651
652 It is OK to have multiple 'root' nodes in your graph.
653
654 if top_down is True, items are yielded from A->D. Otherwise they're yielded
655 from D->A. Within a layer the branches will be yielded in sorted order.
656 """
657 branch_tree = branch_tree.copy()
658
659 # TODO(iannucci): There is probably a more efficient way to do these.
660 if top_down:
661 while branch_tree:
662 this_pass = [(b, p) for b, p in branch_tree.iteritems()
663 if p not in branch_tree]
664 assert this_pass, "Branch tree has cycles: %r" % branch_tree
665 for branch, parent in sorted(this_pass):
666 yield branch, parent
667 del branch_tree[branch]
668 else:
669 parent_to_branches = collections.defaultdict(set)
670 for branch, parent in branch_tree.iteritems():
671 parent_to_branches[parent].add(branch)
672
673 while branch_tree:
674 this_pass = [(b, p) for b, p in branch_tree.iteritems()
675 if not parent_to_branches[b]]
676 assert this_pass, "Branch tree has cycles: %r" % branch_tree
677 for branch, parent in sorted(this_pass):
678 yield branch, parent
679 parent_to_branches[parent].discard(branch)
680 del branch_tree[branch]
681
682
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000683def tree(treeref, recurse=False):
684 """Returns a dict representation of a git tree object.
685
686 Args:
687 treeref (str) - a git ref which resolves to a tree (commits count as trees).
688 recurse (bool) - include all of the tree's decendants too. File names will
689 take the form of 'some/path/to/file'.
690
691 Return format:
692 { 'file_name': (mode, type, ref) }
693
694 mode is an integer where:
695 * 0040000 - Directory
696 * 0100644 - Regular non-executable file
697 * 0100664 - Regular non-executable group-writeable file
698 * 0100755 - Regular executable file
699 * 0120000 - Symbolic link
700 * 0160000 - Gitlink
701
702 type is a string where it's one of 'blob', 'commit', 'tree', 'tag'.
703
704 ref is the hex encoded hash of the entry.
705 """
706 ret = {}
707 opts = ['ls-tree', '--full-tree']
708 if recurse:
709 opts.append('-r')
710 opts.append(treeref)
711 try:
712 for line in run(*opts).splitlines():
713 mode, typ, ref, name = line.split(None, 3)
714 ret[name] = (mode, typ, ref)
715 except subprocess2.CalledProcessError:
716 return None
717 return ret
718
719
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000720def upstream(branch):
721 try:
722 return run('rev-parse', '--abbrev-ref', '--symbolic-full-name',
723 branch+'@{upstream}')
724 except subprocess2.CalledProcessError:
725 return None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000726
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000727
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000728def get_git_version():
729 """Returns a tuple that contains the numeric components of the current git
730 version."""
731 version_string = run('--version')
732 version_match = re.search(r'(\d+.)+(\d+)', version_string)
733 version = version_match.group() if version_match else ''
734
735 return tuple(int(x) for x in version.split('.'))
736
737
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000738def get_branches_info(include_tracking_status):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000739 format_string = (
740 '--format=%(refname:short):%(objectname:short):%(upstream:short):')
741
742 # This is not covered by the depot_tools CQ which only has git version 1.8.
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000743 if (include_tracking_status and
744 get_git_version() >= MIN_UPSTREAM_TRACK_GIT_VERSION): # pragma: no cover
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000745 format_string += '%(upstream:track)'
746
747 info_map = {}
748 data = run('for-each-ref', format_string, 'refs/heads')
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000749 BranchesInfo = collections.namedtuple(
750 'BranchesInfo', 'hash upstream ahead behind')
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000751 for line in data.splitlines():
752 (branch, branch_hash, upstream_branch, tracking_status) = line.split(':')
753
754 ahead_match = re.search(r'ahead (\d+)', tracking_status)
755 ahead = int(ahead_match.group(1)) if ahead_match else None
756
757 behind_match = re.search(r'behind (\d+)', tracking_status)
758 behind = int(behind_match.group(1)) if behind_match else None
759
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000760 info_map[branch] = BranchesInfo(
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000761 hash=branch_hash, upstream=upstream_branch, ahead=ahead, behind=behind)
762
763 # Set None for upstreams which are not branches (e.g empty upstream, remotes
764 # and deleted upstream branches).
765 missing_upstreams = {}
766 for info in info_map.values():
767 if info.upstream not in info_map and info.upstream not in missing_upstreams:
768 missing_upstreams[info.upstream] = None
769
770 return dict(info_map.items() + missing_upstreams.items())