blob: 298ecc4ff3a8c9ee8f9263130b3751167b5eb5fa [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
33
34GIT_EXE = 'git.bat' if sys.platform.startswith('win') else 'git'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000035TEST_MODE = False
36
37FREEZE = 'FREEZE'
38FREEZE_SECTIONS = {
39 'indexed': 'soft',
40 'unindexed': 'mixed'
41}
42FREEZE_MATCHER = re.compile(r'%s.(%s)' % (FREEZE, '|'.join(FREEZE_SECTIONS)))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000043
44
45class 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
52def 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
113def _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
124def 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
152class ProgressPrinter(object):
153 """Threaded single-stat status message printer."""
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000154 def __init__(self, fmt, enabled=None, fout=sys.stderr, period=0.5):
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000155 """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.org97345eb2014-03-13 07:55:15 +0000170 fout (file-like) - The stream to print status messages to.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000171 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.org97345eb2014-03-13 07:55:15 +0000183 self._stream = fout
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000184 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.orgc050a5b2014-03-26 06:18:50 +0000214def 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
227def branch_config(branch, option, default=None):
228 return config('branch.%s.%s' % (branch, option), default=default)
229
230
231def 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.org8bc9b5c2014-03-12 01:36:18 +0000241def branches(*args):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000242 NO_BRANCH = ('* (no branch', '* (detached from ')
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000243
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.org8bc9b5c2014-03-12 01:36:18 +0000264 if line.startswith(NO_BRANCH):
265 continue
266 yield line.split()[-1]
267
268
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000269def 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.orgc050a5b2014-03-26 06:18:50 +0000278def 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.org8bc9b5c2014-03-12 01:36:18 +0000285def config_list(option):
286 try:
287 return run('config', '--get-all', option).split()
288 except subprocess2.CalledProcessError:
289 return []
290
291
292def current_branch():
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000293 try:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000294 return run('rev-parse', '--abbrev-ref', 'HEAD')
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000295 except subprocess2.CalledProcessError:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000296 return None
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000297
298
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000299def del_branch_config(branch, option, scope='local'):
300 del_config('branch.%s.%s' % (branch, option), scope=scope)
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000301
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000302
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000303def del_config(option, scope='local'):
304 try:
305 run('config', '--' + scope, '--unset', option)
306 except subprocess2.CalledProcessError:
307 pass
308
309
310def 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
330def 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.orgaa74cf62013-11-19 20:00:49 +0000335 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000336 skipped = set()
337 branch_tree = {}
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000338
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000339 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.org97345eb2014-03-13 07:55:15 +0000345
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000346 return skipped, branch_tree
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000347
348
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000349def get_or_create_merge_base(branch, parent=None):
350 """Finds the configured merge base for branch.
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000351
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000352 If parent is supplied, it's used instead of calling upstream(branch).
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000353 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000354 base = branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000355 base_upstream = branch_config(branch, 'base-upstream')
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000356 parent = parent or upstream(branch)
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000357 if not parent:
358 return None
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000359 actual_merge_base = run('merge-base', parent, branch)
360
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000361 if base_upstream != parent:
362 base = None
363 base_upstream = None
364
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000365 def is_ancestor(a, b):
366 return run_with_retcode('merge-base', '--is-ancestor', a, b) == 0
367
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000368 if base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000369 if not is_ancestor(base, branch):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000370 logging.debug('Found WRONG pre-set merge-base for %s: %s', branch, base)
371 base = None
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000372 elif is_ancestor(base, actual_merge_base):
373 logging.debug('Found OLD pre-set merge-base for %s: %s', branch, base)
374 base = None
375 else:
376 logging.debug('Found pre-set merge-base for %s: %s', branch, base)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000377
378 if not base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000379 base = actual_merge_base
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000380 manual_merge_base(branch, base, parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000381
382 return base
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000383
384
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000385def hash_multi(*reflike):
386 return run('rev-parse', *reflike).splitlines()
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000387
388
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000389def hash_one(reflike):
390 return run('rev-parse', reflike)
391
392
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000393def in_rebase():
394 git_dir = run('rev-parse', '--git-dir')
395 return (
396 os.path.exists(os.path.join(git_dir, 'rebase-merge')) or
397 os.path.exists(os.path.join(git_dir, 'rebase-apply')))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000398
399
400def intern_f(f, kind='blob'):
401 """Interns a file object into the git object store.
402
403 Args:
404 f (file-like object) - The file-like object to intern
405 kind (git object type) - One of 'blob', 'commit', 'tree', 'tag'.
406
407 Returns the git hash of the interned object (hex encoded).
408 """
409 ret = run('hash-object', '-t', kind, '-w', '--stdin', stdin=f)
410 f.close()
411 return ret
412
413
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000414def is_dormant(branch):
415 # TODO(iannucci): Do an oldness check?
416 return branch_config(branch, 'dormant', 'false') != 'false'
417
418
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000419def manual_merge_base(branch, base, parent):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000420 set_branch_config(branch, 'base', base)
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000421 set_branch_config(branch, 'base-upstream', parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000422
423
424def mktree(treedict):
425 """Makes a git tree object and returns its hash.
426
427 See |tree()| for the values of mode, type, and ref.
428
429 Args:
430 treedict - { name: (mode, type, ref) }
431 """
432 with tempfile.TemporaryFile() as f:
433 for name, (mode, typ, ref) in treedict.iteritems():
434 f.write('%s %s %s\t%s\0' % (mode, typ, ref, name))
435 f.seek(0)
436 return run('mktree', '-z', stdin=f)
437
438
439def parse_commitrefs(*commitrefs):
440 """Returns binary encoded commit hashes for one or more commitrefs.
441
442 A commitref is anything which can resolve to a commit. Popular examples:
443 * 'HEAD'
444 * 'origin/master'
445 * 'cool_branch~2'
446 """
447 try:
448 return map(binascii.unhexlify, hash_multi(*commitrefs))
449 except subprocess2.CalledProcessError:
450 raise BadCommitRefException(commitrefs)
451
452
453RebaseRet = collections.namedtuple('RebaseRet', 'success message')
454
455
456def rebase(parent, start, branch, abort=False):
457 """Rebases |start|..|branch| onto the branch |parent|.
458
459 Args:
460 parent - The new parent ref for the rebased commits.
461 start - The commit to start from
462 branch - The branch to rebase
463 abort - If True, will call git-rebase --abort in the event that the rebase
464 doesn't complete successfully.
465
466 Returns a namedtuple with fields:
467 success - a boolean indicating that the rebase command completed
468 successfully.
469 message - if the rebase failed, this contains the stdout of the failed
470 rebase.
471 """
472 try:
473 args = ['--onto', parent, start, branch]
474 if TEST_MODE:
475 args.insert(0, '--committer-date-is-author-date')
476 run('rebase', *args)
477 return RebaseRet(True, '')
478 except subprocess2.CalledProcessError as cpe:
479 if abort:
480 run('rebase', '--abort')
iannucci@chromium.org56a624a2014-03-26 21:23:09 +0000481 return RebaseRet(False, cpe.stdout)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000482
483
484def remove_merge_base(branch):
485 del_branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000486 del_branch_config(branch, 'base-upstream')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000487
488
489def root():
490 return config('depot-tools.upstream', 'origin/master')
491
492
493def run(*cmd, **kwargs):
494 """The same as run_with_stderr, except it only returns stdout."""
495 return run_with_stderr(*cmd, **kwargs)[0]
496
497
498def run_stream(*cmd, **kwargs):
499 """Runs a git command. Returns stdout as a PIPE (file-like object).
500
501 stderr is dropped to avoid races if the process outputs to both stdout and
502 stderr.
503 """
504 kwargs.setdefault('stderr', subprocess2.VOID)
505 kwargs.setdefault('stdout', subprocess2.PIPE)
iannucci@chromium.org21980022014-04-11 04:51:49 +0000506 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000507 proc = subprocess2.Popen(cmd, **kwargs)
508 return proc.stdout
509
510
511def run_with_stderr(*cmd, **kwargs):
512 """Runs a git command.
513
514 Returns (stdout, stderr) as a pair of strings.
515
516 kwargs
517 autostrip (bool) - Strip the output. Defaults to True.
518 indata (str) - Specifies stdin data for the process.
519 """
520 kwargs.setdefault('stdin', subprocess2.PIPE)
521 kwargs.setdefault('stdout', subprocess2.PIPE)
522 kwargs.setdefault('stderr', subprocess2.PIPE)
523 autostrip = kwargs.pop('autostrip', True)
524 indata = kwargs.pop('indata', None)
525
iannucci@chromium.org21980022014-04-11 04:51:49 +0000526 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000527 proc = subprocess2.Popen(cmd, **kwargs)
528 ret, err = proc.communicate(indata)
529 retcode = proc.wait()
530 if retcode != 0:
531 raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(), ret, err)
532
533 if autostrip:
534 ret = (ret or '').strip()
535 err = (err or '').strip()
536
537 return ret, err
538
539
540def set_branch_config(branch, option, value, scope='local'):
541 set_config('branch.%s.%s' % (branch, option), value, scope=scope)
542
543
544def set_config(option, value, scope='local'):
545 run('config', '--' + scope, option, value)
546
547def squash_current_branch(header=None, merge_base=None):
548 header = header or 'git squash commit.'
549 merge_base = merge_base or get_or_create_merge_base(current_branch())
550 log_msg = header + '\n'
551 if log_msg:
552 log_msg += '\n'
553 log_msg += run('log', '--reverse', '--format=%H%n%B', '%s..HEAD' % merge_base)
554 run('reset', '--soft', merge_base)
555 run('commit', '-a', '-F', '-', indata=log_msg)
556
557
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000558def tags(*args):
559 return run('tag', *args).splitlines()
560
561
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000562def thaw():
563 took_action = False
564 for sha in (s.strip() for s in run_stream('rev-list', 'HEAD').xreadlines()):
565 msg = run('show', '--format=%f%b', '-s', 'HEAD')
566 match = FREEZE_MATCHER.match(msg)
567 if not match:
568 if not took_action:
569 return 'Nothing to thaw.'
570 break
571
572 run('reset', '--' + FREEZE_SECTIONS[match.group(1)], sha)
573 took_action = True
574
575
576def topo_iter(branch_tree, top_down=True):
577 """Generates (branch, parent) in topographical order for a branch tree.
578
579 Given a tree:
580
581 A1
582 B1 B2
583 C1 C2 C3
584 D1
585
586 branch_tree would look like: {
587 'D1': 'C3',
588 'C3': 'B2',
589 'B2': 'A1',
590 'C1': 'B1',
591 'C2': 'B1',
592 'B1': 'A1',
593 }
594
595 It is OK to have multiple 'root' nodes in your graph.
596
597 if top_down is True, items are yielded from A->D. Otherwise they're yielded
598 from D->A. Within a layer the branches will be yielded in sorted order.
599 """
600 branch_tree = branch_tree.copy()
601
602 # TODO(iannucci): There is probably a more efficient way to do these.
603 if top_down:
604 while branch_tree:
605 this_pass = [(b, p) for b, p in branch_tree.iteritems()
606 if p not in branch_tree]
607 assert this_pass, "Branch tree has cycles: %r" % branch_tree
608 for branch, parent in sorted(this_pass):
609 yield branch, parent
610 del branch_tree[branch]
611 else:
612 parent_to_branches = collections.defaultdict(set)
613 for branch, parent in branch_tree.iteritems():
614 parent_to_branches[parent].add(branch)
615
616 while branch_tree:
617 this_pass = [(b, p) for b, p in branch_tree.iteritems()
618 if not parent_to_branches[b]]
619 assert this_pass, "Branch tree has cycles: %r" % branch_tree
620 for branch, parent in sorted(this_pass):
621 yield branch, parent
622 parent_to_branches[parent].discard(branch)
623 del branch_tree[branch]
624
625
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000626def tree(treeref, recurse=False):
627 """Returns a dict representation of a git tree object.
628
629 Args:
630 treeref (str) - a git ref which resolves to a tree (commits count as trees).
631 recurse (bool) - include all of the tree's decendants too. File names will
632 take the form of 'some/path/to/file'.
633
634 Return format:
635 { 'file_name': (mode, type, ref) }
636
637 mode is an integer where:
638 * 0040000 - Directory
639 * 0100644 - Regular non-executable file
640 * 0100664 - Regular non-executable group-writeable file
641 * 0100755 - Regular executable file
642 * 0120000 - Symbolic link
643 * 0160000 - Gitlink
644
645 type is a string where it's one of 'blob', 'commit', 'tree', 'tag'.
646
647 ref is the hex encoded hash of the entry.
648 """
649 ret = {}
650 opts = ['ls-tree', '--full-tree']
651 if recurse:
652 opts.append('-r')
653 opts.append(treeref)
654 try:
655 for line in run(*opts).splitlines():
656 mode, typ, ref, name = line.split(None, 3)
657 ret[name] = (mode, typ, ref)
658 except subprocess2.CalledProcessError:
659 return None
660 return ret
661
662
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000663def upstream(branch):
664 try:
665 return run('rev-parse', '--abbrev-ref', '--symbolic-full-name',
666 branch+'@{upstream}')
667 except subprocess2.CalledProcessError:
668 return None