blob: 8ba938dba3499cad46afea15ff1aa8fd45024640 [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
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +00008import multiprocessing.pool
Josip Sokcevicde6c4562020-03-26 00:39:42 +00009import sys
10import threading
11
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000012from multiprocessing.pool import IMapIterator
Josip Sokcevicde6c4562020-03-26 00:39:42 +000013
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000014def wrapper(func):
15 def wrap(self, timeout=None):
Gavin Makb5c7f4b2023-08-24 18:35:41 +000016 return func(self, timeout=timeout or threading.TIMEOUT_MAX)
Josip Sokcevicde6c4562020-03-26 00:39:42 +000017
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000018 return wrap
19IMapIterator.next = wrapper(IMapIterator.next)
20IMapIterator.__next__ = IMapIterator.next
21# TODO(iannucci): Monkeypatch all other 'wait' methods too.
22
23
24import binascii
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000025import collections
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000026import contextlib
27import functools
28import logging
iannucci@chromium.org97345eb2014-03-13 07:55:15 +000029import os
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000030import re
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +000031import setup_color
sammc@chromium.org900a33f2015-09-29 06:57:09 +000032import shutil
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000033import signal
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000034import tempfile
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +000035import textwrap
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000036
37import subprocess2
38
Raul Tambrec2f74c12019-03-19 05:55:53 +000039from io import BytesIO
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000040
agable02b3c982016-06-22 07:51:22 -070041
42ROOT = os.path.abspath(os.path.dirname(__file__))
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +000043IS_WIN = sys.platform == 'win32'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000044TEST_MODE = False
45
Dan Jacques209a6812017-07-12 11:40:20 -070046
47def win_find_git():
48 for elem in os.environ.get('PATH', '').split(os.pathsep):
49 for candidate in ('git.exe', 'git.bat'):
50 path = os.path.join(elem, candidate)
51 if os.path.isfile(path):
52 return path
53 raise ValueError('Could not find Git on PATH.')
54
55
56GIT_EXE = 'git' if not IS_WIN else win_find_git()
57
58
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000059FREEZE = 'FREEZE'
60FREEZE_SECTIONS = {
61 'indexed': 'soft',
62 'unindexed': 'mixed'
63}
64FREEZE_MATCHER = re.compile(r'%s.(%s)' % (FREEZE, '|'.join(FREEZE_SECTIONS)))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000065
66
Dan Jacques2f8b0c12017-04-05 12:57:21 -070067# NOTE: This list is DEPRECATED in favor of the Infra Git wrapper:
Josip Sokcevic9c0dc302020-11-20 18:41:25 +000068# https://chromium.googlesource.com/infra/infra/+/HEAD/go/src/infra/tools/git
Dan Jacques2f8b0c12017-04-05 12:57:21 -070069#
70# New entries should be added to the Git wrapper, NOT to this list. "git_retry"
71# is, similarly, being deprecated in favor of the Git wrapper.
72#
73# ---
74#
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000075# Retry a git operation if git returns a error response with any of these
76# messages. It's all observed 'bad' GoB responses so far.
77#
78# This list is inspired/derived from the one in ChromiumOS's Chromite:
79# <CHROMITE>/lib/git.py::GIT_TRANSIENT_ERRORS
80#
81# It was last imported from '7add3ac29564d98ac35ce426bc295e743e7c0c02'.
82GIT_TRANSIENT_ERRORS = (
83 # crbug.com/285832
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000084 r'!.*\[remote rejected\].*\(error in hook\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000085
86 # crbug.com/289932
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000087 r'!.*\[remote rejected\].*\(failed to lock\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000088
89 # crbug.com/307156
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000090 r'!.*\[remote rejected\].*\(error in Gerrit backend\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000091
92 # crbug.com/285832
93 r'remote error: Internal Server Error',
94
95 # crbug.com/294449
96 r'fatal: Couldn\'t find remote ref ',
97
98 # crbug.com/220543
99 r'git fetch_pack: expected ACK/NAK, got',
100
101 # crbug.com/189455
102 r'protocol error: bad pack header',
103
104 # crbug.com/202807
105 r'The remote end hung up unexpectedly',
106
107 # crbug.com/298189
108 r'TLS packet with unexpected length was received',
109
110 # crbug.com/187444
111 r'RPC failed; result=\d+, HTTP code = \d+',
112
dnj@chromium.orgde219ec2014-07-28 17:39:08 +0000113 # crbug.com/388876
114 r'Connection timed out',
dnj@chromium.org45cddd62014-11-06 19:36:42 +0000115
116 # crbug.com/430343
117 # TODO(dnj): Resync with Chromite.
118 r'The requested URL returned error: 5\d+',
Arikonb3a21482016-07-22 10:12:24 -0700119
120 r'Connection reset by peer',
121
122 r'Unable to look up',
123
124 r'Couldn\'t resolve host',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +0000125)
126
127GIT_TRANSIENT_ERRORS_RE = re.compile('|'.join(GIT_TRANSIENT_ERRORS),
128 re.IGNORECASE)
129
raphael.kubo.da.costa@intel.com58d05b02015-06-24 08:54:41 +0000130# git's for-each-ref command first supported the upstream:track token in its
131# format string in version 1.9.0, but some usages were broken until 2.3.0.
132# See git commit b6160d95 for more information.
133MIN_UPSTREAM_TRACK_GIT_VERSION = (2, 3)
dnj@chromium.orgde219ec2014-07-28 17:39:08 +0000134
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000135class BadCommitRefException(Exception):
136 def __init__(self, refs):
137 msg = ('one of %s does not seem to be a valid commitref.' %
138 str(refs))
139 super(BadCommitRefException, self).__init__(msg)
140
141
142def memoize_one(**kwargs):
143 """Memoizes a single-argument pure function.
144
145 Values of None are not cached.
146
147 Kwargs:
148 threadsafe (bool) - REQUIRED. Specifies whether to use locking around
149 cache manipulation functions. This is a kwarg so that users of memoize_one
150 are forced to explicitly and verbosely pick True or False.
151
152 Adds three methods to the decorated function:
153 * get(key, default=None) - Gets the value for this key from the cache.
154 * set(key, value) - Sets the value for this key from the cache.
155 * clear() - Drops the entire contents of the cache. Useful for unittests.
156 * update(other) - Updates the contents of the cache from another dict.
157 """
158 assert 'threadsafe' in kwargs, 'Must specify threadsafe={True,False}'
159 threadsafe = kwargs['threadsafe']
160
161 if threadsafe:
162 def withlock(lock, f):
163 def inner(*args, **kwargs):
164 with lock:
165 return f(*args, **kwargs)
166 return inner
167 else:
168 def withlock(_lock, f):
169 return f
170
171 def decorator(f):
172 # Instantiate the lock in decorator, in case users of memoize_one do:
173 #
174 # memoizer = memoize_one(threadsafe=True)
175 #
176 # @memoizer
177 # def fn1(val): ...
178 #
179 # @memoizer
180 # def fn2(val): ...
181
182 lock = threading.Lock() if threadsafe else None
183 cache = {}
184 _get = withlock(lock, cache.get)
185 _set = withlock(lock, cache.__setitem__)
186
187 @functools.wraps(f)
188 def inner(arg):
189 ret = _get(arg)
190 if ret is None:
191 ret = f(arg)
192 if ret is not None:
193 _set(arg, ret)
194 return ret
195 inner.get = _get
196 inner.set = _set
197 inner.clear = withlock(lock, cache.clear)
198 inner.update = withlock(lock, cache.update)
199 return inner
200 return decorator
201
202
203def _ScopedPool_initer(orig, orig_args): # pragma: no cover
204 """Initializer method for ScopedPool's subprocesses.
205
206 This helps ScopedPool handle Ctrl-C's correctly.
207 """
208 signal.signal(signal.SIGINT, signal.SIG_IGN)
209 if orig:
210 orig(*orig_args)
211
212
213@contextlib.contextmanager
214def ScopedPool(*args, **kwargs):
215 """Context Manager which returns a multiprocessing.pool instance which
216 correctly deals with thrown exceptions.
217
218 *args - Arguments to multiprocessing.pool
219
220 Kwargs:
221 kind ('threads', 'procs') - The type of underlying coprocess to use.
222 **etc - Arguments to multiprocessing.pool
223 """
224 if kwargs.pop('kind', None) == 'threads':
225 pool = multiprocessing.pool.ThreadPool(*args, **kwargs)
226 else:
227 orig, orig_args = kwargs.get('initializer'), kwargs.get('initargs', ())
228 kwargs['initializer'] = _ScopedPool_initer
229 kwargs['initargs'] = orig, orig_args
230 pool = multiprocessing.pool.Pool(*args, **kwargs)
231
232 try:
233 yield pool
234 pool.close()
235 except:
236 pool.terminate()
237 raise
238 finally:
239 pool.join()
240
241
242class ProgressPrinter(object):
243 """Threaded single-stat status message printer."""
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000244 def __init__(self, fmt, enabled=None, fout=sys.stderr, period=0.5):
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000245 """Create a ProgressPrinter.
246
247 Use it as a context manager which produces a simple 'increment' method:
248
249 with ProgressPrinter('(%%(count)d/%d)' % 1000) as inc:
250 for i in xrange(1000):
251 # do stuff
252 if i % 10 == 0:
253 inc(10)
254
255 Args:
256 fmt - String format with a single '%(count)d' where the counter value
257 should go.
258 enabled (bool) - If this is None, will default to True if
259 logging.getLogger() is set to INFO or more verbose.
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000260 fout (file-like) - The stream to print status messages to.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000261 period (float) - The time in seconds for the printer thread to wait
262 between printing.
263 """
264 self.fmt = fmt
265 if enabled is None: # pragma: no cover
266 self.enabled = logging.getLogger().isEnabledFor(logging.INFO)
267 else:
268 self.enabled = enabled
269
270 self._count = 0
271 self._dead = False
272 self._dead_cond = threading.Condition()
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000273 self._stream = fout
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000274 self._thread = threading.Thread(target=self._run)
275 self._period = period
276
277 def _emit(self, s):
278 if self.enabled:
279 self._stream.write('\r' + s)
280 self._stream.flush()
281
282 def _run(self):
283 with self._dead_cond:
284 while not self._dead:
285 self._emit(self.fmt % {'count': self._count})
286 self._dead_cond.wait(self._period)
287 self._emit((self.fmt + '\n') % {'count': self._count})
288
289 def inc(self, amount=1):
290 self._count += amount
291
292 def __enter__(self):
293 self._thread.start()
294 return self.inc
295
296 def __exit__(self, _exc_type, _exc_value, _traceback):
297 self._dead = True
298 with self._dead_cond:
299 self._dead_cond.notifyAll()
300 self._thread.join()
301 del self._thread
302
303
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000304def once(function):
305 """@Decorates |function| so that it only performs its action once, no matter
306 how many times the decorated |function| is called."""
Edward Lemur12a537f2019-10-03 21:57:15 +0000307 has_run = [False]
308 def _wrapper(*args, **kwargs):
309 if not has_run[0]:
310 has_run[0] = True
311 function(*args, **kwargs)
312 return _wrapper
313
314
315def unicode_repr(s):
316 result = repr(s)
317 return result[1:] if result.startswith('u') else result
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000318
319
320## Git functions
321
agable7aa2ddd2016-06-21 07:47:00 -0700322def die(message, *args):
Raul Tambrec2f74c12019-03-19 05:55:53 +0000323 print(textwrap.dedent(message % args), file=sys.stderr)
agable7aa2ddd2016-06-21 07:47:00 -0700324 sys.exit(1)
325
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000326
Mark Mentovaif548d082017-03-08 13:32:00 -0500327def blame(filename, revision=None, porcelain=False, abbrev=None, *_args):
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000328 command = ['blame']
329 if porcelain:
330 command.append('-p')
331 if revision is not None:
332 command.append(revision)
Mark Mentovaif548d082017-03-08 13:32:00 -0500333 if abbrev is not None:
334 command.append('--abbrev=%d' % abbrev)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000335 command.extend(['--', filename])
336 return run(*command)
337
338
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000339def branch_config(branch, option, default=None):
agable7aa2ddd2016-06-21 07:47:00 -0700340 return get_config('branch.%s.%s' % (branch, option), default=default)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000341
342
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000343def branch_config_map(option):
344 """Return {branch: <|option| value>} for all branches."""
345 try:
346 reg = re.compile(r'^branch\.(.*)\.%s$' % option)
agable7aa2ddd2016-06-21 07:47:00 -0700347 lines = get_config_regexp(reg.pattern)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000348 return {reg.match(k).group(1): v for k, v in (l.split() for l in lines)}
349 except subprocess2.CalledProcessError:
350 return {}
351
352
Francois Dorayd42c6812017-05-30 15:10:20 -0400353def branches(use_limit=True, *args):
akuegel@chromium.org58888e12015-06-09 15:26:37 +0000354 NO_BRANCH = ('* (no branch', '* (detached', '* (HEAD detached')
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000355
356 key = 'depot-tools.branch-limit'
agable7aa2ddd2016-06-21 07:47:00 -0700357 limit = get_config_int(key, 20)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000358
359 raw_branches = run('branch', *args).splitlines()
360
361 num = len(raw_branches)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000362
Francois Dorayd42c6812017-05-30 15:10:20 -0400363 if use_limit and num > limit:
agable7aa2ddd2016-06-21 07:47:00 -0700364 die("""\
365 Your git repo has too many branches (%d/%d) for this tool to work well.
366
367 You may adjust this limit by running:
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000368 git config %s <new_limit>
agable7aa2ddd2016-06-21 07:47:00 -0700369
370 You may also try cleaning up your old branches by running:
371 git cl archive
372 """, num, limit, key)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000373
374 for line in raw_branches:
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000375 if line.startswith(NO_BRANCH):
376 continue
377 yield line.split()[-1]
378
379
agable7aa2ddd2016-06-21 07:47:00 -0700380def get_config(option, default=None):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000381 try:
382 return run('config', '--get', option) or default
383 except subprocess2.CalledProcessError:
384 return default
385
386
agable7aa2ddd2016-06-21 07:47:00 -0700387def get_config_int(option, default=0):
388 assert isinstance(default, int)
389 try:
390 return int(get_config(option, default))
391 except ValueError:
392 return default
393
394
395def get_config_list(option):
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000396 try:
397 return run('config', '--get-all', option).split()
398 except subprocess2.CalledProcessError:
399 return []
400
401
agable7aa2ddd2016-06-21 07:47:00 -0700402def get_config_regexp(pattern):
403 if IS_WIN: # pragma: no cover
404 # this madness is because we call git.bat which calls git.exe which calls
405 # bash.exe (or something to that effect). Each layer divides the number of
406 # ^'s by 2.
407 pattern = pattern.replace('^', '^' * 8)
408 return run('config', '--get-regexp', pattern).splitlines()
409
410
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000411def current_branch():
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000412 try:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000413 return run('rev-parse', '--abbrev-ref', 'HEAD')
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000414 except subprocess2.CalledProcessError:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000415 return None
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000416
417
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000418def del_branch_config(branch, option, scope='local'):
419 del_config('branch.%s.%s' % (branch, option), scope=scope)
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000420
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000421
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000422def del_config(option, scope='local'):
423 try:
424 run('config', '--' + scope, '--unset', option)
425 except subprocess2.CalledProcessError:
426 pass
427
428
mgiuca@chromium.org01d2cde2016-02-05 03:25:41 +0000429def diff(oldrev, newrev, *args):
430 return run('diff', oldrev, newrev, *args)
431
432
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000433def freeze():
434 took_action = False
agable02b3c982016-06-22 07:51:22 -0700435 key = 'depot-tools.freeze-size-limit'
436 MB = 2**20
437 limit_mb = get_config_int(key, 100)
438 untracked_bytes = 0
439
iannuccieaca0332016-08-03 16:46:50 -0700440 root_path = repo_root()
441
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000442 # unindexed tracks all the files which are unindexed but we want to add to
443 # the `FREEZE.unindexed` commit.
444 unindexed = []
445
446 # will be set to true if there are any indexed files to commit.
447 have_indexed_files = False
448
Joanna Wang25410062023-08-10 23:28:44 +0000449 for f, s in status(ignore_submodules='all'):
agable02b3c982016-06-22 07:51:22 -0700450 if is_unmerged(s):
451 die("Cannot freeze unmerged changes!")
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000452 if s.lstat not in ' ?':
453 # This covers all changes to indexed files.
454 # lstat = ' ' means that the file is tracked and modified, but wasn't
455 # added yet.
456 # lstat = '?' means that the file is untracked.
457 have_indexed_files = True
458 else:
459 unindexed.append(f.encode('utf-8'))
460 if s.lstat == '?' and limit_mb > 0:
461 untracked_bytes += os.lstat(os.path.join(root_path, f)).st_size
462
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800463 if limit_mb > 0 and untracked_bytes > limit_mb * MB:
464 die("""\
465 You appear to have too much untracked+unignored data in your git
466 checkout: %.1f / %d MB.
agable02b3c982016-06-22 07:51:22 -0700467
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800468 Run `git status` to see what it is.
agable02b3c982016-06-22 07:51:22 -0700469
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800470 In addition to making many git commands slower, this will prevent
471 depot_tools from freezing your in-progress changes.
agable02b3c982016-06-22 07:51:22 -0700472
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800473 You should add untracked data that you want to ignore to your repo's
474 .git/info/exclude
475 file. See `git help ignore` for the format of this file.
agable02b3c982016-06-22 07:51:22 -0700476
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000477 If this data is intended as part of your commit, you may adjust the
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800478 freeze limit by running:
479 git config %s <new_limit>
480 Where <new_limit> is an integer threshold in megabytes.""",
481 untracked_bytes / (MB * 1.0), limit_mb, key)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000482
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000483 if have_indexed_files:
484 try:
485 run('commit', '--no-verify', '-m', f'{FREEZE}.indexed')
486 took_action = True
487 except subprocess2.CalledProcessError:
488 pass
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000489
agable96e179b2016-06-24 10:32:51 -0700490 add_errors = False
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000491 if unindexed:
492 try:
493 run('add',
494 '--pathspec-from-file',
495 '-',
496 '--ignore-errors',
Robert Iannucci2f0147a2023-07-20 16:41:59 +0000497 indata=b'\n'.join(unindexed),
498 cwd=root_path)
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000499 except subprocess2.CalledProcessError:
500 add_errors = True
agable96e179b2016-06-24 10:32:51 -0700501
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000502 try:
503 run('commit', '--no-verify', '-m', f'{FREEZE}.unindexed')
504 took_action = True
505 except subprocess2.CalledProcessError:
506 pass
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000507
agable96e179b2016-06-24 10:32:51 -0700508 ret = []
509 if add_errors:
510 ret.append('Failed to index some unindexed files.')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000511 if not took_action:
agable96e179b2016-06-24 10:32:51 -0700512 ret.append('Nothing to freeze.')
513 return ' '.join(ret) or None
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000514
515
Gavin Mak2cbe95c2023-03-06 22:39:56 +0000516def get_branch_tree(use_limit=False):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000517 """Get the dictionary of {branch: parent}, compatible with topo_iter.
518
519 Returns a tuple of (skipped, <branch_tree dict>) where skipped is a set of
520 branches without upstream branches defined.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000521 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000522 skipped = set()
523 branch_tree = {}
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000524
Gavin Mak2cbe95c2023-03-06 22:39:56 +0000525 for branch in branches(use_limit=use_limit):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000526 parent = upstream(branch)
527 if not parent:
528 skipped.add(branch)
529 continue
530 branch_tree[branch] = parent
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000531
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000532 return skipped, branch_tree
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000533
534
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000535def get_or_create_merge_base(branch, parent=None):
536 """Finds the configured merge base for branch.
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000537
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000538 If parent is supplied, it's used instead of calling upstream(branch).
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000539 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000540 base = branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000541 base_upstream = branch_config(branch, 'base-upstream')
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000542 parent = parent or upstream(branch)
sbc@chromium.org79706062015-01-14 21:18:12 +0000543 if parent is None or branch is None:
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000544 return None
Josip Sokcevica3d1aaf2021-07-16 18:26:45 +0000545 actual_merge_base = run('merge-base', parent, branch)
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000546
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000547 if base_upstream != parent:
548 base = None
549 base_upstream = None
550
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000551 def is_ancestor(a, b):
552 return run_with_retcode('merge-base', '--is-ancestor', a, b) == 0
553
clemensh@chromium.orgc3fe99d2016-04-19 08:39:55 +0000554 if base and base != actual_merge_base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000555 if not is_ancestor(base, branch):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000556 logging.debug('Found WRONG pre-set merge-base for %s: %s', branch, base)
557 base = None
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000558 elif is_ancestor(base, actual_merge_base):
559 logging.debug('Found OLD pre-set merge-base for %s: %s', branch, base)
560 base = None
561 else:
562 logging.debug('Found pre-set merge-base for %s: %s', branch, base)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000563
564 if not base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000565 base = actual_merge_base
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000566 manual_merge_base(branch, base, parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000567
568 return base
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000569
570
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000571def hash_multi(*reflike):
572 return run('rev-parse', *reflike).splitlines()
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000573
574
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000575def hash_one(reflike, short=False):
576 args = ['rev-parse', reflike]
577 if short:
578 args.insert(1, '--short')
579 return run(*args)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000580
581
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000582def in_rebase():
583 git_dir = run('rev-parse', '--git-dir')
584 return (
585 os.path.exists(os.path.join(git_dir, 'rebase-merge')) or
586 os.path.exists(os.path.join(git_dir, 'rebase-apply')))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000587
588
589def intern_f(f, kind='blob'):
590 """Interns a file object into the git object store.
591
592 Args:
593 f (file-like object) - The file-like object to intern
594 kind (git object type) - One of 'blob', 'commit', 'tree', 'tag'.
595
596 Returns the git hash of the interned object (hex encoded).
597 """
598 ret = run('hash-object', '-t', kind, '-w', '--stdin', stdin=f)
599 f.close()
600 return ret
601
602
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000603def is_dormant(branch):
604 # TODO(iannucci): Do an oldness check?
605 return branch_config(branch, 'dormant', 'false') != 'false'
606
607
agable02b3c982016-06-22 07:51:22 -0700608def is_unmerged(stat_value):
609 return (
610 'U' in (stat_value.lstat, stat_value.rstat) or
611 ((stat_value.lstat == stat_value.rstat) and stat_value.lstat in 'AD')
612 )
613
614
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000615def manual_merge_base(branch, base, parent):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000616 set_branch_config(branch, 'base', base)
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000617 set_branch_config(branch, 'base-upstream', parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000618
619
620def mktree(treedict):
621 """Makes a git tree object and returns its hash.
622
623 See |tree()| for the values of mode, type, and ref.
624
625 Args:
626 treedict - { name: (mode, type, ref) }
627 """
628 with tempfile.TemporaryFile() as f:
Edward Lemur12a537f2019-10-03 21:57:15 +0000629 for name, (mode, typ, ref) in treedict.items():
Edward Lemur71681bf2019-10-09 23:46:20 +0000630 f.write(('%s %s %s\t%s\0' % (mode, typ, ref, name)).encode('utf-8'))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000631 f.seek(0)
632 return run('mktree', '-z', stdin=f)
633
634
635def parse_commitrefs(*commitrefs):
636 """Returns binary encoded commit hashes for one or more commitrefs.
637
638 A commitref is anything which can resolve to a commit. Popular examples:
639 * 'HEAD'
Josip Sokcevic9c0dc302020-11-20 18:41:25 +0000640 * 'origin/main'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000641 * 'cool_branch~2'
642 """
643 try:
Edward Lemur12a537f2019-10-03 21:57:15 +0000644 return [binascii.unhexlify(h) for h in hash_multi(*commitrefs)]
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000645 except subprocess2.CalledProcessError:
646 raise BadCommitRefException(commitrefs)
647
648
sbc@chromium.org384039b2014-10-13 21:01:00 +0000649RebaseRet = collections.namedtuple('RebaseRet', 'success stdout stderr')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000650
651
Robert Iannuccid3acb162021-05-04 21:37:40 +0000652def rebase(parent, start, branch, abort=False, allow_gc=False):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000653 """Rebases |start|..|branch| onto the branch |parent|.
654
Robert Iannuccid3acb162021-05-04 21:37:40 +0000655 Sets 'gc.auto=0' for the duration of this call to prevent the rebase from
656 running a potentially slow garbage collection cycle.
657
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000658 Args:
659 parent - The new parent ref for the rebased commits.
660 start - The commit to start from
661 branch - The branch to rebase
662 abort - If True, will call git-rebase --abort in the event that the rebase
663 doesn't complete successfully.
Robert Iannuccid3acb162021-05-04 21:37:40 +0000664 allow_gc - If True, sets "-c gc.auto=1" on the rebase call, rather than
665 "-c gc.auto=0". Usually if you're doing a series of rebases,
666 you'll only want to run a single gc pass at the end of all the
667 rebase activity.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000668
669 Returns a namedtuple with fields:
670 success - a boolean indicating that the rebase command completed
671 successfully.
672 message - if the rebase failed, this contains the stdout of the failed
673 rebase.
674 """
675 try:
Robert Iannuccid3acb162021-05-04 21:37:40 +0000676 args = [
677 '-c', 'gc.auto={}'.format('1' if allow_gc else '0'),
678 'rebase',
679 ]
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000680 if TEST_MODE:
Robert Iannuccid3acb162021-05-04 21:37:40 +0000681 args.append('--committer-date-is-author-date')
682 args += [
683 '--onto', parent, start, branch,
684 ]
685 run(*args)
sbc@chromium.org384039b2014-10-13 21:01:00 +0000686 return RebaseRet(True, '', '')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000687 except subprocess2.CalledProcessError as cpe:
688 if abort:
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000689 run_with_retcode('rebase', '--abort') # ignore failure
Josip Sokcevic72f991f2020-04-23 18:53:30 +0000690 return RebaseRet(False, cpe.stdout.decode('utf-8', 'replace'),
691 cpe.stderr.decode('utf-8', 'replace'))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000692
693
694def remove_merge_base(branch):
695 del_branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000696 del_branch_config(branch, 'base-upstream')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000697
698
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000699def repo_root():
700 """Returns the absolute path to the repository root."""
701 return run('rev-parse', '--show-toplevel')
702
703
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000704def upstream_default():
705 """Returns the default branch name of the origin repository."""
706 try:
Josip Sokcevic06423732021-03-31 19:04:42 +0000707 ret = run('rev-parse', '--abbrev-ref', 'origin/HEAD')
708 # Detect if the repository migrated to main branch
709 if ret == 'origin/master':
710 try:
711 ret = run('rev-parse', '--abbrev-ref', 'origin/main')
712 run('remote', 'set-head', '-a', 'origin')
713 ret = run('rev-parse', '--abbrev-ref', 'origin/HEAD')
714 except subprocess2.CalledProcessError:
715 pass
716 return ret
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000717 except subprocess2.CalledProcessError:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +0000718 return 'origin/main'
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000719
720
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000721def root():
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000722 return get_config('depot-tools.upstream', upstream_default())
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000723
724
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000725@contextlib.contextmanager
726def less(): # pragma: no cover
727 """Runs 'less' as context manager yielding its stdin as a PIPE.
728
729 Automatically checks if sys.stdout is a non-TTY stream. If so, it avoids
730 running less and just yields sys.stdout.
Edward Lemur0d462e92020-01-08 20:11:31 +0000731
732 The returned PIPE is opened on binary mode.
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000733 """
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +0000734 if not setup_color.IS_TTY:
Edward Lemur5e94b802019-11-26 21:44:08 +0000735 # On Python 3, sys.stdout doesn't accept bytes, and sys.stdout.buffer must
736 # be used.
737 yield getattr(sys.stdout, 'buffer', sys.stdout)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000738 return
739
740 # Run with the same options that git uses (see setup_pager in git repo).
741 # -F: Automatically quit if the output is less than one screen.
742 # -R: Don't escape ANSI color codes.
743 # -X: Don't clear the screen before starting.
744 cmd = ('less', '-FRX')
745 try:
746 proc = subprocess2.Popen(cmd, stdin=subprocess2.PIPE)
747 yield proc.stdin
748 finally:
Edward Lemurb800fde2020-01-10 23:04:44 +0000749 try:
750 proc.stdin.close()
751 except BrokenPipeError:
752 # BrokenPipeError is raised if proc has already completed,
753 pass
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000754 proc.wait()
755
756
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000757def run(*cmd, **kwargs):
758 """The same as run_with_stderr, except it only returns stdout."""
759 return run_with_stderr(*cmd, **kwargs)[0]
760
761
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000762def run_with_retcode(*cmd, **kwargs):
763 """Run a command but only return the status code."""
764 try:
765 run(*cmd, **kwargs)
766 return 0
767 except subprocess2.CalledProcessError as cpe:
768 return cpe.returncode
769
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000770def run_stream(*cmd, **kwargs):
771 """Runs a git command. Returns stdout as a PIPE (file-like object).
772
773 stderr is dropped to avoid races if the process outputs to both stdout and
774 stderr.
775 """
Edward Lesmescf06cad2020-12-14 22:03:23 +0000776 kwargs.setdefault('stderr', subprocess2.DEVNULL)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000777 kwargs.setdefault('stdout', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000778 kwargs.setdefault('shell', False)
iannucci@chromium.org21980022014-04-11 04:51:49 +0000779 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000780 proc = subprocess2.Popen(cmd, **kwargs)
781 return proc.stdout
782
783
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000784@contextlib.contextmanager
785def run_stream_with_retcode(*cmd, **kwargs):
786 """Runs a git command as context manager yielding stdout as a PIPE.
787
788 stderr is dropped to avoid races if the process outputs to both stdout and
789 stderr.
790
791 Raises subprocess2.CalledProcessError on nonzero return code.
792 """
Edward Lesmescf06cad2020-12-14 22:03:23 +0000793 kwargs.setdefault('stderr', subprocess2.DEVNULL)
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000794 kwargs.setdefault('stdout', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000795 kwargs.setdefault('shell', False)
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000796 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
797 try:
798 proc = subprocess2.Popen(cmd, **kwargs)
799 yield proc.stdout
800 finally:
801 retcode = proc.wait()
802 if retcode != 0:
803 raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(),
Josip Sokcevic72f991f2020-04-23 18:53:30 +0000804 b'', b'')
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000805
806
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000807def run_with_stderr(*cmd, **kwargs):
808 """Runs a git command.
809
810 Returns (stdout, stderr) as a pair of strings.
811
812 kwargs
813 autostrip (bool) - Strip the output. Defaults to True.
814 indata (str) - Specifies stdin data for the process.
815 """
816 kwargs.setdefault('stdin', subprocess2.PIPE)
817 kwargs.setdefault('stdout', subprocess2.PIPE)
818 kwargs.setdefault('stderr', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000819 kwargs.setdefault('shell', False)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000820 autostrip = kwargs.pop('autostrip', True)
821 indata = kwargs.pop('indata', None)
Edward Lemur12a537f2019-10-03 21:57:15 +0000822 decode = kwargs.pop('decode', True)
Orr Bernsteinb7e16d22023-07-14 11:00:55 +0000823 accepted_retcodes = kwargs.pop('accepted_retcodes', [0])
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000824
iannucci@chromium.org21980022014-04-11 04:51:49 +0000825 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000826 proc = subprocess2.Popen(cmd, **kwargs)
827 ret, err = proc.communicate(indata)
828 retcode = proc.wait()
Orr Bernsteinb7e16d22023-07-14 11:00:55 +0000829 if retcode not in accepted_retcodes:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000830 raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(), ret, err)
831
832 if autostrip:
Edward Lemur12a537f2019-10-03 21:57:15 +0000833 ret = (ret or b'').strip()
834 err = (err or b'').strip()
835
836 if decode:
837 ret = ret.decode('utf-8', 'replace')
838 err = err.decode('utf-8', 'replace')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000839
840 return ret, err
841
842
843def set_branch_config(branch, option, value, scope='local'):
844 set_config('branch.%s.%s' % (branch, option), value, scope=scope)
845
846
847def set_config(option, value, scope='local'):
848 run('config', '--' + scope, option, value)
849
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000850
sbc@chromium.org71437c02015-04-09 19:29:40 +0000851def get_dirty_files():
852 # Make sure index is up-to-date before running diff-index.
853 run_with_retcode('update-index', '--refresh', '-q')
Eli Ribble54434e72019-05-24 00:41:15 +0000854 return run('diff-index', '--ignore-submodules', '--name-status', 'HEAD')
sbc@chromium.org71437c02015-04-09 19:29:40 +0000855
856
857def is_dirty_git_tree(cmd):
iannuccie38699b2016-08-15 17:32:31 -0700858 w = lambda s: sys.stderr.write(s+"\n")
859
sbc@chromium.org71437c02015-04-09 19:29:40 +0000860 dirty = get_dirty_files()
861 if dirty:
Josip Sokcevicfcf9fc42022-09-27 21:59:01 +0000862 w('Cannot %s with a dirty tree. Commit%s or stash your changes first.' %
863 (cmd, '' if cmd == 'upload' else ', freeze'))
iannuccie38699b2016-08-15 17:32:31 -0700864 w('Uncommitted files: (git diff-index --name-status HEAD)')
865 w(dirty[:4096])
sbc@chromium.org71437c02015-04-09 19:29:40 +0000866 if len(dirty) > 4096: # pragma: no cover
iannuccie38699b2016-08-15 17:32:31 -0700867 w('... (run "git diff-index --name-status HEAD" to see full output).')
sbc@chromium.org71437c02015-04-09 19:29:40 +0000868 return True
869 return False
870
871
Greg NISBET923bcf82023-08-10 22:50:46 +0000872def status(ignore_submodules=None):
agable02b3c982016-06-22 07:51:22 -0700873 """Returns a parsed version of git-status.
874
Greg NISBET923bcf82023-08-10 22:50:46 +0000875 Args:
876 ignore_submodules (str|None): "all", "none", or None.
877 None is equivalent to "none".
878
agable02b3c982016-06-22 07:51:22 -0700879 Returns a generator of (current_name, (lstat, rstat, src)) pairs where:
880 * current_name is the name of the file
881 * lstat is the left status code letter from git-status
882 * rstat is the left status code letter from git-status
883 * src is the current name of the file, or the original name of the file
884 if lstat == 'R'
885 """
Greg NISBET923bcf82023-08-10 22:50:46 +0000886
887 ignore_submodules = ignore_submodules or 'none'
888 assert ignore_submodules in (
889 'all', 'none'), f'ignore_submodules value {ignore_submodules} is invalid'
890
agable02b3c982016-06-22 07:51:22 -0700891 stat_entry = collections.namedtuple('stat_entry', 'lstat rstat src')
892
893 def tokenizer(stream):
Raul Tambrec2f74c12019-03-19 05:55:53 +0000894 acc = BytesIO()
agable02b3c982016-06-22 07:51:22 -0700895 c = None
Edward Lemur12a537f2019-10-03 21:57:15 +0000896 while c != b'':
agable02b3c982016-06-22 07:51:22 -0700897 c = stream.read(1)
Edward Lemur12a537f2019-10-03 21:57:15 +0000898 if c in (None, b'', b'\0'):
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000899 if len(acc.getvalue()) > 0:
agable02b3c982016-06-22 07:51:22 -0700900 yield acc.getvalue()
Raul Tambrec2f74c12019-03-19 05:55:53 +0000901 acc = BytesIO()
agable02b3c982016-06-22 07:51:22 -0700902 else:
903 acc.write(c)
904
905 def parser(tokens):
906 while True:
Edward Lemur12a537f2019-10-03 21:57:15 +0000907 try:
908 status_dest = next(tokens).decode('utf-8')
909 except StopIteration:
910 return
agable02b3c982016-06-22 07:51:22 -0700911 stat, dest = status_dest[:2], status_dest[3:]
912 lstat, rstat = stat
913 if lstat == 'R':
Edward Lemur12a537f2019-10-03 21:57:15 +0000914 src = next(tokens).decode('utf-8')
agable02b3c982016-06-22 07:51:22 -0700915 else:
916 src = dest
917 yield (dest, stat_entry(lstat, rstat, src))
918
Greg NISBET923bcf82023-08-10 22:50:46 +0000919 return parser(
920 tokenizer(
921 run_stream('status',
922 '-z',
923 f'--ignore-submodules={ignore_submodules}',
924 bufsize=-1)))
agable02b3c982016-06-22 07:51:22 -0700925
926
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000927def squash_current_branch(header=None, merge_base=None):
Alan Cutter00017822016-12-20 17:39:59 +1100928 header = header or 'git squash commit for %s.' % current_branch()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000929 merge_base = merge_base or get_or_create_merge_base(current_branch())
930 log_msg = header + '\n'
931 if log_msg:
932 log_msg += '\n'
933 log_msg += run('log', '--reverse', '--format=%H%n%B', '%s..HEAD' % merge_base)
934 run('reset', '--soft', merge_base)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000935
936 if not get_dirty_files():
937 # Sometimes the squash can result in the same tree, meaning that there is
938 # nothing to commit at this point.
Raul Tambrec2f74c12019-03-19 05:55:53 +0000939 print('Nothing to commit; squashed branch is empty')
sbc@chromium.org71437c02015-04-09 19:29:40 +0000940 return False
Edward Lemur71681bf2019-10-09 23:46:20 +0000941 run('commit', '--no-verify', '-a', '-F', '-', indata=log_msg.encode('utf-8'))
sbc@chromium.org71437c02015-04-09 19:29:40 +0000942 return True
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000943
944
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000945def tags(*args):
946 return run('tag', *args).splitlines()
947
948
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000949def thaw():
950 took_action = False
Bruce Dawson4082f882023-05-15 17:14:17 +0000951 with run_stream('rev-list', 'HEAD') as stream:
952 for sha in stream:
953 sha = sha.strip().decode('utf-8')
954 msg = run('show', '--format=%f%b', '-s', 'HEAD')
955 match = FREEZE_MATCHER.match(msg)
956 if not match:
957 if not took_action:
958 return 'Nothing to thaw.'
959 break
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000960
Bruce Dawson4082f882023-05-15 17:14:17 +0000961 run('reset', '--' + FREEZE_SECTIONS[match.group(1)], sha)
962 took_action = True
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000963
964
965def topo_iter(branch_tree, top_down=True):
966 """Generates (branch, parent) in topographical order for a branch tree.
967
968 Given a tree:
969
970 A1
971 B1 B2
972 C1 C2 C3
973 D1
974
975 branch_tree would look like: {
976 'D1': 'C3',
977 'C3': 'B2',
978 'B2': 'A1',
979 'C1': 'B1',
980 'C2': 'B1',
981 'B1': 'A1',
982 }
983
984 It is OK to have multiple 'root' nodes in your graph.
985
986 if top_down is True, items are yielded from A->D. Otherwise they're yielded
987 from D->A. Within a layer the branches will be yielded in sorted order.
988 """
989 branch_tree = branch_tree.copy()
990
991 # TODO(iannucci): There is probably a more efficient way to do these.
992 if top_down:
993 while branch_tree:
Edward Lemur12a537f2019-10-03 21:57:15 +0000994 this_pass = [(b, p) for b, p in branch_tree.items()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000995 if p not in branch_tree]
996 assert this_pass, "Branch tree has cycles: %r" % branch_tree
997 for branch, parent in sorted(this_pass):
998 yield branch, parent
999 del branch_tree[branch]
1000 else:
1001 parent_to_branches = collections.defaultdict(set)
Edward Lemur12a537f2019-10-03 21:57:15 +00001002 for branch, parent in branch_tree.items():
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001003 parent_to_branches[parent].add(branch)
1004
1005 while branch_tree:
Edward Lemur12a537f2019-10-03 21:57:15 +00001006 this_pass = [(b, p) for b, p in branch_tree.items()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001007 if not parent_to_branches[b]]
1008 assert this_pass, "Branch tree has cycles: %r" % branch_tree
1009 for branch, parent in sorted(this_pass):
1010 yield branch, parent
1011 parent_to_branches[parent].discard(branch)
1012 del branch_tree[branch]
1013
1014
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +00001015def tree(treeref, recurse=False):
1016 """Returns a dict representation of a git tree object.
1017
1018 Args:
1019 treeref (str) - a git ref which resolves to a tree (commits count as trees).
qyearsley12fa6ff2016-08-24 09:18:40 -07001020 recurse (bool) - include all of the tree's descendants too. File names will
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +00001021 take the form of 'some/path/to/file'.
1022
1023 Return format:
1024 { 'file_name': (mode, type, ref) }
1025
1026 mode is an integer where:
1027 * 0040000 - Directory
1028 * 0100644 - Regular non-executable file
1029 * 0100664 - Regular non-executable group-writeable file
1030 * 0100755 - Regular executable file
1031 * 0120000 - Symbolic link
1032 * 0160000 - Gitlink
1033
1034 type is a string where it's one of 'blob', 'commit', 'tree', 'tag'.
1035
1036 ref is the hex encoded hash of the entry.
1037 """
1038 ret = {}
1039 opts = ['ls-tree', '--full-tree']
1040 if recurse:
1041 opts.append('-r')
1042 opts.append(treeref)
1043 try:
1044 for line in run(*opts).splitlines():
1045 mode, typ, ref, name = line.split(None, 3)
1046 ret[name] = (mode, typ, ref)
1047 except subprocess2.CalledProcessError:
1048 return None
1049 return ret
1050
1051
Mun Yong Jang781e71e2017-10-25 15:46:20 -07001052def get_remote_url(remote='origin'):
1053 try:
1054 return run('config', 'remote.%s.url' % remote)
1055 except subprocess2.CalledProcessError:
1056 return None
1057
1058
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +00001059def upstream(branch):
1060 try:
1061 return run('rev-parse', '--abbrev-ref', '--symbolic-full-name',
1062 branch+'@{upstream}')
1063 except subprocess2.CalledProcessError:
1064 return None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001065
agable@chromium.orgd629fb42014-10-01 09:40:10 +00001066
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001067def get_git_version():
1068 """Returns a tuple that contains the numeric components of the current git
1069 version."""
1070 version_string = run('--version')
1071 version_match = re.search(r'(\d+.)+(\d+)', version_string)
1072 version = version_match.group() if version_match else ''
1073
1074 return tuple(int(x) for x in version.split('.'))
1075
1076
calamity@chromium.org745ffa62014-09-08 01:03:19 +00001077def get_branches_info(include_tracking_status):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001078 format_string = (
1079 '--format=%(refname:short):%(objectname:short):%(upstream:short):')
1080
1081 # This is not covered by the depot_tools CQ which only has git version 1.8.
calamity@chromium.org745ffa62014-09-08 01:03:19 +00001082 if (include_tracking_status and
1083 get_git_version() >= MIN_UPSTREAM_TRACK_GIT_VERSION): # pragma: no cover
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001084 format_string += '%(upstream:track)'
1085
1086 info_map = {}
1087 data = run('for-each-ref', format_string, 'refs/heads')
calamity@chromium.org745ffa62014-09-08 01:03:19 +00001088 BranchesInfo = collections.namedtuple(
Gavin Mak8d7201b2020-09-17 19:21:38 +00001089 'BranchesInfo', 'hash upstream commits behind')
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001090 for line in data.splitlines():
1091 (branch, branch_hash, upstream_branch, tracking_status) = line.split(':')
1092
Gavin Mak8d7201b2020-09-17 19:21:38 +00001093 commits = None
Antonio Sartorie0dff202021-02-18 06:33:50 +00001094 if include_tracking_status:
1095 base = get_or_create_merge_base(branch)
1096 if base:
1097 commits_list = run('rev-list', '--count', branch, '^%s' % base, '--')
1098 commits = int(commits_list) or None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001099
1100 behind_match = re.search(r'behind (\d+)', tracking_status)
1101 behind = int(behind_match.group(1)) if behind_match else None
1102
calamity@chromium.org745ffa62014-09-08 01:03:19 +00001103 info_map[branch] = BranchesInfo(
Robert Iannuccid3acb162021-05-04 21:37:40 +00001104 hash=branch_hash, upstream=upstream_branch, commits=commits,
Gavin Mak8d7201b2020-09-17 19:21:38 +00001105 behind=behind)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001106
1107 # Set None for upstreams which are not branches (e.g empty upstream, remotes
1108 # and deleted upstream branches).
1109 missing_upstreams = {}
1110 for info in info_map.values():
1111 if info.upstream not in info_map and info.upstream not in missing_upstreams:
1112 missing_upstreams[info.upstream] = None
1113
Edward Lemur12a537f2019-10-03 21:57:15 +00001114 result = info_map.copy()
1115 result.update(missing_upstreams)
1116 return result
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001117
1118
1119def make_workdir_common(repository, new_workdir, files_to_symlink,
scottmg@chromium.orgd4218d42015-10-07 23:49:20 +00001120 files_to_copy, symlink=None):
1121 if not symlink:
1122 symlink = os.symlink
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001123 os.makedirs(new_workdir)
1124 for entry in files_to_symlink:
scottmg@chromium.orgd4218d42015-10-07 23:49:20 +00001125 clone_file(repository, new_workdir, entry, symlink)
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001126 for entry in files_to_copy:
1127 clone_file(repository, new_workdir, entry, shutil.copy)
1128
1129
1130def make_workdir(repository, new_workdir):
1131 GIT_DIRECTORY_WHITELIST = [
1132 'config',
1133 'info',
1134 'hooks',
1135 'logs/refs',
1136 'objects',
1137 'packed-refs',
1138 'refs',
1139 'remotes',
1140 'rr-cache',
Richard He42033b22020-05-22 03:03:45 +00001141 'shallow',
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001142 ]
1143 make_workdir_common(repository, new_workdir, GIT_DIRECTORY_WHITELIST,
1144 ['HEAD'])
1145
1146
1147def clone_file(repository, new_workdir, link, operation):
1148 if not os.path.exists(os.path.join(repository, link)):
1149 return
1150 link_dir = os.path.dirname(os.path.join(new_workdir, link))
1151 if not os.path.exists(link_dir):
1152 os.makedirs(link_dir)
Henrique Ferreirofd4ad242018-01-10 12:19:18 +01001153 src = os.path.join(repository, link)
1154 if os.path.islink(src):
Henrique Ferreiroaea45d22018-02-19 09:48:36 +01001155 src = os.path.realpath(src)
Henrique Ferreirofd4ad242018-01-10 12:19:18 +01001156 operation(src, os.path.join(new_workdir, link))