blob: d406dc43507092cfb422643d4709d9ed9c3cae89 [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
Aravind Vasudevanb8164182023-08-25 21:49:12 +000014from third_party import colorama
15
16
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000017def wrapper(func):
18 def wrap(self, timeout=None):
Gavin Makcc976552023-08-28 17:01:52 +000019 return func(self, timeout=timeout or threading.TIMEOUT_MAX)
Josip Sokcevicde6c4562020-03-26 00:39:42 +000020
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000021 return wrap
22IMapIterator.next = wrapper(IMapIterator.next)
23IMapIterator.__next__ = IMapIterator.next
24# TODO(iannucci): Monkeypatch all other 'wait' methods too.
25
26
27import binascii
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000028import collections
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000029import contextlib
30import functools
31import logging
iannucci@chromium.org97345eb2014-03-13 07:55:15 +000032import os
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000033import re
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +000034import setup_color
sammc@chromium.org900a33f2015-09-29 06:57:09 +000035import shutil
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000036import signal
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000037import tempfile
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +000038import textwrap
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000039
40import subprocess2
41
Raul Tambrec2f74c12019-03-19 05:55:53 +000042from io import BytesIO
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000043
agable02b3c982016-06-22 07:51:22 -070044
45ROOT = os.path.abspath(os.path.dirname(__file__))
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +000046IS_WIN = sys.platform == 'win32'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000047TEST_MODE = False
48
Dan Jacques209a6812017-07-12 11:40:20 -070049
50def win_find_git():
51 for elem in os.environ.get('PATH', '').split(os.pathsep):
52 for candidate in ('git.exe', 'git.bat'):
53 path = os.path.join(elem, candidate)
54 if os.path.isfile(path):
55 return path
56 raise ValueError('Could not find Git on PATH.')
57
58
59GIT_EXE = 'git' if not IS_WIN else win_find_git()
60
61
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000062FREEZE = 'FREEZE'
63FREEZE_SECTIONS = {
64 'indexed': 'soft',
65 'unindexed': 'mixed'
66}
67FREEZE_MATCHER = re.compile(r'%s.(%s)' % (FREEZE, '|'.join(FREEZE_SECTIONS)))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000068
69
Dan Jacques2f8b0c12017-04-05 12:57:21 -070070# NOTE: This list is DEPRECATED in favor of the Infra Git wrapper:
Josip Sokcevic9c0dc302020-11-20 18:41:25 +000071# https://chromium.googlesource.com/infra/infra/+/HEAD/go/src/infra/tools/git
Dan Jacques2f8b0c12017-04-05 12:57:21 -070072#
73# New entries should be added to the Git wrapper, NOT to this list. "git_retry"
74# is, similarly, being deprecated in favor of the Git wrapper.
75#
76# ---
77#
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000078# Retry a git operation if git returns a error response with any of these
79# messages. It's all observed 'bad' GoB responses so far.
80#
81# This list is inspired/derived from the one in ChromiumOS's Chromite:
82# <CHROMITE>/lib/git.py::GIT_TRANSIENT_ERRORS
83#
84# It was last imported from '7add3ac29564d98ac35ce426bc295e743e7c0c02'.
85GIT_TRANSIENT_ERRORS = (
86 # crbug.com/285832
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000087 r'!.*\[remote rejected\].*\(error in hook\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000088
89 # crbug.com/289932
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000090 r'!.*\[remote rejected\].*\(failed to lock\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000091
92 # crbug.com/307156
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000093 r'!.*\[remote rejected\].*\(error in Gerrit backend\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000094
95 # crbug.com/285832
96 r'remote error: Internal Server Error',
97
98 # crbug.com/294449
99 r'fatal: Couldn\'t find remote ref ',
100
101 # crbug.com/220543
102 r'git fetch_pack: expected ACK/NAK, got',
103
104 # crbug.com/189455
105 r'protocol error: bad pack header',
106
107 # crbug.com/202807
108 r'The remote end hung up unexpectedly',
109
110 # crbug.com/298189
111 r'TLS packet with unexpected length was received',
112
113 # crbug.com/187444
114 r'RPC failed; result=\d+, HTTP code = \d+',
115
dnj@chromium.orgde219ec2014-07-28 17:39:08 +0000116 # crbug.com/388876
117 r'Connection timed out',
dnj@chromium.org45cddd62014-11-06 19:36:42 +0000118
119 # crbug.com/430343
120 # TODO(dnj): Resync with Chromite.
121 r'The requested URL returned error: 5\d+',
Arikonb3a21482016-07-22 10:12:24 -0700122
123 r'Connection reset by peer',
124
125 r'Unable to look up',
126
127 r'Couldn\'t resolve host',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +0000128)
129
130GIT_TRANSIENT_ERRORS_RE = re.compile('|'.join(GIT_TRANSIENT_ERRORS),
131 re.IGNORECASE)
132
raphael.kubo.da.costa@intel.com58d05b02015-06-24 08:54:41 +0000133# git's for-each-ref command first supported the upstream:track token in its
134# format string in version 1.9.0, but some usages were broken until 2.3.0.
135# See git commit b6160d95 for more information.
136MIN_UPSTREAM_TRACK_GIT_VERSION = (2, 3)
dnj@chromium.orgde219ec2014-07-28 17:39:08 +0000137
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000138class BadCommitRefException(Exception):
139 def __init__(self, refs):
140 msg = ('one of %s does not seem to be a valid commitref.' %
141 str(refs))
142 super(BadCommitRefException, self).__init__(msg)
143
144
145def memoize_one(**kwargs):
146 """Memoizes a single-argument pure function.
147
148 Values of None are not cached.
149
150 Kwargs:
151 threadsafe (bool) - REQUIRED. Specifies whether to use locking around
152 cache manipulation functions. This is a kwarg so that users of memoize_one
153 are forced to explicitly and verbosely pick True or False.
154
155 Adds three methods to the decorated function:
156 * get(key, default=None) - Gets the value for this key from the cache.
157 * set(key, value) - Sets the value for this key from the cache.
158 * clear() - Drops the entire contents of the cache. Useful for unittests.
159 * update(other) - Updates the contents of the cache from another dict.
160 """
161 assert 'threadsafe' in kwargs, 'Must specify threadsafe={True,False}'
162 threadsafe = kwargs['threadsafe']
163
164 if threadsafe:
165 def withlock(lock, f):
166 def inner(*args, **kwargs):
167 with lock:
168 return f(*args, **kwargs)
169 return inner
170 else:
171 def withlock(_lock, f):
172 return f
173
174 def decorator(f):
175 # Instantiate the lock in decorator, in case users of memoize_one do:
176 #
177 # memoizer = memoize_one(threadsafe=True)
178 #
179 # @memoizer
180 # def fn1(val): ...
181 #
182 # @memoizer
183 # def fn2(val): ...
184
185 lock = threading.Lock() if threadsafe else None
186 cache = {}
187 _get = withlock(lock, cache.get)
188 _set = withlock(lock, cache.__setitem__)
189
190 @functools.wraps(f)
191 def inner(arg):
192 ret = _get(arg)
193 if ret is None:
194 ret = f(arg)
195 if ret is not None:
196 _set(arg, ret)
197 return ret
198 inner.get = _get
199 inner.set = _set
200 inner.clear = withlock(lock, cache.clear)
201 inner.update = withlock(lock, cache.update)
202 return inner
203 return decorator
204
205
206def _ScopedPool_initer(orig, orig_args): # pragma: no cover
207 """Initializer method for ScopedPool's subprocesses.
208
209 This helps ScopedPool handle Ctrl-C's correctly.
210 """
211 signal.signal(signal.SIGINT, signal.SIG_IGN)
212 if orig:
213 orig(*orig_args)
214
215
216@contextlib.contextmanager
217def ScopedPool(*args, **kwargs):
218 """Context Manager which returns a multiprocessing.pool instance which
219 correctly deals with thrown exceptions.
220
221 *args - Arguments to multiprocessing.pool
222
223 Kwargs:
224 kind ('threads', 'procs') - The type of underlying coprocess to use.
225 **etc - Arguments to multiprocessing.pool
226 """
227 if kwargs.pop('kind', None) == 'threads':
228 pool = multiprocessing.pool.ThreadPool(*args, **kwargs)
229 else:
230 orig, orig_args = kwargs.get('initializer'), kwargs.get('initargs', ())
231 kwargs['initializer'] = _ScopedPool_initer
232 kwargs['initargs'] = orig, orig_args
233 pool = multiprocessing.pool.Pool(*args, **kwargs)
234
235 try:
236 yield pool
237 pool.close()
238 except:
239 pool.terminate()
240 raise
241 finally:
242 pool.join()
243
244
245class ProgressPrinter(object):
246 """Threaded single-stat status message printer."""
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000247 def __init__(self, fmt, enabled=None, fout=sys.stderr, period=0.5):
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000248 """Create a ProgressPrinter.
249
250 Use it as a context manager which produces a simple 'increment' method:
251
252 with ProgressPrinter('(%%(count)d/%d)' % 1000) as inc:
253 for i in xrange(1000):
254 # do stuff
255 if i % 10 == 0:
256 inc(10)
257
258 Args:
259 fmt - String format with a single '%(count)d' where the counter value
260 should go.
261 enabled (bool) - If this is None, will default to True if
262 logging.getLogger() is set to INFO or more verbose.
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000263 fout (file-like) - The stream to print status messages to.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000264 period (float) - The time in seconds for the printer thread to wait
265 between printing.
266 """
267 self.fmt = fmt
268 if enabled is None: # pragma: no cover
269 self.enabled = logging.getLogger().isEnabledFor(logging.INFO)
270 else:
271 self.enabled = enabled
272
273 self._count = 0
274 self._dead = False
275 self._dead_cond = threading.Condition()
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000276 self._stream = fout
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000277 self._thread = threading.Thread(target=self._run)
278 self._period = period
279
280 def _emit(self, s):
281 if self.enabled:
282 self._stream.write('\r' + s)
283 self._stream.flush()
284
285 def _run(self):
286 with self._dead_cond:
287 while not self._dead:
288 self._emit(self.fmt % {'count': self._count})
289 self._dead_cond.wait(self._period)
290 self._emit((self.fmt + '\n') % {'count': self._count})
291
292 def inc(self, amount=1):
293 self._count += amount
294
295 def __enter__(self):
296 self._thread.start()
297 return self.inc
298
299 def __exit__(self, _exc_type, _exc_value, _traceback):
300 self._dead = True
301 with self._dead_cond:
302 self._dead_cond.notifyAll()
303 self._thread.join()
304 del self._thread
305
306
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000307def once(function):
308 """@Decorates |function| so that it only performs its action once, no matter
309 how many times the decorated |function| is called."""
Edward Lemur12a537f2019-10-03 21:57:15 +0000310 has_run = [False]
311 def _wrapper(*args, **kwargs):
312 if not has_run[0]:
313 has_run[0] = True
314 function(*args, **kwargs)
315 return _wrapper
316
317
318def unicode_repr(s):
319 result = repr(s)
320 return result[1:] if result.startswith('u') else result
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000321
322
323## Git functions
324
agable7aa2ddd2016-06-21 07:47:00 -0700325def die(message, *args):
Raul Tambrec2f74c12019-03-19 05:55:53 +0000326 print(textwrap.dedent(message % args), file=sys.stderr)
agable7aa2ddd2016-06-21 07:47:00 -0700327 sys.exit(1)
328
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000329
Mark Mentovaif548d082017-03-08 13:32:00 -0500330def blame(filename, revision=None, porcelain=False, abbrev=None, *_args):
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000331 command = ['blame']
332 if porcelain:
333 command.append('-p')
334 if revision is not None:
335 command.append(revision)
Mark Mentovaif548d082017-03-08 13:32:00 -0500336 if abbrev is not None:
337 command.append('--abbrev=%d' % abbrev)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000338 command.extend(['--', filename])
339 return run(*command)
340
341
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000342def branch_config(branch, option, default=None):
agable7aa2ddd2016-06-21 07:47:00 -0700343 return get_config('branch.%s.%s' % (branch, option), default=default)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000344
345
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000346def branch_config_map(option):
347 """Return {branch: <|option| value>} for all branches."""
348 try:
349 reg = re.compile(r'^branch\.(.*)\.%s$' % option)
agable7aa2ddd2016-06-21 07:47:00 -0700350 lines = get_config_regexp(reg.pattern)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000351 return {reg.match(k).group(1): v for k, v in (l.split() for l in lines)}
352 except subprocess2.CalledProcessError:
353 return {}
354
355
Francois Dorayd42c6812017-05-30 15:10:20 -0400356def branches(use_limit=True, *args):
akuegel@chromium.org58888e12015-06-09 15:26:37 +0000357 NO_BRANCH = ('* (no branch', '* (detached', '* (HEAD detached')
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000358
359 key = 'depot-tools.branch-limit'
agable7aa2ddd2016-06-21 07:47:00 -0700360 limit = get_config_int(key, 20)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000361
362 raw_branches = run('branch', *args).splitlines()
363
364 num = len(raw_branches)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000365
Francois Dorayd42c6812017-05-30 15:10:20 -0400366 if use_limit and num > limit:
agable7aa2ddd2016-06-21 07:47:00 -0700367 die("""\
368 Your git repo has too many branches (%d/%d) for this tool to work well.
369
370 You may adjust this limit by running:
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000371 git config %s <new_limit>
agable7aa2ddd2016-06-21 07:47:00 -0700372
373 You may also try cleaning up your old branches by running:
374 git cl archive
375 """, num, limit, key)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000376
377 for line in raw_branches:
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000378 if line.startswith(NO_BRANCH):
379 continue
380 yield line.split()[-1]
381
382
agable7aa2ddd2016-06-21 07:47:00 -0700383def get_config(option, default=None):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000384 try:
385 return run('config', '--get', option) or default
386 except subprocess2.CalledProcessError:
387 return default
388
389
agable7aa2ddd2016-06-21 07:47:00 -0700390def get_config_int(option, default=0):
391 assert isinstance(default, int)
392 try:
393 return int(get_config(option, default))
394 except ValueError:
395 return default
396
397
398def get_config_list(option):
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000399 try:
400 return run('config', '--get-all', option).split()
401 except subprocess2.CalledProcessError:
402 return []
403
404
agable7aa2ddd2016-06-21 07:47:00 -0700405def get_config_regexp(pattern):
406 if IS_WIN: # pragma: no cover
407 # this madness is because we call git.bat which calls git.exe which calls
408 # bash.exe (or something to that effect). Each layer divides the number of
409 # ^'s by 2.
410 pattern = pattern.replace('^', '^' * 8)
411 return run('config', '--get-regexp', pattern).splitlines()
412
413
Aravind Vasudevanb8164182023-08-25 21:49:12 +0000414def is_fsmonitor_enabled():
415 """Returns true if core.fsmonitor is enabled in git config."""
416 fsmonitor = get_config('core.fsmonitor', 'False')
417 return fsmonitor.strip().lower() == 'true'
418
419
420def warn_submodule():
421 """Print warnings for submodules."""
422 # TODO(crbug.com/1475405): Warn users if the project uses submodules and
423 # they have fsmonitor enabled.
424 if is_fsmonitor_enabled():
425 print(colorama.Fore.RED)
426 print('WARNING: You have fsmonitor enabled. There is a major issue '
427 'resulting in git diff-index returning wrong results. Please '
428 'disable it by running:')
Aravind Vasudevanc38ebea2023-08-29 20:53:30 +0000429 print(' git config core.fsmonitor false')
Aravind Vasudevanb8164182023-08-25 21:49:12 +0000430 print('We will remove this warning once https://crbug.com/1475405 is '
431 'fixed.')
432 print(colorama.Style.RESET_ALL)
433
434
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000435def current_branch():
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000436 try:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000437 return run('rev-parse', '--abbrev-ref', 'HEAD')
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000438 except subprocess2.CalledProcessError:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000439 return None
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000440
441
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000442def del_branch_config(branch, option, scope='local'):
443 del_config('branch.%s.%s' % (branch, option), scope=scope)
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000444
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000445
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000446def del_config(option, scope='local'):
447 try:
448 run('config', '--' + scope, '--unset', option)
449 except subprocess2.CalledProcessError:
450 pass
451
452
mgiuca@chromium.org01d2cde2016-02-05 03:25:41 +0000453def diff(oldrev, newrev, *args):
454 return run('diff', oldrev, newrev, *args)
455
456
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000457def freeze():
458 took_action = False
agable02b3c982016-06-22 07:51:22 -0700459 key = 'depot-tools.freeze-size-limit'
460 MB = 2**20
461 limit_mb = get_config_int(key, 100)
462 untracked_bytes = 0
463
iannuccieaca0332016-08-03 16:46:50 -0700464 root_path = repo_root()
465
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000466 # unindexed tracks all the files which are unindexed but we want to add to
467 # the `FREEZE.unindexed` commit.
468 unindexed = []
469
470 # will be set to true if there are any indexed files to commit.
471 have_indexed_files = False
472
Joanna Wang25410062023-08-10 23:28:44 +0000473 for f, s in status(ignore_submodules='all'):
agable02b3c982016-06-22 07:51:22 -0700474 if is_unmerged(s):
475 die("Cannot freeze unmerged changes!")
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000476 if s.lstat not in ' ?':
477 # This covers all changes to indexed files.
478 # lstat = ' ' means that the file is tracked and modified, but wasn't
479 # added yet.
480 # lstat = '?' means that the file is untracked.
481 have_indexed_files = True
Aravind Vasudevanc71efb52023-08-29 23:02:15 +0000482
483 # If the file has both indexed and unindexed changes.
484 # rstat shows the status of the working tree. If the file also has changes
485 # in the working tree, it should be tracked both in indexed and unindexed
486 # changes.
487 if s.rstat != ' ':
488 unindexed.append(f.encode('utf-8'))
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000489 else:
490 unindexed.append(f.encode('utf-8'))
Aravind Vasudevanc71efb52023-08-29 23:02:15 +0000491
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000492 if s.lstat == '?' and limit_mb > 0:
493 untracked_bytes += os.lstat(os.path.join(root_path, f)).st_size
494
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800495 if limit_mb > 0 and untracked_bytes > limit_mb * MB:
496 die("""\
497 You appear to have too much untracked+unignored data in your git
498 checkout: %.1f / %d MB.
agable02b3c982016-06-22 07:51:22 -0700499
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800500 Run `git status` to see what it is.
agable02b3c982016-06-22 07:51:22 -0700501
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800502 In addition to making many git commands slower, this will prevent
503 depot_tools from freezing your in-progress changes.
agable02b3c982016-06-22 07:51:22 -0700504
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800505 You should add untracked data that you want to ignore to your repo's
506 .git/info/exclude
507 file. See `git help ignore` for the format of this file.
agable02b3c982016-06-22 07:51:22 -0700508
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000509 If this data is intended as part of your commit, you may adjust the
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800510 freeze limit by running:
511 git config %s <new_limit>
512 Where <new_limit> is an integer threshold in megabytes.""",
513 untracked_bytes / (MB * 1.0), limit_mb, key)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000514
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000515 if have_indexed_files:
516 try:
517 run('commit', '--no-verify', '-m', f'{FREEZE}.indexed')
518 took_action = True
519 except subprocess2.CalledProcessError:
520 pass
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000521
agable96e179b2016-06-24 10:32:51 -0700522 add_errors = False
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000523 if unindexed:
524 try:
525 run('add',
526 '--pathspec-from-file',
527 '-',
528 '--ignore-errors',
Robert Iannucci2f0147a2023-07-20 16:41:59 +0000529 indata=b'\n'.join(unindexed),
530 cwd=root_path)
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000531 except subprocess2.CalledProcessError:
532 add_errors = True
agable96e179b2016-06-24 10:32:51 -0700533
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000534 try:
535 run('commit', '--no-verify', '-m', f'{FREEZE}.unindexed')
536 took_action = True
537 except subprocess2.CalledProcessError:
538 pass
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000539
agable96e179b2016-06-24 10:32:51 -0700540 ret = []
541 if add_errors:
542 ret.append('Failed to index some unindexed files.')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000543 if not took_action:
agable96e179b2016-06-24 10:32:51 -0700544 ret.append('Nothing to freeze.')
545 return ' '.join(ret) or None
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000546
547
Gavin Mak2cbe95c2023-03-06 22:39:56 +0000548def get_branch_tree(use_limit=False):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000549 """Get the dictionary of {branch: parent}, compatible with topo_iter.
550
551 Returns a tuple of (skipped, <branch_tree dict>) where skipped is a set of
552 branches without upstream branches defined.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000553 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000554 skipped = set()
555 branch_tree = {}
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000556
Gavin Mak2cbe95c2023-03-06 22:39:56 +0000557 for branch in branches(use_limit=use_limit):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000558 parent = upstream(branch)
559 if not parent:
560 skipped.add(branch)
561 continue
562 branch_tree[branch] = parent
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000563
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000564 return skipped, branch_tree
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000565
566
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000567def get_or_create_merge_base(branch, parent=None):
568 """Finds the configured merge base for branch.
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000569
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000570 If parent is supplied, it's used instead of calling upstream(branch).
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000571 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000572 base = branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000573 base_upstream = branch_config(branch, 'base-upstream')
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000574 parent = parent or upstream(branch)
sbc@chromium.org79706062015-01-14 21:18:12 +0000575 if parent is None or branch is None:
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000576 return None
Josip Sokcevica3d1aaf2021-07-16 18:26:45 +0000577 actual_merge_base = run('merge-base', parent, branch)
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000578
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000579 if base_upstream != parent:
580 base = None
581 base_upstream = None
582
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000583 def is_ancestor(a, b):
584 return run_with_retcode('merge-base', '--is-ancestor', a, b) == 0
585
clemensh@chromium.orgc3fe99d2016-04-19 08:39:55 +0000586 if base and base != actual_merge_base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000587 if not is_ancestor(base, branch):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000588 logging.debug('Found WRONG pre-set merge-base for %s: %s', branch, base)
589 base = None
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000590 elif is_ancestor(base, actual_merge_base):
591 logging.debug('Found OLD pre-set merge-base for %s: %s', branch, base)
592 base = None
593 else:
594 logging.debug('Found pre-set merge-base for %s: %s', branch, base)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000595
596 if not base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000597 base = actual_merge_base
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000598 manual_merge_base(branch, base, parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000599
600 return base
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000601
602
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000603def hash_multi(*reflike):
604 return run('rev-parse', *reflike).splitlines()
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000605
606
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000607def hash_one(reflike, short=False):
608 args = ['rev-parse', reflike]
609 if short:
610 args.insert(1, '--short')
611 return run(*args)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000612
613
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000614def in_rebase():
615 git_dir = run('rev-parse', '--git-dir')
616 return (
617 os.path.exists(os.path.join(git_dir, 'rebase-merge')) or
618 os.path.exists(os.path.join(git_dir, 'rebase-apply')))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000619
620
621def intern_f(f, kind='blob'):
622 """Interns a file object into the git object store.
623
624 Args:
625 f (file-like object) - The file-like object to intern
626 kind (git object type) - One of 'blob', 'commit', 'tree', 'tag'.
627
628 Returns the git hash of the interned object (hex encoded).
629 """
630 ret = run('hash-object', '-t', kind, '-w', '--stdin', stdin=f)
631 f.close()
632 return ret
633
634
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000635def is_dormant(branch):
636 # TODO(iannucci): Do an oldness check?
637 return branch_config(branch, 'dormant', 'false') != 'false'
638
639
agable02b3c982016-06-22 07:51:22 -0700640def is_unmerged(stat_value):
641 return (
642 'U' in (stat_value.lstat, stat_value.rstat) or
643 ((stat_value.lstat == stat_value.rstat) and stat_value.lstat in 'AD')
644 )
645
646
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000647def manual_merge_base(branch, base, parent):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000648 set_branch_config(branch, 'base', base)
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000649 set_branch_config(branch, 'base-upstream', parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000650
651
652def mktree(treedict):
653 """Makes a git tree object and returns its hash.
654
655 See |tree()| for the values of mode, type, and ref.
656
657 Args:
658 treedict - { name: (mode, type, ref) }
659 """
660 with tempfile.TemporaryFile() as f:
Edward Lemur12a537f2019-10-03 21:57:15 +0000661 for name, (mode, typ, ref) in treedict.items():
Edward Lemur71681bf2019-10-09 23:46:20 +0000662 f.write(('%s %s %s\t%s\0' % (mode, typ, ref, name)).encode('utf-8'))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000663 f.seek(0)
664 return run('mktree', '-z', stdin=f)
665
666
667def parse_commitrefs(*commitrefs):
668 """Returns binary encoded commit hashes for one or more commitrefs.
669
670 A commitref is anything which can resolve to a commit. Popular examples:
671 * 'HEAD'
Josip Sokcevic9c0dc302020-11-20 18:41:25 +0000672 * 'origin/main'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000673 * 'cool_branch~2'
674 """
675 try:
Edward Lemur12a537f2019-10-03 21:57:15 +0000676 return [binascii.unhexlify(h) for h in hash_multi(*commitrefs)]
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000677 except subprocess2.CalledProcessError:
678 raise BadCommitRefException(commitrefs)
679
680
sbc@chromium.org384039b2014-10-13 21:01:00 +0000681RebaseRet = collections.namedtuple('RebaseRet', 'success stdout stderr')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000682
683
Robert Iannuccid3acb162021-05-04 21:37:40 +0000684def rebase(parent, start, branch, abort=False, allow_gc=False):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000685 """Rebases |start|..|branch| onto the branch |parent|.
686
Robert Iannuccid3acb162021-05-04 21:37:40 +0000687 Sets 'gc.auto=0' for the duration of this call to prevent the rebase from
688 running a potentially slow garbage collection cycle.
689
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000690 Args:
691 parent - The new parent ref for the rebased commits.
692 start - The commit to start from
693 branch - The branch to rebase
694 abort - If True, will call git-rebase --abort in the event that the rebase
695 doesn't complete successfully.
Robert Iannuccid3acb162021-05-04 21:37:40 +0000696 allow_gc - If True, sets "-c gc.auto=1" on the rebase call, rather than
697 "-c gc.auto=0". Usually if you're doing a series of rebases,
698 you'll only want to run a single gc pass at the end of all the
699 rebase activity.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000700
701 Returns a namedtuple with fields:
702 success - a boolean indicating that the rebase command completed
703 successfully.
704 message - if the rebase failed, this contains the stdout of the failed
705 rebase.
706 """
707 try:
Robert Iannuccid3acb162021-05-04 21:37:40 +0000708 args = [
709 '-c', 'gc.auto={}'.format('1' if allow_gc else '0'),
710 'rebase',
711 ]
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000712 if TEST_MODE:
Robert Iannuccid3acb162021-05-04 21:37:40 +0000713 args.append('--committer-date-is-author-date')
714 args += [
715 '--onto', parent, start, branch,
716 ]
717 run(*args)
sbc@chromium.org384039b2014-10-13 21:01:00 +0000718 return RebaseRet(True, '', '')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000719 except subprocess2.CalledProcessError as cpe:
720 if abort:
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000721 run_with_retcode('rebase', '--abort') # ignore failure
Josip Sokcevic72f991f2020-04-23 18:53:30 +0000722 return RebaseRet(False, cpe.stdout.decode('utf-8', 'replace'),
723 cpe.stderr.decode('utf-8', 'replace'))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000724
725
726def remove_merge_base(branch):
727 del_branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000728 del_branch_config(branch, 'base-upstream')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000729
730
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000731def repo_root():
732 """Returns the absolute path to the repository root."""
733 return run('rev-parse', '--show-toplevel')
734
735
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000736def upstream_default():
737 """Returns the default branch name of the origin repository."""
738 try:
Josip Sokcevic06423732021-03-31 19:04:42 +0000739 ret = run('rev-parse', '--abbrev-ref', 'origin/HEAD')
740 # Detect if the repository migrated to main branch
741 if ret == 'origin/master':
742 try:
743 ret = run('rev-parse', '--abbrev-ref', 'origin/main')
744 run('remote', 'set-head', '-a', 'origin')
745 ret = run('rev-parse', '--abbrev-ref', 'origin/HEAD')
746 except subprocess2.CalledProcessError:
747 pass
748 return ret
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000749 except subprocess2.CalledProcessError:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +0000750 return 'origin/main'
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000751
752
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000753def root():
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000754 return get_config('depot-tools.upstream', upstream_default())
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000755
756
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000757@contextlib.contextmanager
758def less(): # pragma: no cover
759 """Runs 'less' as context manager yielding its stdin as a PIPE.
760
761 Automatically checks if sys.stdout is a non-TTY stream. If so, it avoids
762 running less and just yields sys.stdout.
Edward Lemur0d462e92020-01-08 20:11:31 +0000763
764 The returned PIPE is opened on binary mode.
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000765 """
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +0000766 if not setup_color.IS_TTY:
Edward Lemur5e94b802019-11-26 21:44:08 +0000767 # On Python 3, sys.stdout doesn't accept bytes, and sys.stdout.buffer must
768 # be used.
769 yield getattr(sys.stdout, 'buffer', sys.stdout)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000770 return
771
772 # Run with the same options that git uses (see setup_pager in git repo).
773 # -F: Automatically quit if the output is less than one screen.
774 # -R: Don't escape ANSI color codes.
775 # -X: Don't clear the screen before starting.
776 cmd = ('less', '-FRX')
777 try:
778 proc = subprocess2.Popen(cmd, stdin=subprocess2.PIPE)
779 yield proc.stdin
780 finally:
Edward Lemurb800fde2020-01-10 23:04:44 +0000781 try:
782 proc.stdin.close()
783 except BrokenPipeError:
784 # BrokenPipeError is raised if proc has already completed,
785 pass
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000786 proc.wait()
787
788
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000789def run(*cmd, **kwargs):
790 """The same as run_with_stderr, except it only returns stdout."""
791 return run_with_stderr(*cmd, **kwargs)[0]
792
793
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000794def run_with_retcode(*cmd, **kwargs):
795 """Run a command but only return the status code."""
796 try:
797 run(*cmd, **kwargs)
798 return 0
799 except subprocess2.CalledProcessError as cpe:
800 return cpe.returncode
801
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000802def run_stream(*cmd, **kwargs):
803 """Runs a git command. Returns stdout as a PIPE (file-like object).
804
805 stderr is dropped to avoid races if the process outputs to both stdout and
806 stderr.
807 """
Edward Lesmescf06cad2020-12-14 22:03:23 +0000808 kwargs.setdefault('stderr', subprocess2.DEVNULL)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000809 kwargs.setdefault('stdout', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000810 kwargs.setdefault('shell', False)
iannucci@chromium.org21980022014-04-11 04:51:49 +0000811 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000812 proc = subprocess2.Popen(cmd, **kwargs)
813 return proc.stdout
814
815
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000816@contextlib.contextmanager
817def run_stream_with_retcode(*cmd, **kwargs):
818 """Runs a git command as context manager yielding stdout as a PIPE.
819
820 stderr is dropped to avoid races if the process outputs to both stdout and
821 stderr.
822
823 Raises subprocess2.CalledProcessError on nonzero return code.
824 """
Edward Lesmescf06cad2020-12-14 22:03:23 +0000825 kwargs.setdefault('stderr', subprocess2.DEVNULL)
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000826 kwargs.setdefault('stdout', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000827 kwargs.setdefault('shell', False)
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000828 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
829 try:
830 proc = subprocess2.Popen(cmd, **kwargs)
831 yield proc.stdout
832 finally:
833 retcode = proc.wait()
834 if retcode != 0:
835 raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(),
Josip Sokcevic72f991f2020-04-23 18:53:30 +0000836 b'', b'')
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000837
838
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000839def run_with_stderr(*cmd, **kwargs):
840 """Runs a git command.
841
842 Returns (stdout, stderr) as a pair of strings.
843
844 kwargs
845 autostrip (bool) - Strip the output. Defaults to True.
846 indata (str) - Specifies stdin data for the process.
847 """
848 kwargs.setdefault('stdin', subprocess2.PIPE)
849 kwargs.setdefault('stdout', subprocess2.PIPE)
850 kwargs.setdefault('stderr', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000851 kwargs.setdefault('shell', False)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000852 autostrip = kwargs.pop('autostrip', True)
853 indata = kwargs.pop('indata', None)
Edward Lemur12a537f2019-10-03 21:57:15 +0000854 decode = kwargs.pop('decode', True)
Orr Bernsteinb7e16d22023-07-14 11:00:55 +0000855 accepted_retcodes = kwargs.pop('accepted_retcodes', [0])
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000856
iannucci@chromium.org21980022014-04-11 04:51:49 +0000857 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000858 proc = subprocess2.Popen(cmd, **kwargs)
859 ret, err = proc.communicate(indata)
860 retcode = proc.wait()
Orr Bernsteinb7e16d22023-07-14 11:00:55 +0000861 if retcode not in accepted_retcodes:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000862 raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(), ret, err)
863
864 if autostrip:
Edward Lemur12a537f2019-10-03 21:57:15 +0000865 ret = (ret or b'').strip()
866 err = (err or b'').strip()
867
868 if decode:
869 ret = ret.decode('utf-8', 'replace')
870 err = err.decode('utf-8', 'replace')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000871
872 return ret, err
873
874
875def set_branch_config(branch, option, value, scope='local'):
876 set_config('branch.%s.%s' % (branch, option), value, scope=scope)
877
878
879def set_config(option, value, scope='local'):
880 run('config', '--' + scope, option, value)
881
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000882
sbc@chromium.org71437c02015-04-09 19:29:40 +0000883def get_dirty_files():
884 # Make sure index is up-to-date before running diff-index.
885 run_with_retcode('update-index', '--refresh', '-q')
Eli Ribble54434e72019-05-24 00:41:15 +0000886 return run('diff-index', '--ignore-submodules', '--name-status', 'HEAD')
sbc@chromium.org71437c02015-04-09 19:29:40 +0000887
888
889def is_dirty_git_tree(cmd):
iannuccie38699b2016-08-15 17:32:31 -0700890 w = lambda s: sys.stderr.write(s+"\n")
891
sbc@chromium.org71437c02015-04-09 19:29:40 +0000892 dirty = get_dirty_files()
893 if dirty:
Josip Sokcevicfcf9fc42022-09-27 21:59:01 +0000894 w('Cannot %s with a dirty tree. Commit%s or stash your changes first.' %
895 (cmd, '' if cmd == 'upload' else ', freeze'))
iannuccie38699b2016-08-15 17:32:31 -0700896 w('Uncommitted files: (git diff-index --name-status HEAD)')
897 w(dirty[:4096])
sbc@chromium.org71437c02015-04-09 19:29:40 +0000898 if len(dirty) > 4096: # pragma: no cover
iannuccie38699b2016-08-15 17:32:31 -0700899 w('... (run "git diff-index --name-status HEAD" to see full output).')
sbc@chromium.org71437c02015-04-09 19:29:40 +0000900 return True
901 return False
902
903
Greg NISBET923bcf82023-08-10 22:50:46 +0000904def status(ignore_submodules=None):
agable02b3c982016-06-22 07:51:22 -0700905 """Returns a parsed version of git-status.
906
Greg NISBET923bcf82023-08-10 22:50:46 +0000907 Args:
908 ignore_submodules (str|None): "all", "none", or None.
909 None is equivalent to "none".
910
agable02b3c982016-06-22 07:51:22 -0700911 Returns a generator of (current_name, (lstat, rstat, src)) pairs where:
912 * current_name is the name of the file
913 * lstat is the left status code letter from git-status
Aravind Vasudevanc71efb52023-08-29 23:02:15 +0000914 * rstat is the right status code letter from git-status
agable02b3c982016-06-22 07:51:22 -0700915 * src is the current name of the file, or the original name of the file
916 if lstat == 'R'
917 """
Greg NISBET923bcf82023-08-10 22:50:46 +0000918
919 ignore_submodules = ignore_submodules or 'none'
920 assert ignore_submodules in (
921 'all', 'none'), f'ignore_submodules value {ignore_submodules} is invalid'
922
agable02b3c982016-06-22 07:51:22 -0700923 stat_entry = collections.namedtuple('stat_entry', 'lstat rstat src')
924
925 def tokenizer(stream):
Raul Tambrec2f74c12019-03-19 05:55:53 +0000926 acc = BytesIO()
agable02b3c982016-06-22 07:51:22 -0700927 c = None
Edward Lemur12a537f2019-10-03 21:57:15 +0000928 while c != b'':
agable02b3c982016-06-22 07:51:22 -0700929 c = stream.read(1)
Edward Lemur12a537f2019-10-03 21:57:15 +0000930 if c in (None, b'', b'\0'):
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000931 if len(acc.getvalue()) > 0:
agable02b3c982016-06-22 07:51:22 -0700932 yield acc.getvalue()
Raul Tambrec2f74c12019-03-19 05:55:53 +0000933 acc = BytesIO()
agable02b3c982016-06-22 07:51:22 -0700934 else:
935 acc.write(c)
936
937 def parser(tokens):
938 while True:
Edward Lemur12a537f2019-10-03 21:57:15 +0000939 try:
940 status_dest = next(tokens).decode('utf-8')
941 except StopIteration:
942 return
agable02b3c982016-06-22 07:51:22 -0700943 stat, dest = status_dest[:2], status_dest[3:]
944 lstat, rstat = stat
945 if lstat == 'R':
Edward Lemur12a537f2019-10-03 21:57:15 +0000946 src = next(tokens).decode('utf-8')
agable02b3c982016-06-22 07:51:22 -0700947 else:
948 src = dest
949 yield (dest, stat_entry(lstat, rstat, src))
950
Greg NISBET923bcf82023-08-10 22:50:46 +0000951 return parser(
952 tokenizer(
953 run_stream('status',
954 '-z',
955 f'--ignore-submodules={ignore_submodules}',
956 bufsize=-1)))
agable02b3c982016-06-22 07:51:22 -0700957
958
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000959def squash_current_branch(header=None, merge_base=None):
Alan Cutter00017822016-12-20 17:39:59 +1100960 header = header or 'git squash commit for %s.' % current_branch()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000961 merge_base = merge_base or get_or_create_merge_base(current_branch())
962 log_msg = header + '\n'
963 if log_msg:
964 log_msg += '\n'
965 log_msg += run('log', '--reverse', '--format=%H%n%B', '%s..HEAD' % merge_base)
966 run('reset', '--soft', merge_base)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000967
968 if not get_dirty_files():
969 # Sometimes the squash can result in the same tree, meaning that there is
970 # nothing to commit at this point.
Raul Tambrec2f74c12019-03-19 05:55:53 +0000971 print('Nothing to commit; squashed branch is empty')
sbc@chromium.org71437c02015-04-09 19:29:40 +0000972 return False
Edward Lemur71681bf2019-10-09 23:46:20 +0000973 run('commit', '--no-verify', '-a', '-F', '-', indata=log_msg.encode('utf-8'))
sbc@chromium.org71437c02015-04-09 19:29:40 +0000974 return True
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000975
976
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000977def tags(*args):
978 return run('tag', *args).splitlines()
979
980
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000981def thaw():
982 took_action = False
Bruce Dawson4082f882023-05-15 17:14:17 +0000983 with run_stream('rev-list', 'HEAD') as stream:
984 for sha in stream:
985 sha = sha.strip().decode('utf-8')
986 msg = run('show', '--format=%f%b', '-s', 'HEAD')
987 match = FREEZE_MATCHER.match(msg)
988 if not match:
989 if not took_action:
990 return 'Nothing to thaw.'
991 break
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000992
Bruce Dawson4082f882023-05-15 17:14:17 +0000993 run('reset', '--' + FREEZE_SECTIONS[match.group(1)], sha)
994 took_action = True
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000995
996
997def topo_iter(branch_tree, top_down=True):
998 """Generates (branch, parent) in topographical order for a branch tree.
999
1000 Given a tree:
1001
1002 A1
1003 B1 B2
1004 C1 C2 C3
1005 D1
1006
1007 branch_tree would look like: {
1008 'D1': 'C3',
1009 'C3': 'B2',
1010 'B2': 'A1',
1011 'C1': 'B1',
1012 'C2': 'B1',
1013 'B1': 'A1',
1014 }
1015
1016 It is OK to have multiple 'root' nodes in your graph.
1017
1018 if top_down is True, items are yielded from A->D. Otherwise they're yielded
1019 from D->A. Within a layer the branches will be yielded in sorted order.
1020 """
1021 branch_tree = branch_tree.copy()
1022
1023 # TODO(iannucci): There is probably a more efficient way to do these.
1024 if top_down:
1025 while branch_tree:
Edward Lemur12a537f2019-10-03 21:57:15 +00001026 this_pass = [(b, p) for b, p in branch_tree.items()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001027 if p not in branch_tree]
1028 assert this_pass, "Branch tree has cycles: %r" % branch_tree
1029 for branch, parent in sorted(this_pass):
1030 yield branch, parent
1031 del branch_tree[branch]
1032 else:
1033 parent_to_branches = collections.defaultdict(set)
Edward Lemur12a537f2019-10-03 21:57:15 +00001034 for branch, parent in branch_tree.items():
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001035 parent_to_branches[parent].add(branch)
1036
1037 while branch_tree:
Edward Lemur12a537f2019-10-03 21:57:15 +00001038 this_pass = [(b, p) for b, p in branch_tree.items()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001039 if not parent_to_branches[b]]
1040 assert this_pass, "Branch tree has cycles: %r" % branch_tree
1041 for branch, parent in sorted(this_pass):
1042 yield branch, parent
1043 parent_to_branches[parent].discard(branch)
1044 del branch_tree[branch]
1045
1046
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +00001047def tree(treeref, recurse=False):
1048 """Returns a dict representation of a git tree object.
1049
1050 Args:
1051 treeref (str) - a git ref which resolves to a tree (commits count as trees).
qyearsley12fa6ff2016-08-24 09:18:40 -07001052 recurse (bool) - include all of the tree's descendants too. File names will
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +00001053 take the form of 'some/path/to/file'.
1054
1055 Return format:
1056 { 'file_name': (mode, type, ref) }
1057
1058 mode is an integer where:
1059 * 0040000 - Directory
1060 * 0100644 - Regular non-executable file
1061 * 0100664 - Regular non-executable group-writeable file
1062 * 0100755 - Regular executable file
1063 * 0120000 - Symbolic link
1064 * 0160000 - Gitlink
1065
1066 type is a string where it's one of 'blob', 'commit', 'tree', 'tag'.
1067
1068 ref is the hex encoded hash of the entry.
1069 """
1070 ret = {}
1071 opts = ['ls-tree', '--full-tree']
1072 if recurse:
1073 opts.append('-r')
1074 opts.append(treeref)
1075 try:
1076 for line in run(*opts).splitlines():
1077 mode, typ, ref, name = line.split(None, 3)
1078 ret[name] = (mode, typ, ref)
1079 except subprocess2.CalledProcessError:
1080 return None
1081 return ret
1082
1083
Mun Yong Jang781e71e2017-10-25 15:46:20 -07001084def get_remote_url(remote='origin'):
1085 try:
1086 return run('config', 'remote.%s.url' % remote)
1087 except subprocess2.CalledProcessError:
1088 return None
1089
1090
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +00001091def upstream(branch):
1092 try:
1093 return run('rev-parse', '--abbrev-ref', '--symbolic-full-name',
1094 branch+'@{upstream}')
1095 except subprocess2.CalledProcessError:
1096 return None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001097
agable@chromium.orgd629fb42014-10-01 09:40:10 +00001098
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001099def get_git_version():
1100 """Returns a tuple that contains the numeric components of the current git
1101 version."""
1102 version_string = run('--version')
1103 version_match = re.search(r'(\d+.)+(\d+)', version_string)
1104 version = version_match.group() if version_match else ''
1105
1106 return tuple(int(x) for x in version.split('.'))
1107
1108
calamity@chromium.org745ffa62014-09-08 01:03:19 +00001109def get_branches_info(include_tracking_status):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001110 format_string = (
1111 '--format=%(refname:short):%(objectname:short):%(upstream:short):')
1112
1113 # This is not covered by the depot_tools CQ which only has git version 1.8.
calamity@chromium.org745ffa62014-09-08 01:03:19 +00001114 if (include_tracking_status and
1115 get_git_version() >= MIN_UPSTREAM_TRACK_GIT_VERSION): # pragma: no cover
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001116 format_string += '%(upstream:track)'
1117
1118 info_map = {}
1119 data = run('for-each-ref', format_string, 'refs/heads')
calamity@chromium.org745ffa62014-09-08 01:03:19 +00001120 BranchesInfo = collections.namedtuple(
Gavin Mak8d7201b2020-09-17 19:21:38 +00001121 'BranchesInfo', 'hash upstream commits behind')
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001122 for line in data.splitlines():
1123 (branch, branch_hash, upstream_branch, tracking_status) = line.split(':')
1124
Gavin Mak8d7201b2020-09-17 19:21:38 +00001125 commits = None
Antonio Sartorie0dff202021-02-18 06:33:50 +00001126 if include_tracking_status:
1127 base = get_or_create_merge_base(branch)
1128 if base:
1129 commits_list = run('rev-list', '--count', branch, '^%s' % base, '--')
1130 commits = int(commits_list) or None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001131
1132 behind_match = re.search(r'behind (\d+)', tracking_status)
1133 behind = int(behind_match.group(1)) if behind_match else None
1134
calamity@chromium.org745ffa62014-09-08 01:03:19 +00001135 info_map[branch] = BranchesInfo(
Robert Iannuccid3acb162021-05-04 21:37:40 +00001136 hash=branch_hash, upstream=upstream_branch, commits=commits,
Gavin Mak8d7201b2020-09-17 19:21:38 +00001137 behind=behind)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001138
1139 # Set None for upstreams which are not branches (e.g empty upstream, remotes
1140 # and deleted upstream branches).
1141 missing_upstreams = {}
1142 for info in info_map.values():
1143 if info.upstream not in info_map and info.upstream not in missing_upstreams:
1144 missing_upstreams[info.upstream] = None
1145
Edward Lemur12a537f2019-10-03 21:57:15 +00001146 result = info_map.copy()
1147 result.update(missing_upstreams)
1148 return result
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001149
1150
1151def make_workdir_common(repository, new_workdir, files_to_symlink,
scottmg@chromium.orgd4218d42015-10-07 23:49:20 +00001152 files_to_copy, symlink=None):
1153 if not symlink:
1154 symlink = os.symlink
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001155 os.makedirs(new_workdir)
1156 for entry in files_to_symlink:
scottmg@chromium.orgd4218d42015-10-07 23:49:20 +00001157 clone_file(repository, new_workdir, entry, symlink)
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001158 for entry in files_to_copy:
1159 clone_file(repository, new_workdir, entry, shutil.copy)
1160
1161
1162def make_workdir(repository, new_workdir):
1163 GIT_DIRECTORY_WHITELIST = [
1164 'config',
1165 'info',
1166 'hooks',
1167 'logs/refs',
1168 'objects',
1169 'packed-refs',
1170 'refs',
1171 'remotes',
1172 'rr-cache',
Richard He42033b22020-05-22 03:03:45 +00001173 'shallow',
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001174 ]
1175 make_workdir_common(repository, new_workdir, GIT_DIRECTORY_WHITELIST,
1176 ['HEAD'])
1177
1178
1179def clone_file(repository, new_workdir, link, operation):
1180 if not os.path.exists(os.path.join(repository, link)):
1181 return
1182 link_dir = os.path.dirname(os.path.join(new_workdir, link))
1183 if not os.path.exists(link_dir):
1184 os.makedirs(link_dir)
Henrique Ferreirofd4ad242018-01-10 12:19:18 +01001185 src = os.path.join(repository, link)
1186 if os.path.islink(src):
Henrique Ferreiroaea45d22018-02-19 09:48:36 +01001187 src = os.path.realpath(src)
Henrique Ferreirofd4ad242018-01-10 12:19:18 +01001188 operation(src, os.path.join(new_workdir, link))