blob: 2e268da0f35b9dedda1a7f0a49548929be5e02fe [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.orgedeaa812014-03-26 21:27:47 +0000322def 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.orgc050a5b2014-03-26 06:18:50 +0000331def 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.org8bc9b5c2014-03-12 01:36:18 +0000338def config_list(option):
339 try:
340 return run('config', '--get-all', option).split()
341 except subprocess2.CalledProcessError:
342 return []
343
344
345def current_branch():
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000346 try:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000347 return run('rev-parse', '--abbrev-ref', 'HEAD')
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000348 except subprocess2.CalledProcessError:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000349 return None
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000350
351
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000352def del_branch_config(branch, option, scope='local'):
353 del_config('branch.%s.%s' % (branch, option), scope=scope)
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000354
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000355
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000356def del_config(option, scope='local'):
357 try:
358 run('config', '--' + scope, '--unset', option)
359 except subprocess2.CalledProcessError:
360 pass
361
362
363def 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
383def 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.orgaa74cf62013-11-19 20:00:49 +0000388 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000389 skipped = set()
390 branch_tree = {}
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000391
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000392 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.org97345eb2014-03-13 07:55:15 +0000398
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000399 return skipped, branch_tree
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000400
401
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000402def get_or_create_merge_base(branch, parent=None):
403 """Finds the configured merge base for branch.
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000404
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000405 If parent is supplied, it's used instead of calling upstream(branch).
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000406 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000407 base = branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000408 base_upstream = branch_config(branch, 'base-upstream')
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000409 parent = parent or upstream(branch)
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000410 if not parent:
411 return None
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000412 actual_merge_base = run('merge-base', parent, branch)
413
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000414 if base_upstream != parent:
415 base = None
416 base_upstream = None
417
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000418 def is_ancestor(a, b):
419 return run_with_retcode('merge-base', '--is-ancestor', a, b) == 0
420
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000421 if base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000422 if not is_ancestor(base, branch):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000423 logging.debug('Found WRONG pre-set merge-base for %s: %s', branch, base)
424 base = None
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000425 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.orgc050a5b2014-03-26 06:18:50 +0000430
431 if not base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000432 base = actual_merge_base
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000433 manual_merge_base(branch, base, parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000434
435 return base
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000436
437
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000438def hash_multi(*reflike):
439 return run('rev-parse', *reflike).splitlines()
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000440
441
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000442def hash_one(reflike, short=False):
443 args = ['rev-parse', reflike]
444 if short:
445 args.insert(1, '--short')
446 return run(*args)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000447
448
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000449def 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.orgaa74cf62013-11-19 20:00:49 +0000454
455
456def 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.orgc050a5b2014-03-26 06:18:50 +0000470def is_dormant(branch):
471 # TODO(iannucci): Do an oldness check?
472 return branch_config(branch, 'dormant', 'false') != 'false'
473
474
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000475def manual_merge_base(branch, base, parent):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000476 set_branch_config(branch, 'base', base)
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000477 set_branch_config(branch, 'base-upstream', parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000478
479
480def 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
495def 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
509RebaseRet = collections.namedtuple('RebaseRet', 'success message')
510
511
512def 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.org56a624a2014-03-26 21:23:09 +0000537 return RebaseRet(False, cpe.stdout)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000538
539
540def remove_merge_base(branch):
541 del_branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000542 del_branch_config(branch, 'base-upstream')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000543
544
545def root():
546 return config('depot-tools.upstream', 'origin/master')
547
548
549def 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
554def 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
603def 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.org8bc9b5c2014-03-12 01:36:18 +0000614def tags(*args):
615 return run('tag', *args).splitlines()
616
617
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000618def 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
632def 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.orgaa74cf62013-11-19 20:00:49 +0000682def 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.org8bc9b5c2014-03-12 01:36:18 +0000719def 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.org9d2c8802014-09-03 02:04:46 +0000725
726def 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
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000736def get_branches_info(include_tracking_status):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000737 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.
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000741 if (include_tracking_status and
742 get_git_version() >= MIN_UPSTREAM_TRACK_GIT_VERSION): # pragma: no cover
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000743 format_string += '%(upstream:track)'
744
745 info_map = {}
746 data = run('for-each-ref', format_string, 'refs/heads')
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000747 BranchesInfo = collections.namedtuple(
748 'BranchesInfo', 'hash upstream ahead behind')
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000749 for line in data.splitlines():
750 (branch, branch_hash, upstream_branch, tracking_status) = line.split(':')
751
752 ahead_match = re.search(r'ahead (\d+)', tracking_status)
753 ahead = int(ahead_match.group(1)) if ahead_match else None
754
755 behind_match = re.search(r'behind (\d+)', tracking_status)
756 behind = int(behind_match.group(1)) if behind_match else None
757
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000758 info_map[branch] = BranchesInfo(
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000759 hash=branch_hash, upstream=upstream_branch, ahead=ahead, behind=behind)
760
761 # Set None for upstreams which are not branches (e.g empty upstream, remotes
762 # and deleted upstream branches).
763 missing_upstreams = {}
764 for info in info_map.values():
765 if info.upstream not in info_map and info.upstream not in missing_upstreams:
766 missing_upstreams[info.upstream] = None
767
768 return dict(info_map.items() + missing_upstreams.items())