blob: 86a571e2f54f9e4694382c37b98d95f7285e900b [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
Raul Tambrec2f74c12019-03-19 05:55:53 +00007
8from __future__ import print_function
Edward Lemur12a537f2019-10-03 21:57:15 +00009from __future__ import unicode_literals
Raul Tambrec2f74c12019-03-19 05:55:53 +000010
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000011import multiprocessing.pool
Josip Sokcevicde6c4562020-03-26 00:39:42 +000012import sys
13import threading
14
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000015from multiprocessing.pool import IMapIterator
Josip Sokcevicde6c4562020-03-26 00:39:42 +000016
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000017def wrapper(func):
18 def wrap(self, timeout=None):
Josip Sokcevicde6c4562020-03-26 00:39:42 +000019 default_timeout = (1 << 31 if sys.version_info.major == 2 else
20 threading.TIMEOUT_MAX)
21 return func(self, timeout=timeout or default_timeout)
22
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000023 return wrap
24IMapIterator.next = wrapper(IMapIterator.next)
25IMapIterator.__next__ = IMapIterator.next
26# TODO(iannucci): Monkeypatch all other 'wait' methods too.
27
28
29import binascii
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000030import collections
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000031import contextlib
32import functools
33import logging
iannucci@chromium.org97345eb2014-03-13 07:55:15 +000034import os
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000035import re
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +000036import setup_color
sammc@chromium.org900a33f2015-09-29 06:57:09 +000037import shutil
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000038import signal
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000039import tempfile
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +000040import textwrap
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000041
42import subprocess2
43
Raul Tambrec2f74c12019-03-19 05:55:53 +000044from io import BytesIO
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000045
agable02b3c982016-06-22 07:51:22 -070046
Edward Lemurb800fde2020-01-10 23:04:44 +000047if sys.version_info.major == 2:
48 # On Python 3, BrokenPipeError is raised instead.
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +000049 # pylint:disable=redefined-builtin
Edward Lemurb800fde2020-01-10 23:04:44 +000050 BrokenPipeError = IOError
51
52
agable02b3c982016-06-22 07:51:22 -070053ROOT = os.path.abspath(os.path.dirname(__file__))
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +000054IS_WIN = sys.platform == 'win32'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000055TEST_MODE = False
56
Dan Jacques209a6812017-07-12 11:40:20 -070057
58def win_find_git():
59 for elem in os.environ.get('PATH', '').split(os.pathsep):
60 for candidate in ('git.exe', 'git.bat'):
61 path = os.path.join(elem, candidate)
62 if os.path.isfile(path):
63 return path
64 raise ValueError('Could not find Git on PATH.')
65
66
67GIT_EXE = 'git' if not IS_WIN else win_find_git()
68
69
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000070FREEZE = 'FREEZE'
71FREEZE_SECTIONS = {
72 'indexed': 'soft',
73 'unindexed': 'mixed'
74}
75FREEZE_MATCHER = re.compile(r'%s.(%s)' % (FREEZE, '|'.join(FREEZE_SECTIONS)))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000076
77
Dan Jacques2f8b0c12017-04-05 12:57:21 -070078# NOTE: This list is DEPRECATED in favor of the Infra Git wrapper:
Josip Sokcevic9c0dc302020-11-20 18:41:25 +000079# https://chromium.googlesource.com/infra/infra/+/HEAD/go/src/infra/tools/git
Dan Jacques2f8b0c12017-04-05 12:57:21 -070080#
81# New entries should be added to the Git wrapper, NOT to this list. "git_retry"
82# is, similarly, being deprecated in favor of the Git wrapper.
83#
84# ---
85#
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000086# Retry a git operation if git returns a error response with any of these
87# messages. It's all observed 'bad' GoB responses so far.
88#
89# This list is inspired/derived from the one in ChromiumOS's Chromite:
90# <CHROMITE>/lib/git.py::GIT_TRANSIENT_ERRORS
91#
92# It was last imported from '7add3ac29564d98ac35ce426bc295e743e7c0c02'.
93GIT_TRANSIENT_ERRORS = (
94 # crbug.com/285832
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000095 r'!.*\[remote rejected\].*\(error in hook\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000096
97 # crbug.com/289932
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000098 r'!.*\[remote rejected\].*\(failed to lock\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000099
100 # crbug.com/307156
iannucci@chromium.org6e95d402014-08-29 22:10:55 +0000101 r'!.*\[remote rejected\].*\(error in Gerrit backend\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +0000102
103 # crbug.com/285832
104 r'remote error: Internal Server Error',
105
106 # crbug.com/294449
107 r'fatal: Couldn\'t find remote ref ',
108
109 # crbug.com/220543
110 r'git fetch_pack: expected ACK/NAK, got',
111
112 # crbug.com/189455
113 r'protocol error: bad pack header',
114
115 # crbug.com/202807
116 r'The remote end hung up unexpectedly',
117
118 # crbug.com/298189
119 r'TLS packet with unexpected length was received',
120
121 # crbug.com/187444
122 r'RPC failed; result=\d+, HTTP code = \d+',
123
dnj@chromium.orgde219ec2014-07-28 17:39:08 +0000124 # crbug.com/388876
125 r'Connection timed out',
dnj@chromium.org45cddd62014-11-06 19:36:42 +0000126
127 # crbug.com/430343
128 # TODO(dnj): Resync with Chromite.
129 r'The requested URL returned error: 5\d+',
Arikonb3a21482016-07-22 10:12:24 -0700130
131 r'Connection reset by peer',
132
133 r'Unable to look up',
134
135 r'Couldn\'t resolve host',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +0000136)
137
138GIT_TRANSIENT_ERRORS_RE = re.compile('|'.join(GIT_TRANSIENT_ERRORS),
139 re.IGNORECASE)
140
raphael.kubo.da.costa@intel.com58d05b02015-06-24 08:54:41 +0000141# git's for-each-ref command first supported the upstream:track token in its
142# format string in version 1.9.0, but some usages were broken until 2.3.0.
143# See git commit b6160d95 for more information.
144MIN_UPSTREAM_TRACK_GIT_VERSION = (2, 3)
dnj@chromium.orgde219ec2014-07-28 17:39:08 +0000145
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000146class BadCommitRefException(Exception):
147 def __init__(self, refs):
148 msg = ('one of %s does not seem to be a valid commitref.' %
149 str(refs))
150 super(BadCommitRefException, self).__init__(msg)
151
152
153def memoize_one(**kwargs):
154 """Memoizes a single-argument pure function.
155
156 Values of None are not cached.
157
158 Kwargs:
159 threadsafe (bool) - REQUIRED. Specifies whether to use locking around
160 cache manipulation functions. This is a kwarg so that users of memoize_one
161 are forced to explicitly and verbosely pick True or False.
162
163 Adds three methods to the decorated function:
164 * get(key, default=None) - Gets the value for this key from the cache.
165 * set(key, value) - Sets the value for this key from the cache.
166 * clear() - Drops the entire contents of the cache. Useful for unittests.
167 * update(other) - Updates the contents of the cache from another dict.
168 """
169 assert 'threadsafe' in kwargs, 'Must specify threadsafe={True,False}'
170 threadsafe = kwargs['threadsafe']
171
172 if threadsafe:
173 def withlock(lock, f):
174 def inner(*args, **kwargs):
175 with lock:
176 return f(*args, **kwargs)
177 return inner
178 else:
179 def withlock(_lock, f):
180 return f
181
182 def decorator(f):
183 # Instantiate the lock in decorator, in case users of memoize_one do:
184 #
185 # memoizer = memoize_one(threadsafe=True)
186 #
187 # @memoizer
188 # def fn1(val): ...
189 #
190 # @memoizer
191 # def fn2(val): ...
192
193 lock = threading.Lock() if threadsafe else None
194 cache = {}
195 _get = withlock(lock, cache.get)
196 _set = withlock(lock, cache.__setitem__)
197
198 @functools.wraps(f)
199 def inner(arg):
200 ret = _get(arg)
201 if ret is None:
202 ret = f(arg)
203 if ret is not None:
204 _set(arg, ret)
205 return ret
206 inner.get = _get
207 inner.set = _set
208 inner.clear = withlock(lock, cache.clear)
209 inner.update = withlock(lock, cache.update)
210 return inner
211 return decorator
212
213
214def _ScopedPool_initer(orig, orig_args): # pragma: no cover
215 """Initializer method for ScopedPool's subprocesses.
216
217 This helps ScopedPool handle Ctrl-C's correctly.
218 """
219 signal.signal(signal.SIGINT, signal.SIG_IGN)
220 if orig:
221 orig(*orig_args)
222
223
224@contextlib.contextmanager
225def ScopedPool(*args, **kwargs):
226 """Context Manager which returns a multiprocessing.pool instance which
227 correctly deals with thrown exceptions.
228
229 *args - Arguments to multiprocessing.pool
230
231 Kwargs:
232 kind ('threads', 'procs') - The type of underlying coprocess to use.
233 **etc - Arguments to multiprocessing.pool
234 """
235 if kwargs.pop('kind', None) == 'threads':
236 pool = multiprocessing.pool.ThreadPool(*args, **kwargs)
237 else:
238 orig, orig_args = kwargs.get('initializer'), kwargs.get('initargs', ())
239 kwargs['initializer'] = _ScopedPool_initer
240 kwargs['initargs'] = orig, orig_args
241 pool = multiprocessing.pool.Pool(*args, **kwargs)
242
243 try:
244 yield pool
245 pool.close()
246 except:
247 pool.terminate()
248 raise
249 finally:
250 pool.join()
251
252
253class ProgressPrinter(object):
254 """Threaded single-stat status message printer."""
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000255 def __init__(self, fmt, enabled=None, fout=sys.stderr, period=0.5):
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000256 """Create a ProgressPrinter.
257
258 Use it as a context manager which produces a simple 'increment' method:
259
260 with ProgressPrinter('(%%(count)d/%d)' % 1000) as inc:
261 for i in xrange(1000):
262 # do stuff
263 if i % 10 == 0:
264 inc(10)
265
266 Args:
267 fmt - String format with a single '%(count)d' where the counter value
268 should go.
269 enabled (bool) - If this is None, will default to True if
270 logging.getLogger() is set to INFO or more verbose.
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000271 fout (file-like) - The stream to print status messages to.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000272 period (float) - The time in seconds for the printer thread to wait
273 between printing.
274 """
275 self.fmt = fmt
276 if enabled is None: # pragma: no cover
277 self.enabled = logging.getLogger().isEnabledFor(logging.INFO)
278 else:
279 self.enabled = enabled
280
281 self._count = 0
282 self._dead = False
283 self._dead_cond = threading.Condition()
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000284 self._stream = fout
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000285 self._thread = threading.Thread(target=self._run)
286 self._period = period
287
288 def _emit(self, s):
289 if self.enabled:
290 self._stream.write('\r' + s)
291 self._stream.flush()
292
293 def _run(self):
294 with self._dead_cond:
295 while not self._dead:
296 self._emit(self.fmt % {'count': self._count})
297 self._dead_cond.wait(self._period)
298 self._emit((self.fmt + '\n') % {'count': self._count})
299
300 def inc(self, amount=1):
301 self._count += amount
302
303 def __enter__(self):
304 self._thread.start()
305 return self.inc
306
307 def __exit__(self, _exc_type, _exc_value, _traceback):
308 self._dead = True
309 with self._dead_cond:
310 self._dead_cond.notifyAll()
311 self._thread.join()
312 del self._thread
313
314
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000315def once(function):
316 """@Decorates |function| so that it only performs its action once, no matter
317 how many times the decorated |function| is called."""
Edward Lemur12a537f2019-10-03 21:57:15 +0000318 has_run = [False]
319 def _wrapper(*args, **kwargs):
320 if not has_run[0]:
321 has_run[0] = True
322 function(*args, **kwargs)
323 return _wrapper
324
325
326def unicode_repr(s):
327 result = repr(s)
328 return result[1:] if result.startswith('u') else result
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000329
330
331## Git functions
332
agable7aa2ddd2016-06-21 07:47:00 -0700333def die(message, *args):
Raul Tambrec2f74c12019-03-19 05:55:53 +0000334 print(textwrap.dedent(message % args), file=sys.stderr)
agable7aa2ddd2016-06-21 07:47:00 -0700335 sys.exit(1)
336
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000337
Mark Mentovaif548d082017-03-08 13:32:00 -0500338def blame(filename, revision=None, porcelain=False, abbrev=None, *_args):
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000339 command = ['blame']
340 if porcelain:
341 command.append('-p')
342 if revision is not None:
343 command.append(revision)
Mark Mentovaif548d082017-03-08 13:32:00 -0500344 if abbrev is not None:
345 command.append('--abbrev=%d' % abbrev)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000346 command.extend(['--', filename])
347 return run(*command)
348
349
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000350def branch_config(branch, option, default=None):
agable7aa2ddd2016-06-21 07:47:00 -0700351 return get_config('branch.%s.%s' % (branch, option), default=default)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000352
353
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000354def branch_config_map(option):
355 """Return {branch: <|option| value>} for all branches."""
356 try:
357 reg = re.compile(r'^branch\.(.*)\.%s$' % option)
agable7aa2ddd2016-06-21 07:47:00 -0700358 lines = get_config_regexp(reg.pattern)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000359 return {reg.match(k).group(1): v for k, v in (l.split() for l in lines)}
360 except subprocess2.CalledProcessError:
361 return {}
362
363
Francois Dorayd42c6812017-05-30 15:10:20 -0400364def branches(use_limit=True, *args):
akuegel@chromium.org58888e12015-06-09 15:26:37 +0000365 NO_BRANCH = ('* (no branch', '* (detached', '* (HEAD detached')
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000366
367 key = 'depot-tools.branch-limit'
agable7aa2ddd2016-06-21 07:47:00 -0700368 limit = get_config_int(key, 20)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000369
370 raw_branches = run('branch', *args).splitlines()
371
372 num = len(raw_branches)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000373
Francois Dorayd42c6812017-05-30 15:10:20 -0400374 if use_limit and num > limit:
agable7aa2ddd2016-06-21 07:47:00 -0700375 die("""\
376 Your git repo has too many branches (%d/%d) for this tool to work well.
377
378 You may adjust this limit by running:
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000379 git config %s <new_limit>
agable7aa2ddd2016-06-21 07:47:00 -0700380
381 You may also try cleaning up your old branches by running:
382 git cl archive
383 """, num, limit, key)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000384
385 for line in raw_branches:
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000386 if line.startswith(NO_BRANCH):
387 continue
388 yield line.split()[-1]
389
390
agable7aa2ddd2016-06-21 07:47:00 -0700391def get_config(option, default=None):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000392 try:
393 return run('config', '--get', option) or default
394 except subprocess2.CalledProcessError:
395 return default
396
397
agable7aa2ddd2016-06-21 07:47:00 -0700398def get_config_int(option, default=0):
399 assert isinstance(default, int)
400 try:
401 return int(get_config(option, default))
402 except ValueError:
403 return default
404
405
406def get_config_list(option):
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000407 try:
408 return run('config', '--get-all', option).split()
409 except subprocess2.CalledProcessError:
410 return []
411
412
agable7aa2ddd2016-06-21 07:47:00 -0700413def get_config_regexp(pattern):
414 if IS_WIN: # pragma: no cover
415 # this madness is because we call git.bat which calls git.exe which calls
416 # bash.exe (or something to that effect). Each layer divides the number of
417 # ^'s by 2.
418 pattern = pattern.replace('^', '^' * 8)
419 return run('config', '--get-regexp', pattern).splitlines()
420
421
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000422def current_branch():
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000423 try:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000424 return run('rev-parse', '--abbrev-ref', 'HEAD')
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000425 except subprocess2.CalledProcessError:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000426 return None
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000427
428
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000429def del_branch_config(branch, option, scope='local'):
430 del_config('branch.%s.%s' % (branch, option), scope=scope)
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000431
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000432
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000433def del_config(option, scope='local'):
434 try:
435 run('config', '--' + scope, '--unset', option)
436 except subprocess2.CalledProcessError:
437 pass
438
439
mgiuca@chromium.org01d2cde2016-02-05 03:25:41 +0000440def diff(oldrev, newrev, *args):
441 return run('diff', oldrev, newrev, *args)
442
443
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000444def freeze():
445 took_action = False
agable02b3c982016-06-22 07:51:22 -0700446 key = 'depot-tools.freeze-size-limit'
447 MB = 2**20
448 limit_mb = get_config_int(key, 100)
449 untracked_bytes = 0
450
iannuccieaca0332016-08-03 16:46:50 -0700451 root_path = repo_root()
452
agable02b3c982016-06-22 07:51:22 -0700453 for f, s in status():
454 if is_unmerged(s):
455 die("Cannot freeze unmerged changes!")
456 if limit_mb > 0:
457 if s.lstat == '?':
Andrew Grievefc5e1032020-04-15 18:16:08 +0000458 untracked_bytes += os.lstat(os.path.join(root_path, f)).st_size
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800459 if limit_mb > 0 and untracked_bytes > limit_mb * MB:
460 die("""\
461 You appear to have too much untracked+unignored data in your git
462 checkout: %.1f / %d MB.
agable02b3c982016-06-22 07:51:22 -0700463
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800464 Run `git status` to see what it is.
agable02b3c982016-06-22 07:51:22 -0700465
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800466 In addition to making many git commands slower, this will prevent
467 depot_tools from freezing your in-progress changes.
agable02b3c982016-06-22 07:51:22 -0700468
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800469 You should add untracked data that you want to ignore to your repo's
470 .git/info/exclude
471 file. See `git help ignore` for the format of this file.
agable02b3c982016-06-22 07:51:22 -0700472
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000473 If this data is intended as part of your commit, you may adjust the
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800474 freeze limit by running:
475 git config %s <new_limit>
476 Where <new_limit> is an integer threshold in megabytes.""",
477 untracked_bytes / (MB * 1.0), limit_mb, key)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000478
479 try:
iannucci@chromium.org3b4f2282015-09-17 15:46:00 +0000480 run('commit', '--no-verify', '-m', FREEZE + '.indexed')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000481 took_action = True
482 except subprocess2.CalledProcessError:
483 pass
484
agable96e179b2016-06-24 10:32:51 -0700485 add_errors = False
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000486 try:
agable96e179b2016-06-24 10:32:51 -0700487 run('add', '-A', '--ignore-errors')
488 except subprocess2.CalledProcessError:
489 add_errors = True
490
491 try:
iannucci@chromium.org3b4f2282015-09-17 15:46:00 +0000492 run('commit', '--no-verify', '-m', FREEZE + '.unindexed')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000493 took_action = True
494 except subprocess2.CalledProcessError:
495 pass
496
agable96e179b2016-06-24 10:32:51 -0700497 ret = []
498 if add_errors:
499 ret.append('Failed to index some unindexed files.')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000500 if not took_action:
agable96e179b2016-06-24 10:32:51 -0700501 ret.append('Nothing to freeze.')
502 return ' '.join(ret) or None
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000503
504
505def get_branch_tree():
506 """Get the dictionary of {branch: parent}, compatible with topo_iter.
507
508 Returns a tuple of (skipped, <branch_tree dict>) where skipped is a set of
509 branches without upstream branches defined.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000510 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000511 skipped = set()
512 branch_tree = {}
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000513
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000514 for branch in branches():
515 parent = upstream(branch)
516 if not parent:
517 skipped.add(branch)
518 continue
519 branch_tree[branch] = parent
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000520
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000521 return skipped, branch_tree
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000522
523
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000524def get_or_create_merge_base(branch, parent=None):
525 """Finds the configured merge base for branch.
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000526
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000527 If parent is supplied, it's used instead of calling upstream(branch).
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000528 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000529 base = branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000530 base_upstream = branch_config(branch, 'base-upstream')
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000531 parent = parent or upstream(branch)
sbc@chromium.org79706062015-01-14 21:18:12 +0000532 if parent is None or branch is None:
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000533 return None
Josip Sokcevica3d1aaf2021-07-16 18:26:45 +0000534 actual_merge_base = run('merge-base', parent, branch)
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000535
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000536 if base_upstream != parent:
537 base = None
538 base_upstream = None
539
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000540 def is_ancestor(a, b):
541 return run_with_retcode('merge-base', '--is-ancestor', a, b) == 0
542
clemensh@chromium.orgc3fe99d2016-04-19 08:39:55 +0000543 if base and base != actual_merge_base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000544 if not is_ancestor(base, branch):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000545 logging.debug('Found WRONG pre-set merge-base for %s: %s', branch, base)
546 base = None
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000547 elif is_ancestor(base, actual_merge_base):
548 logging.debug('Found OLD pre-set merge-base for %s: %s', branch, base)
549 base = None
550 else:
551 logging.debug('Found pre-set merge-base for %s: %s', branch, base)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000552
553 if not base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000554 base = actual_merge_base
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000555 manual_merge_base(branch, base, parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000556
557 return base
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000558
559
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000560def hash_multi(*reflike):
561 return run('rev-parse', *reflike).splitlines()
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000562
563
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000564def hash_one(reflike, short=False):
565 args = ['rev-parse', reflike]
566 if short:
567 args.insert(1, '--short')
568 return run(*args)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000569
570
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000571def in_rebase():
572 git_dir = run('rev-parse', '--git-dir')
573 return (
574 os.path.exists(os.path.join(git_dir, 'rebase-merge')) or
575 os.path.exists(os.path.join(git_dir, 'rebase-apply')))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000576
577
578def intern_f(f, kind='blob'):
579 """Interns a file object into the git object store.
580
581 Args:
582 f (file-like object) - The file-like object to intern
583 kind (git object type) - One of 'blob', 'commit', 'tree', 'tag'.
584
585 Returns the git hash of the interned object (hex encoded).
586 """
587 ret = run('hash-object', '-t', kind, '-w', '--stdin', stdin=f)
588 f.close()
589 return ret
590
591
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000592def is_dormant(branch):
593 # TODO(iannucci): Do an oldness check?
594 return branch_config(branch, 'dormant', 'false') != 'false'
595
596
agable02b3c982016-06-22 07:51:22 -0700597def is_unmerged(stat_value):
598 return (
599 'U' in (stat_value.lstat, stat_value.rstat) or
600 ((stat_value.lstat == stat_value.rstat) and stat_value.lstat in 'AD')
601 )
602
603
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000604def manual_merge_base(branch, base, parent):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000605 set_branch_config(branch, 'base', base)
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000606 set_branch_config(branch, 'base-upstream', parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000607
608
609def mktree(treedict):
610 """Makes a git tree object and returns its hash.
611
612 See |tree()| for the values of mode, type, and ref.
613
614 Args:
615 treedict - { name: (mode, type, ref) }
616 """
617 with tempfile.TemporaryFile() as f:
Edward Lemur12a537f2019-10-03 21:57:15 +0000618 for name, (mode, typ, ref) in treedict.items():
Edward Lemur71681bf2019-10-09 23:46:20 +0000619 f.write(('%s %s %s\t%s\0' % (mode, typ, ref, name)).encode('utf-8'))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000620 f.seek(0)
621 return run('mktree', '-z', stdin=f)
622
623
624def parse_commitrefs(*commitrefs):
625 """Returns binary encoded commit hashes for one or more commitrefs.
626
627 A commitref is anything which can resolve to a commit. Popular examples:
628 * 'HEAD'
Josip Sokcevic9c0dc302020-11-20 18:41:25 +0000629 * 'origin/main'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000630 * 'cool_branch~2'
631 """
632 try:
Edward Lemur12a537f2019-10-03 21:57:15 +0000633 return [binascii.unhexlify(h) for h in hash_multi(*commitrefs)]
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000634 except subprocess2.CalledProcessError:
635 raise BadCommitRefException(commitrefs)
636
637
sbc@chromium.org384039b2014-10-13 21:01:00 +0000638RebaseRet = collections.namedtuple('RebaseRet', 'success stdout stderr')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000639
640
Robert Iannuccid3acb162021-05-04 21:37:40 +0000641def rebase(parent, start, branch, abort=False, allow_gc=False):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000642 """Rebases |start|..|branch| onto the branch |parent|.
643
Robert Iannuccid3acb162021-05-04 21:37:40 +0000644 Sets 'gc.auto=0' for the duration of this call to prevent the rebase from
645 running a potentially slow garbage collection cycle.
646
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000647 Args:
648 parent - The new parent ref for the rebased commits.
649 start - The commit to start from
650 branch - The branch to rebase
651 abort - If True, will call git-rebase --abort in the event that the rebase
652 doesn't complete successfully.
Robert Iannuccid3acb162021-05-04 21:37:40 +0000653 allow_gc - If True, sets "-c gc.auto=1" on the rebase call, rather than
654 "-c gc.auto=0". Usually if you're doing a series of rebases,
655 you'll only want to run a single gc pass at the end of all the
656 rebase activity.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000657
658 Returns a namedtuple with fields:
659 success - a boolean indicating that the rebase command completed
660 successfully.
661 message - if the rebase failed, this contains the stdout of the failed
662 rebase.
663 """
664 try:
Robert Iannuccid3acb162021-05-04 21:37:40 +0000665 args = [
666 '-c', 'gc.auto={}'.format('1' if allow_gc else '0'),
667 'rebase',
668 ]
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000669 if TEST_MODE:
Robert Iannuccid3acb162021-05-04 21:37:40 +0000670 args.append('--committer-date-is-author-date')
671 args += [
672 '--onto', parent, start, branch,
673 ]
674 run(*args)
sbc@chromium.org384039b2014-10-13 21:01:00 +0000675 return RebaseRet(True, '', '')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000676 except subprocess2.CalledProcessError as cpe:
677 if abort:
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000678 run_with_retcode('rebase', '--abort') # ignore failure
Josip Sokcevic72f991f2020-04-23 18:53:30 +0000679 return RebaseRet(False, cpe.stdout.decode('utf-8', 'replace'),
680 cpe.stderr.decode('utf-8', 'replace'))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000681
682
683def remove_merge_base(branch):
684 del_branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000685 del_branch_config(branch, 'base-upstream')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000686
687
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000688def repo_root():
689 """Returns the absolute path to the repository root."""
690 return run('rev-parse', '--show-toplevel')
691
692
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000693def upstream_default():
694 """Returns the default branch name of the origin repository."""
695 try:
Josip Sokcevic06423732021-03-31 19:04:42 +0000696 ret = run('rev-parse', '--abbrev-ref', 'origin/HEAD')
697 # Detect if the repository migrated to main branch
698 if ret == 'origin/master':
699 try:
700 ret = run('rev-parse', '--abbrev-ref', 'origin/main')
701 run('remote', 'set-head', '-a', 'origin')
702 ret = run('rev-parse', '--abbrev-ref', 'origin/HEAD')
703 except subprocess2.CalledProcessError:
704 pass
705 return ret
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000706 except subprocess2.CalledProcessError:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +0000707 return 'origin/main'
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000708
709
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000710def root():
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000711 return get_config('depot-tools.upstream', upstream_default())
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000712
713
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000714@contextlib.contextmanager
715def less(): # pragma: no cover
716 """Runs 'less' as context manager yielding its stdin as a PIPE.
717
718 Automatically checks if sys.stdout is a non-TTY stream. If so, it avoids
719 running less and just yields sys.stdout.
Edward Lemur0d462e92020-01-08 20:11:31 +0000720
721 The returned PIPE is opened on binary mode.
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000722 """
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +0000723 if not setup_color.IS_TTY:
Edward Lemur5e94b802019-11-26 21:44:08 +0000724 # On Python 3, sys.stdout doesn't accept bytes, and sys.stdout.buffer must
725 # be used.
726 yield getattr(sys.stdout, 'buffer', sys.stdout)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000727 return
728
729 # Run with the same options that git uses (see setup_pager in git repo).
730 # -F: Automatically quit if the output is less than one screen.
731 # -R: Don't escape ANSI color codes.
732 # -X: Don't clear the screen before starting.
733 cmd = ('less', '-FRX')
734 try:
735 proc = subprocess2.Popen(cmd, stdin=subprocess2.PIPE)
736 yield proc.stdin
737 finally:
Edward Lemurb800fde2020-01-10 23:04:44 +0000738 try:
739 proc.stdin.close()
740 except BrokenPipeError:
741 # BrokenPipeError is raised if proc has already completed,
742 pass
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000743 proc.wait()
744
745
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000746def run(*cmd, **kwargs):
747 """The same as run_with_stderr, except it only returns stdout."""
748 return run_with_stderr(*cmd, **kwargs)[0]
749
750
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000751def run_with_retcode(*cmd, **kwargs):
752 """Run a command but only return the status code."""
753 try:
754 run(*cmd, **kwargs)
755 return 0
756 except subprocess2.CalledProcessError as cpe:
757 return cpe.returncode
758
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000759def run_stream(*cmd, **kwargs):
760 """Runs a git command. Returns stdout as a PIPE (file-like object).
761
762 stderr is dropped to avoid races if the process outputs to both stdout and
763 stderr.
764 """
Edward Lesmescf06cad2020-12-14 22:03:23 +0000765 kwargs.setdefault('stderr', subprocess2.DEVNULL)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000766 kwargs.setdefault('stdout', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000767 kwargs.setdefault('shell', False)
iannucci@chromium.org21980022014-04-11 04:51:49 +0000768 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000769 proc = subprocess2.Popen(cmd, **kwargs)
770 return proc.stdout
771
772
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000773@contextlib.contextmanager
774def run_stream_with_retcode(*cmd, **kwargs):
775 """Runs a git command as context manager yielding stdout as a PIPE.
776
777 stderr is dropped to avoid races if the process outputs to both stdout and
778 stderr.
779
780 Raises subprocess2.CalledProcessError on nonzero return code.
781 """
Edward Lesmescf06cad2020-12-14 22:03:23 +0000782 kwargs.setdefault('stderr', subprocess2.DEVNULL)
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000783 kwargs.setdefault('stdout', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000784 kwargs.setdefault('shell', False)
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000785 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
786 try:
787 proc = subprocess2.Popen(cmd, **kwargs)
788 yield proc.stdout
789 finally:
790 retcode = proc.wait()
791 if retcode != 0:
792 raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(),
Josip Sokcevic72f991f2020-04-23 18:53:30 +0000793 b'', b'')
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000794
795
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000796def run_with_stderr(*cmd, **kwargs):
797 """Runs a git command.
798
799 Returns (stdout, stderr) as a pair of strings.
800
801 kwargs
802 autostrip (bool) - Strip the output. Defaults to True.
803 indata (str) - Specifies stdin data for the process.
804 """
805 kwargs.setdefault('stdin', subprocess2.PIPE)
806 kwargs.setdefault('stdout', subprocess2.PIPE)
807 kwargs.setdefault('stderr', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000808 kwargs.setdefault('shell', False)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000809 autostrip = kwargs.pop('autostrip', True)
810 indata = kwargs.pop('indata', None)
Edward Lemur12a537f2019-10-03 21:57:15 +0000811 decode = kwargs.pop('decode', True)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000812
iannucci@chromium.org21980022014-04-11 04:51:49 +0000813 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000814 proc = subprocess2.Popen(cmd, **kwargs)
815 ret, err = proc.communicate(indata)
816 retcode = proc.wait()
817 if retcode != 0:
818 raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(), ret, err)
819
820 if autostrip:
Edward Lemur12a537f2019-10-03 21:57:15 +0000821 ret = (ret or b'').strip()
822 err = (err or b'').strip()
823
824 if decode:
825 ret = ret.decode('utf-8', 'replace')
826 err = err.decode('utf-8', 'replace')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000827
828 return ret, err
829
830
831def set_branch_config(branch, option, value, scope='local'):
832 set_config('branch.%s.%s' % (branch, option), value, scope=scope)
833
834
835def set_config(option, value, scope='local'):
836 run('config', '--' + scope, option, value)
837
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000838
sbc@chromium.org71437c02015-04-09 19:29:40 +0000839def get_dirty_files():
840 # Make sure index is up-to-date before running diff-index.
841 run_with_retcode('update-index', '--refresh', '-q')
Eli Ribble54434e72019-05-24 00:41:15 +0000842 return run('diff-index', '--ignore-submodules', '--name-status', 'HEAD')
sbc@chromium.org71437c02015-04-09 19:29:40 +0000843
844
845def is_dirty_git_tree(cmd):
iannuccie38699b2016-08-15 17:32:31 -0700846 w = lambda s: sys.stderr.write(s+"\n")
847
sbc@chromium.org71437c02015-04-09 19:29:40 +0000848 dirty = get_dirty_files()
849 if dirty:
Josip Sokcevicfcf9fc42022-09-27 21:59:01 +0000850 w('Cannot %s with a dirty tree. Commit%s or stash your changes first.' %
851 (cmd, '' if cmd == 'upload' else ', freeze'))
iannuccie38699b2016-08-15 17:32:31 -0700852 w('Uncommitted files: (git diff-index --name-status HEAD)')
853 w(dirty[:4096])
sbc@chromium.org71437c02015-04-09 19:29:40 +0000854 if len(dirty) > 4096: # pragma: no cover
iannuccie38699b2016-08-15 17:32:31 -0700855 w('... (run "git diff-index --name-status HEAD" to see full output).')
sbc@chromium.org71437c02015-04-09 19:29:40 +0000856 return True
857 return False
858
859
agable02b3c982016-06-22 07:51:22 -0700860def status():
861 """Returns a parsed version of git-status.
862
863 Returns a generator of (current_name, (lstat, rstat, src)) pairs where:
864 * current_name is the name of the file
865 * lstat is the left status code letter from git-status
866 * rstat is the left status code letter from git-status
867 * src is the current name of the file, or the original name of the file
868 if lstat == 'R'
869 """
870 stat_entry = collections.namedtuple('stat_entry', 'lstat rstat src')
871
872 def tokenizer(stream):
Raul Tambrec2f74c12019-03-19 05:55:53 +0000873 acc = BytesIO()
agable02b3c982016-06-22 07:51:22 -0700874 c = None
Edward Lemur12a537f2019-10-03 21:57:15 +0000875 while c != b'':
agable02b3c982016-06-22 07:51:22 -0700876 c = stream.read(1)
Edward Lemur12a537f2019-10-03 21:57:15 +0000877 if c in (None, b'', b'\0'):
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000878 if len(acc.getvalue()) > 0:
agable02b3c982016-06-22 07:51:22 -0700879 yield acc.getvalue()
Raul Tambrec2f74c12019-03-19 05:55:53 +0000880 acc = BytesIO()
agable02b3c982016-06-22 07:51:22 -0700881 else:
882 acc.write(c)
883
884 def parser(tokens):
885 while True:
Edward Lemur12a537f2019-10-03 21:57:15 +0000886 try:
887 status_dest = next(tokens).decode('utf-8')
888 except StopIteration:
889 return
agable02b3c982016-06-22 07:51:22 -0700890 stat, dest = status_dest[:2], status_dest[3:]
891 lstat, rstat = stat
892 if lstat == 'R':
Edward Lemur12a537f2019-10-03 21:57:15 +0000893 src = next(tokens).decode('utf-8')
agable02b3c982016-06-22 07:51:22 -0700894 else:
895 src = dest
896 yield (dest, stat_entry(lstat, rstat, src))
897
898 return parser(tokenizer(run_stream('status', '-z', bufsize=-1)))
899
900
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000901def squash_current_branch(header=None, merge_base=None):
Alan Cutter00017822016-12-20 17:39:59 +1100902 header = header or 'git squash commit for %s.' % current_branch()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000903 merge_base = merge_base or get_or_create_merge_base(current_branch())
904 log_msg = header + '\n'
905 if log_msg:
906 log_msg += '\n'
907 log_msg += run('log', '--reverse', '--format=%H%n%B', '%s..HEAD' % merge_base)
908 run('reset', '--soft', merge_base)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000909
910 if not get_dirty_files():
911 # Sometimes the squash can result in the same tree, meaning that there is
912 # nothing to commit at this point.
Raul Tambrec2f74c12019-03-19 05:55:53 +0000913 print('Nothing to commit; squashed branch is empty')
sbc@chromium.org71437c02015-04-09 19:29:40 +0000914 return False
Edward Lemur71681bf2019-10-09 23:46:20 +0000915 run('commit', '--no-verify', '-a', '-F', '-', indata=log_msg.encode('utf-8'))
sbc@chromium.org71437c02015-04-09 19:29:40 +0000916 return True
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000917
918
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000919def tags(*args):
920 return run('tag', *args).splitlines()
921
922
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000923def thaw():
924 took_action = False
Martin Bidlingmaier6f2321d2022-10-26 17:39:01 +0000925 for sha in run_stream('rev-list', 'HEAD'):
Edward Lemur12a537f2019-10-03 21:57:15 +0000926 sha = sha.strip().decode('utf-8')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000927 msg = run('show', '--format=%f%b', '-s', 'HEAD')
928 match = FREEZE_MATCHER.match(msg)
929 if not match:
930 if not took_action:
931 return 'Nothing to thaw.'
932 break
933
934 run('reset', '--' + FREEZE_SECTIONS[match.group(1)], sha)
935 took_action = True
936
937
938def topo_iter(branch_tree, top_down=True):
939 """Generates (branch, parent) in topographical order for a branch tree.
940
941 Given a tree:
942
943 A1
944 B1 B2
945 C1 C2 C3
946 D1
947
948 branch_tree would look like: {
949 'D1': 'C3',
950 'C3': 'B2',
951 'B2': 'A1',
952 'C1': 'B1',
953 'C2': 'B1',
954 'B1': 'A1',
955 }
956
957 It is OK to have multiple 'root' nodes in your graph.
958
959 if top_down is True, items are yielded from A->D. Otherwise they're yielded
960 from D->A. Within a layer the branches will be yielded in sorted order.
961 """
962 branch_tree = branch_tree.copy()
963
964 # TODO(iannucci): There is probably a more efficient way to do these.
965 if top_down:
966 while branch_tree:
Edward Lemur12a537f2019-10-03 21:57:15 +0000967 this_pass = [(b, p) for b, p in branch_tree.items()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000968 if p not in branch_tree]
969 assert this_pass, "Branch tree has cycles: %r" % branch_tree
970 for branch, parent in sorted(this_pass):
971 yield branch, parent
972 del branch_tree[branch]
973 else:
974 parent_to_branches = collections.defaultdict(set)
Edward Lemur12a537f2019-10-03 21:57:15 +0000975 for branch, parent in branch_tree.items():
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000976 parent_to_branches[parent].add(branch)
977
978 while branch_tree:
Edward Lemur12a537f2019-10-03 21:57:15 +0000979 this_pass = [(b, p) for b, p in branch_tree.items()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000980 if not parent_to_branches[b]]
981 assert this_pass, "Branch tree has cycles: %r" % branch_tree
982 for branch, parent in sorted(this_pass):
983 yield branch, parent
984 parent_to_branches[parent].discard(branch)
985 del branch_tree[branch]
986
987
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000988def tree(treeref, recurse=False):
989 """Returns a dict representation of a git tree object.
990
991 Args:
992 treeref (str) - a git ref which resolves to a tree (commits count as trees).
qyearsley12fa6ff2016-08-24 09:18:40 -0700993 recurse (bool) - include all of the tree's descendants too. File names will
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000994 take the form of 'some/path/to/file'.
995
996 Return format:
997 { 'file_name': (mode, type, ref) }
998
999 mode is an integer where:
1000 * 0040000 - Directory
1001 * 0100644 - Regular non-executable file
1002 * 0100664 - Regular non-executable group-writeable file
1003 * 0100755 - Regular executable file
1004 * 0120000 - Symbolic link
1005 * 0160000 - Gitlink
1006
1007 type is a string where it's one of 'blob', 'commit', 'tree', 'tag'.
1008
1009 ref is the hex encoded hash of the entry.
1010 """
1011 ret = {}
1012 opts = ['ls-tree', '--full-tree']
1013 if recurse:
1014 opts.append('-r')
1015 opts.append(treeref)
1016 try:
1017 for line in run(*opts).splitlines():
1018 mode, typ, ref, name = line.split(None, 3)
1019 ret[name] = (mode, typ, ref)
1020 except subprocess2.CalledProcessError:
1021 return None
1022 return ret
1023
1024
Mun Yong Jang781e71e2017-10-25 15:46:20 -07001025def get_remote_url(remote='origin'):
1026 try:
1027 return run('config', 'remote.%s.url' % remote)
1028 except subprocess2.CalledProcessError:
1029 return None
1030
1031
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +00001032def upstream(branch):
1033 try:
1034 return run('rev-parse', '--abbrev-ref', '--symbolic-full-name',
1035 branch+'@{upstream}')
1036 except subprocess2.CalledProcessError:
1037 return None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001038
agable@chromium.orgd629fb42014-10-01 09:40:10 +00001039
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001040def get_git_version():
1041 """Returns a tuple that contains the numeric components of the current git
1042 version."""
1043 version_string = run('--version')
1044 version_match = re.search(r'(\d+.)+(\d+)', version_string)
1045 version = version_match.group() if version_match else ''
1046
1047 return tuple(int(x) for x in version.split('.'))
1048
1049
calamity@chromium.org745ffa62014-09-08 01:03:19 +00001050def get_branches_info(include_tracking_status):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001051 format_string = (
1052 '--format=%(refname:short):%(objectname:short):%(upstream:short):')
1053
1054 # This is not covered by the depot_tools CQ which only has git version 1.8.
calamity@chromium.org745ffa62014-09-08 01:03:19 +00001055 if (include_tracking_status and
1056 get_git_version() >= MIN_UPSTREAM_TRACK_GIT_VERSION): # pragma: no cover
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001057 format_string += '%(upstream:track)'
1058
1059 info_map = {}
1060 data = run('for-each-ref', format_string, 'refs/heads')
calamity@chromium.org745ffa62014-09-08 01:03:19 +00001061 BranchesInfo = collections.namedtuple(
Gavin Mak8d7201b2020-09-17 19:21:38 +00001062 'BranchesInfo', 'hash upstream commits behind')
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001063 for line in data.splitlines():
1064 (branch, branch_hash, upstream_branch, tracking_status) = line.split(':')
1065
Gavin Mak8d7201b2020-09-17 19:21:38 +00001066 commits = None
Antonio Sartorie0dff202021-02-18 06:33:50 +00001067 if include_tracking_status:
1068 base = get_or_create_merge_base(branch)
1069 if base:
1070 commits_list = run('rev-list', '--count', branch, '^%s' % base, '--')
1071 commits = int(commits_list) or None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001072
1073 behind_match = re.search(r'behind (\d+)', tracking_status)
1074 behind = int(behind_match.group(1)) if behind_match else None
1075
calamity@chromium.org745ffa62014-09-08 01:03:19 +00001076 info_map[branch] = BranchesInfo(
Robert Iannuccid3acb162021-05-04 21:37:40 +00001077 hash=branch_hash, upstream=upstream_branch, commits=commits,
Gavin Mak8d7201b2020-09-17 19:21:38 +00001078 behind=behind)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001079
1080 # Set None for upstreams which are not branches (e.g empty upstream, remotes
1081 # and deleted upstream branches).
1082 missing_upstreams = {}
1083 for info in info_map.values():
1084 if info.upstream not in info_map and info.upstream not in missing_upstreams:
1085 missing_upstreams[info.upstream] = None
1086
Edward Lemur12a537f2019-10-03 21:57:15 +00001087 result = info_map.copy()
1088 result.update(missing_upstreams)
1089 return result
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001090
1091
1092def make_workdir_common(repository, new_workdir, files_to_symlink,
scottmg@chromium.orgd4218d42015-10-07 23:49:20 +00001093 files_to_copy, symlink=None):
1094 if not symlink:
1095 symlink = os.symlink
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001096 os.makedirs(new_workdir)
1097 for entry in files_to_symlink:
scottmg@chromium.orgd4218d42015-10-07 23:49:20 +00001098 clone_file(repository, new_workdir, entry, symlink)
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001099 for entry in files_to_copy:
1100 clone_file(repository, new_workdir, entry, shutil.copy)
1101
1102
1103def make_workdir(repository, new_workdir):
1104 GIT_DIRECTORY_WHITELIST = [
1105 'config',
1106 'info',
1107 'hooks',
1108 'logs/refs',
1109 'objects',
1110 'packed-refs',
1111 'refs',
1112 'remotes',
1113 'rr-cache',
Richard He42033b22020-05-22 03:03:45 +00001114 'shallow',
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001115 ]
1116 make_workdir_common(repository, new_workdir, GIT_DIRECTORY_WHITELIST,
1117 ['HEAD'])
1118
1119
1120def clone_file(repository, new_workdir, link, operation):
1121 if not os.path.exists(os.path.join(repository, link)):
1122 return
1123 link_dir = os.path.dirname(os.path.join(new_workdir, link))
1124 if not os.path.exists(link_dir):
1125 os.makedirs(link_dir)
Henrique Ferreirofd4ad242018-01-10 12:19:18 +01001126 src = os.path.join(repository, link)
1127 if os.path.islink(src):
Henrique Ferreiroaea45d22018-02-19 09:48:36 +01001128 src = os.path.realpath(src)
Henrique Ferreirofd4ad242018-01-10 12:19:18 +01001129 operation(src, os.path.join(new_workdir, link))