blob: 3079b02e6c5418d49fbeca22e86a03b3d9e94f77 [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 Mak42674f52023-08-24 20:39:59 +000019 default_timeout = (1 << 31 if sys.version_info.major == 2 else
20 threading.TIMEOUT_MAX)
21 return func(self, timeout=timeout or default_timeout)
Josip Sokcevicde6c4562020-03-26 00:39:42 +000022
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000023 return wrap
24IMapIterator.next = wrapper(IMapIterator.next)
25IMapIterator.__next__ = IMapIterator.next
26# TODO(iannucci): Monkeypatch all other 'wait' methods too.
27
28
29import binascii
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000030import collections
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000031import contextlib
32import functools
33import logging
iannucci@chromium.org97345eb2014-03-13 07:55:15 +000034import os
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000035import re
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +000036import setup_color
sammc@chromium.org900a33f2015-09-29 06:57:09 +000037import shutil
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000038import signal
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000039import tempfile
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +000040import textwrap
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000041
42import subprocess2
43
Raul Tambrec2f74c12019-03-19 05:55:53 +000044from io import BytesIO
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000045
agable02b3c982016-06-22 07:51:22 -070046
47ROOT = os.path.abspath(os.path.dirname(__file__))
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +000048IS_WIN = sys.platform == 'win32'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000049TEST_MODE = False
50
Dan Jacques209a6812017-07-12 11:40:20 -070051
52def win_find_git():
53 for elem in os.environ.get('PATH', '').split(os.pathsep):
54 for candidate in ('git.exe', 'git.bat'):
55 path = os.path.join(elem, candidate)
56 if os.path.isfile(path):
57 return path
58 raise ValueError('Could not find Git on PATH.')
59
60
61GIT_EXE = 'git' if not IS_WIN else win_find_git()
62
63
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000064FREEZE = 'FREEZE'
65FREEZE_SECTIONS = {
66 'indexed': 'soft',
67 'unindexed': 'mixed'
68}
69FREEZE_MATCHER = re.compile(r'%s.(%s)' % (FREEZE, '|'.join(FREEZE_SECTIONS)))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000070
71
Dan Jacques2f8b0c12017-04-05 12:57:21 -070072# NOTE: This list is DEPRECATED in favor of the Infra Git wrapper:
Josip Sokcevic9c0dc302020-11-20 18:41:25 +000073# https://chromium.googlesource.com/infra/infra/+/HEAD/go/src/infra/tools/git
Dan Jacques2f8b0c12017-04-05 12:57:21 -070074#
75# New entries should be added to the Git wrapper, NOT to this list. "git_retry"
76# is, similarly, being deprecated in favor of the Git wrapper.
77#
78# ---
79#
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000080# Retry a git operation if git returns a error response with any of these
81# messages. It's all observed 'bad' GoB responses so far.
82#
83# This list is inspired/derived from the one in ChromiumOS's Chromite:
84# <CHROMITE>/lib/git.py::GIT_TRANSIENT_ERRORS
85#
86# It was last imported from '7add3ac29564d98ac35ce426bc295e743e7c0c02'.
87GIT_TRANSIENT_ERRORS = (
88 # crbug.com/285832
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000089 r'!.*\[remote rejected\].*\(error in hook\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000090
91 # crbug.com/289932
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000092 r'!.*\[remote rejected\].*\(failed to lock\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000093
94 # crbug.com/307156
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000095 r'!.*\[remote rejected\].*\(error in Gerrit backend\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000096
97 # crbug.com/285832
98 r'remote error: Internal Server Error',
99
100 # crbug.com/294449
101 r'fatal: Couldn\'t find remote ref ',
102
103 # crbug.com/220543
104 r'git fetch_pack: expected ACK/NAK, got',
105
106 # crbug.com/189455
107 r'protocol error: bad pack header',
108
109 # crbug.com/202807
110 r'The remote end hung up unexpectedly',
111
112 # crbug.com/298189
113 r'TLS packet with unexpected length was received',
114
115 # crbug.com/187444
116 r'RPC failed; result=\d+, HTTP code = \d+',
117
dnj@chromium.orgde219ec2014-07-28 17:39:08 +0000118 # crbug.com/388876
119 r'Connection timed out',
dnj@chromium.org45cddd62014-11-06 19:36:42 +0000120
121 # crbug.com/430343
122 # TODO(dnj): Resync with Chromite.
123 r'The requested URL returned error: 5\d+',
Arikonb3a21482016-07-22 10:12:24 -0700124
125 r'Connection reset by peer',
126
127 r'Unable to look up',
128
129 r'Couldn\'t resolve host',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +0000130)
131
132GIT_TRANSIENT_ERRORS_RE = re.compile('|'.join(GIT_TRANSIENT_ERRORS),
133 re.IGNORECASE)
134
raphael.kubo.da.costa@intel.com58d05b02015-06-24 08:54:41 +0000135# git's for-each-ref command first supported the upstream:track token in its
136# format string in version 1.9.0, but some usages were broken until 2.3.0.
137# See git commit b6160d95 for more information.
138MIN_UPSTREAM_TRACK_GIT_VERSION = (2, 3)
dnj@chromium.orgde219ec2014-07-28 17:39:08 +0000139
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000140class BadCommitRefException(Exception):
141 def __init__(self, refs):
142 msg = ('one of %s does not seem to be a valid commitref.' %
143 str(refs))
144 super(BadCommitRefException, self).__init__(msg)
145
146
147def memoize_one(**kwargs):
148 """Memoizes a single-argument pure function.
149
150 Values of None are not cached.
151
152 Kwargs:
153 threadsafe (bool) - REQUIRED. Specifies whether to use locking around
154 cache manipulation functions. This is a kwarg so that users of memoize_one
155 are forced to explicitly and verbosely pick True or False.
156
157 Adds three methods to the decorated function:
158 * get(key, default=None) - Gets the value for this key from the cache.
159 * set(key, value) - Sets the value for this key from the cache.
160 * clear() - Drops the entire contents of the cache. Useful for unittests.
161 * update(other) - Updates the contents of the cache from another dict.
162 """
163 assert 'threadsafe' in kwargs, 'Must specify threadsafe={True,False}'
164 threadsafe = kwargs['threadsafe']
165
166 if threadsafe:
167 def withlock(lock, f):
168 def inner(*args, **kwargs):
169 with lock:
170 return f(*args, **kwargs)
171 return inner
172 else:
173 def withlock(_lock, f):
174 return f
175
176 def decorator(f):
177 # Instantiate the lock in decorator, in case users of memoize_one do:
178 #
179 # memoizer = memoize_one(threadsafe=True)
180 #
181 # @memoizer
182 # def fn1(val): ...
183 #
184 # @memoizer
185 # def fn2(val): ...
186
187 lock = threading.Lock() if threadsafe else None
188 cache = {}
189 _get = withlock(lock, cache.get)
190 _set = withlock(lock, cache.__setitem__)
191
192 @functools.wraps(f)
193 def inner(arg):
194 ret = _get(arg)
195 if ret is None:
196 ret = f(arg)
197 if ret is not None:
198 _set(arg, ret)
199 return ret
200 inner.get = _get
201 inner.set = _set
202 inner.clear = withlock(lock, cache.clear)
203 inner.update = withlock(lock, cache.update)
204 return inner
205 return decorator
206
207
208def _ScopedPool_initer(orig, orig_args): # pragma: no cover
209 """Initializer method for ScopedPool's subprocesses.
210
211 This helps ScopedPool handle Ctrl-C's correctly.
212 """
213 signal.signal(signal.SIGINT, signal.SIG_IGN)
214 if orig:
215 orig(*orig_args)
216
217
218@contextlib.contextmanager
219def ScopedPool(*args, **kwargs):
220 """Context Manager which returns a multiprocessing.pool instance which
221 correctly deals with thrown exceptions.
222
223 *args - Arguments to multiprocessing.pool
224
225 Kwargs:
226 kind ('threads', 'procs') - The type of underlying coprocess to use.
227 **etc - Arguments to multiprocessing.pool
228 """
229 if kwargs.pop('kind', None) == 'threads':
230 pool = multiprocessing.pool.ThreadPool(*args, **kwargs)
231 else:
232 orig, orig_args = kwargs.get('initializer'), kwargs.get('initargs', ())
233 kwargs['initializer'] = _ScopedPool_initer
234 kwargs['initargs'] = orig, orig_args
235 pool = multiprocessing.pool.Pool(*args, **kwargs)
236
237 try:
238 yield pool
239 pool.close()
240 except:
241 pool.terminate()
242 raise
243 finally:
244 pool.join()
245
246
247class ProgressPrinter(object):
248 """Threaded single-stat status message printer."""
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000249 def __init__(self, fmt, enabled=None, fout=sys.stderr, period=0.5):
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000250 """Create a ProgressPrinter.
251
252 Use it as a context manager which produces a simple 'increment' method:
253
254 with ProgressPrinter('(%%(count)d/%d)' % 1000) as inc:
255 for i in xrange(1000):
256 # do stuff
257 if i % 10 == 0:
258 inc(10)
259
260 Args:
261 fmt - String format with a single '%(count)d' where the counter value
262 should go.
263 enabled (bool) - If this is None, will default to True if
264 logging.getLogger() is set to INFO or more verbose.
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000265 fout (file-like) - The stream to print status messages to.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000266 period (float) - The time in seconds for the printer thread to wait
267 between printing.
268 """
269 self.fmt = fmt
270 if enabled is None: # pragma: no cover
271 self.enabled = logging.getLogger().isEnabledFor(logging.INFO)
272 else:
273 self.enabled = enabled
274
275 self._count = 0
276 self._dead = False
277 self._dead_cond = threading.Condition()
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000278 self._stream = fout
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000279 self._thread = threading.Thread(target=self._run)
280 self._period = period
281
282 def _emit(self, s):
283 if self.enabled:
284 self._stream.write('\r' + s)
285 self._stream.flush()
286
287 def _run(self):
288 with self._dead_cond:
289 while not self._dead:
290 self._emit(self.fmt % {'count': self._count})
291 self._dead_cond.wait(self._period)
292 self._emit((self.fmt + '\n') % {'count': self._count})
293
294 def inc(self, amount=1):
295 self._count += amount
296
297 def __enter__(self):
298 self._thread.start()
299 return self.inc
300
301 def __exit__(self, _exc_type, _exc_value, _traceback):
302 self._dead = True
303 with self._dead_cond:
304 self._dead_cond.notifyAll()
305 self._thread.join()
306 del self._thread
307
308
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000309def once(function):
310 """@Decorates |function| so that it only performs its action once, no matter
311 how many times the decorated |function| is called."""
Edward Lemur12a537f2019-10-03 21:57:15 +0000312 has_run = [False]
313 def _wrapper(*args, **kwargs):
314 if not has_run[0]:
315 has_run[0] = True
316 function(*args, **kwargs)
317 return _wrapper
318
319
320def unicode_repr(s):
321 result = repr(s)
322 return result[1:] if result.startswith('u') else result
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000323
324
325## Git functions
326
agable7aa2ddd2016-06-21 07:47:00 -0700327def die(message, *args):
Raul Tambrec2f74c12019-03-19 05:55:53 +0000328 print(textwrap.dedent(message % args), file=sys.stderr)
agable7aa2ddd2016-06-21 07:47:00 -0700329 sys.exit(1)
330
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000331
Mark Mentovaif548d082017-03-08 13:32:00 -0500332def blame(filename, revision=None, porcelain=False, abbrev=None, *_args):
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000333 command = ['blame']
334 if porcelain:
335 command.append('-p')
336 if revision is not None:
337 command.append(revision)
Mark Mentovaif548d082017-03-08 13:32:00 -0500338 if abbrev is not None:
339 command.append('--abbrev=%d' % abbrev)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000340 command.extend(['--', filename])
341 return run(*command)
342
343
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000344def branch_config(branch, option, default=None):
agable7aa2ddd2016-06-21 07:47:00 -0700345 return get_config('branch.%s.%s' % (branch, option), default=default)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000346
347
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000348def branch_config_map(option):
349 """Return {branch: <|option| value>} for all branches."""
350 try:
351 reg = re.compile(r'^branch\.(.*)\.%s$' % option)
agable7aa2ddd2016-06-21 07:47:00 -0700352 lines = get_config_regexp(reg.pattern)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000353 return {reg.match(k).group(1): v for k, v in (l.split() for l in lines)}
354 except subprocess2.CalledProcessError:
355 return {}
356
357
Francois Dorayd42c6812017-05-30 15:10:20 -0400358def branches(use_limit=True, *args):
akuegel@chromium.org58888e12015-06-09 15:26:37 +0000359 NO_BRANCH = ('* (no branch', '* (detached', '* (HEAD detached')
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000360
361 key = 'depot-tools.branch-limit'
agable7aa2ddd2016-06-21 07:47:00 -0700362 limit = get_config_int(key, 20)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000363
364 raw_branches = run('branch', *args).splitlines()
365
366 num = len(raw_branches)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000367
Francois Dorayd42c6812017-05-30 15:10:20 -0400368 if use_limit and num > limit:
agable7aa2ddd2016-06-21 07:47:00 -0700369 die("""\
370 Your git repo has too many branches (%d/%d) for this tool to work well.
371
372 You may adjust this limit by running:
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000373 git config %s <new_limit>
agable7aa2ddd2016-06-21 07:47:00 -0700374
375 You may also try cleaning up your old branches by running:
376 git cl archive
377 """, num, limit, key)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000378
379 for line in raw_branches:
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000380 if line.startswith(NO_BRANCH):
381 continue
382 yield line.split()[-1]
383
384
agable7aa2ddd2016-06-21 07:47:00 -0700385def get_config(option, default=None):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000386 try:
387 return run('config', '--get', option) or default
388 except subprocess2.CalledProcessError:
389 return default
390
391
agable7aa2ddd2016-06-21 07:47:00 -0700392def get_config_int(option, default=0):
393 assert isinstance(default, int)
394 try:
395 return int(get_config(option, default))
396 except ValueError:
397 return default
398
399
400def get_config_list(option):
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000401 try:
402 return run('config', '--get-all', option).split()
403 except subprocess2.CalledProcessError:
404 return []
405
406
agable7aa2ddd2016-06-21 07:47:00 -0700407def get_config_regexp(pattern):
408 if IS_WIN: # pragma: no cover
409 # this madness is because we call git.bat which calls git.exe which calls
410 # bash.exe (or something to that effect). Each layer divides the number of
411 # ^'s by 2.
412 pattern = pattern.replace('^', '^' * 8)
413 return run('config', '--get-regexp', pattern).splitlines()
414
415
Aravind Vasudevanb8164182023-08-25 21:49:12 +0000416def is_fsmonitor_enabled():
417 """Returns true if core.fsmonitor is enabled in git config."""
418 fsmonitor = get_config('core.fsmonitor', 'False')
419 return fsmonitor.strip().lower() == 'true'
420
421
422def warn_submodule():
423 """Print warnings for submodules."""
424 # TODO(crbug.com/1475405): Warn users if the project uses submodules and
425 # they have fsmonitor enabled.
426 if is_fsmonitor_enabled():
427 print(colorama.Fore.RED)
428 print('WARNING: You have fsmonitor enabled. There is a major issue '
429 'resulting in git diff-index returning wrong results. Please '
430 'disable it by running:')
431 print(' git config --global core.fsmonitor false')
432 print('We will remove this warning once https://crbug.com/1475405 is '
433 'fixed.')
434 print(colorama.Style.RESET_ALL)
435
436
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000437def current_branch():
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000438 try:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000439 return run('rev-parse', '--abbrev-ref', 'HEAD')
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000440 except subprocess2.CalledProcessError:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000441 return None
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000442
443
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000444def del_branch_config(branch, option, scope='local'):
445 del_config('branch.%s.%s' % (branch, option), scope=scope)
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000446
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000447
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000448def del_config(option, scope='local'):
449 try:
450 run('config', '--' + scope, '--unset', option)
451 except subprocess2.CalledProcessError:
452 pass
453
454
mgiuca@chromium.org01d2cde2016-02-05 03:25:41 +0000455def diff(oldrev, newrev, *args):
456 return run('diff', oldrev, newrev, *args)
457
458
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000459def freeze():
460 took_action = False
agable02b3c982016-06-22 07:51:22 -0700461 key = 'depot-tools.freeze-size-limit'
462 MB = 2**20
463 limit_mb = get_config_int(key, 100)
464 untracked_bytes = 0
465
iannuccieaca0332016-08-03 16:46:50 -0700466 root_path = repo_root()
467
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000468 # unindexed tracks all the files which are unindexed but we want to add to
469 # the `FREEZE.unindexed` commit.
470 unindexed = []
471
472 # will be set to true if there are any indexed files to commit.
473 have_indexed_files = False
474
Joanna Wang25410062023-08-10 23:28:44 +0000475 for f, s in status(ignore_submodules='all'):
agable02b3c982016-06-22 07:51:22 -0700476 if is_unmerged(s):
477 die("Cannot freeze unmerged changes!")
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000478 if s.lstat not in ' ?':
479 # This covers all changes to indexed files.
480 # lstat = ' ' means that the file is tracked and modified, but wasn't
481 # added yet.
482 # lstat = '?' means that the file is untracked.
483 have_indexed_files = True
484 else:
485 unindexed.append(f.encode('utf-8'))
486 if s.lstat == '?' and limit_mb > 0:
487 untracked_bytes += os.lstat(os.path.join(root_path, f)).st_size
488
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800489 if limit_mb > 0 and untracked_bytes > limit_mb * MB:
490 die("""\
491 You appear to have too much untracked+unignored data in your git
492 checkout: %.1f / %d MB.
agable02b3c982016-06-22 07:51:22 -0700493
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800494 Run `git status` to see what it is.
agable02b3c982016-06-22 07:51:22 -0700495
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800496 In addition to making many git commands slower, this will prevent
497 depot_tools from freezing your in-progress changes.
agable02b3c982016-06-22 07:51:22 -0700498
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800499 You should add untracked data that you want to ignore to your repo's
500 .git/info/exclude
501 file. See `git help ignore` for the format of this file.
agable02b3c982016-06-22 07:51:22 -0700502
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000503 If this data is intended as part of your commit, you may adjust the
Bruce Dawson4bff3fd2018-01-04 14:44:23 -0800504 freeze limit by running:
505 git config %s <new_limit>
506 Where <new_limit> is an integer threshold in megabytes.""",
507 untracked_bytes / (MB * 1.0), limit_mb, key)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000508
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000509 if have_indexed_files:
510 try:
511 run('commit', '--no-verify', '-m', f'{FREEZE}.indexed')
512 took_action = True
513 except subprocess2.CalledProcessError:
514 pass
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000515
agable96e179b2016-06-24 10:32:51 -0700516 add_errors = False
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000517 if unindexed:
518 try:
519 run('add',
520 '--pathspec-from-file',
521 '-',
522 '--ignore-errors',
Robert Iannucci2f0147a2023-07-20 16:41:59 +0000523 indata=b'\n'.join(unindexed),
524 cwd=root_path)
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000525 except subprocess2.CalledProcessError:
526 add_errors = True
agable96e179b2016-06-24 10:32:51 -0700527
Robert Iannucci4e87f5b2023-07-13 19:51:33 +0000528 try:
529 run('commit', '--no-verify', '-m', f'{FREEZE}.unindexed')
530 took_action = True
531 except subprocess2.CalledProcessError:
532 pass
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000533
agable96e179b2016-06-24 10:32:51 -0700534 ret = []
535 if add_errors:
536 ret.append('Failed to index some unindexed files.')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000537 if not took_action:
agable96e179b2016-06-24 10:32:51 -0700538 ret.append('Nothing to freeze.')
539 return ' '.join(ret) or None
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000540
541
Gavin Mak2cbe95c2023-03-06 22:39:56 +0000542def get_branch_tree(use_limit=False):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000543 """Get the dictionary of {branch: parent}, compatible with topo_iter.
544
545 Returns a tuple of (skipped, <branch_tree dict>) where skipped is a set of
546 branches without upstream branches defined.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000547 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000548 skipped = set()
549 branch_tree = {}
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000550
Gavin Mak2cbe95c2023-03-06 22:39:56 +0000551 for branch in branches(use_limit=use_limit):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000552 parent = upstream(branch)
553 if not parent:
554 skipped.add(branch)
555 continue
556 branch_tree[branch] = parent
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000557
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000558 return skipped, branch_tree
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000559
560
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000561def get_or_create_merge_base(branch, parent=None):
562 """Finds the configured merge base for branch.
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000563
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000564 If parent is supplied, it's used instead of calling upstream(branch).
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000565 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000566 base = branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000567 base_upstream = branch_config(branch, 'base-upstream')
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000568 parent = parent or upstream(branch)
sbc@chromium.org79706062015-01-14 21:18:12 +0000569 if parent is None or branch is None:
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000570 return None
Josip Sokcevica3d1aaf2021-07-16 18:26:45 +0000571 actual_merge_base = run('merge-base', parent, branch)
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000572
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000573 if base_upstream != parent:
574 base = None
575 base_upstream = None
576
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000577 def is_ancestor(a, b):
578 return run_with_retcode('merge-base', '--is-ancestor', a, b) == 0
579
clemensh@chromium.orgc3fe99d2016-04-19 08:39:55 +0000580 if base and base != actual_merge_base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000581 if not is_ancestor(base, branch):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000582 logging.debug('Found WRONG pre-set merge-base for %s: %s', branch, base)
583 base = None
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000584 elif is_ancestor(base, actual_merge_base):
585 logging.debug('Found OLD pre-set merge-base for %s: %s', branch, base)
586 base = None
587 else:
588 logging.debug('Found pre-set merge-base for %s: %s', branch, base)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000589
590 if not base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000591 base = actual_merge_base
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000592 manual_merge_base(branch, base, parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000593
594 return base
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000595
596
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000597def hash_multi(*reflike):
598 return run('rev-parse', *reflike).splitlines()
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000599
600
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000601def hash_one(reflike, short=False):
602 args = ['rev-parse', reflike]
603 if short:
604 args.insert(1, '--short')
605 return run(*args)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000606
607
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000608def in_rebase():
609 git_dir = run('rev-parse', '--git-dir')
610 return (
611 os.path.exists(os.path.join(git_dir, 'rebase-merge')) or
612 os.path.exists(os.path.join(git_dir, 'rebase-apply')))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000613
614
615def intern_f(f, kind='blob'):
616 """Interns a file object into the git object store.
617
618 Args:
619 f (file-like object) - The file-like object to intern
620 kind (git object type) - One of 'blob', 'commit', 'tree', 'tag'.
621
622 Returns the git hash of the interned object (hex encoded).
623 """
624 ret = run('hash-object', '-t', kind, '-w', '--stdin', stdin=f)
625 f.close()
626 return ret
627
628
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000629def is_dormant(branch):
630 # TODO(iannucci): Do an oldness check?
631 return branch_config(branch, 'dormant', 'false') != 'false'
632
633
agable02b3c982016-06-22 07:51:22 -0700634def is_unmerged(stat_value):
635 return (
636 'U' in (stat_value.lstat, stat_value.rstat) or
637 ((stat_value.lstat == stat_value.rstat) and stat_value.lstat in 'AD')
638 )
639
640
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000641def manual_merge_base(branch, base, parent):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000642 set_branch_config(branch, 'base', base)
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000643 set_branch_config(branch, 'base-upstream', parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000644
645
646def mktree(treedict):
647 """Makes a git tree object and returns its hash.
648
649 See |tree()| for the values of mode, type, and ref.
650
651 Args:
652 treedict - { name: (mode, type, ref) }
653 """
654 with tempfile.TemporaryFile() as f:
Edward Lemur12a537f2019-10-03 21:57:15 +0000655 for name, (mode, typ, ref) in treedict.items():
Edward Lemur71681bf2019-10-09 23:46:20 +0000656 f.write(('%s %s %s\t%s\0' % (mode, typ, ref, name)).encode('utf-8'))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000657 f.seek(0)
658 return run('mktree', '-z', stdin=f)
659
660
661def parse_commitrefs(*commitrefs):
662 """Returns binary encoded commit hashes for one or more commitrefs.
663
664 A commitref is anything which can resolve to a commit. Popular examples:
665 * 'HEAD'
Josip Sokcevic9c0dc302020-11-20 18:41:25 +0000666 * 'origin/main'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000667 * 'cool_branch~2'
668 """
669 try:
Edward Lemur12a537f2019-10-03 21:57:15 +0000670 return [binascii.unhexlify(h) for h in hash_multi(*commitrefs)]
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000671 except subprocess2.CalledProcessError:
672 raise BadCommitRefException(commitrefs)
673
674
sbc@chromium.org384039b2014-10-13 21:01:00 +0000675RebaseRet = collections.namedtuple('RebaseRet', 'success stdout stderr')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000676
677
Robert Iannuccid3acb162021-05-04 21:37:40 +0000678def rebase(parent, start, branch, abort=False, allow_gc=False):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000679 """Rebases |start|..|branch| onto the branch |parent|.
680
Robert Iannuccid3acb162021-05-04 21:37:40 +0000681 Sets 'gc.auto=0' for the duration of this call to prevent the rebase from
682 running a potentially slow garbage collection cycle.
683
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000684 Args:
685 parent - The new parent ref for the rebased commits.
686 start - The commit to start from
687 branch - The branch to rebase
688 abort - If True, will call git-rebase --abort in the event that the rebase
689 doesn't complete successfully.
Robert Iannuccid3acb162021-05-04 21:37:40 +0000690 allow_gc - If True, sets "-c gc.auto=1" on the rebase call, rather than
691 "-c gc.auto=0". Usually if you're doing a series of rebases,
692 you'll only want to run a single gc pass at the end of all the
693 rebase activity.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000694
695 Returns a namedtuple with fields:
696 success - a boolean indicating that the rebase command completed
697 successfully.
698 message - if the rebase failed, this contains the stdout of the failed
699 rebase.
700 """
701 try:
Robert Iannuccid3acb162021-05-04 21:37:40 +0000702 args = [
703 '-c', 'gc.auto={}'.format('1' if allow_gc else '0'),
704 'rebase',
705 ]
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000706 if TEST_MODE:
Robert Iannuccid3acb162021-05-04 21:37:40 +0000707 args.append('--committer-date-is-author-date')
708 args += [
709 '--onto', parent, start, branch,
710 ]
711 run(*args)
sbc@chromium.org384039b2014-10-13 21:01:00 +0000712 return RebaseRet(True, '', '')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000713 except subprocess2.CalledProcessError as cpe:
714 if abort:
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000715 run_with_retcode('rebase', '--abort') # ignore failure
Josip Sokcevic72f991f2020-04-23 18:53:30 +0000716 return RebaseRet(False, cpe.stdout.decode('utf-8', 'replace'),
717 cpe.stderr.decode('utf-8', 'replace'))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000718
719
720def remove_merge_base(branch):
721 del_branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000722 del_branch_config(branch, 'base-upstream')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000723
724
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000725def repo_root():
726 """Returns the absolute path to the repository root."""
727 return run('rev-parse', '--show-toplevel')
728
729
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000730def upstream_default():
731 """Returns the default branch name of the origin repository."""
732 try:
Josip Sokcevic06423732021-03-31 19:04:42 +0000733 ret = run('rev-parse', '--abbrev-ref', 'origin/HEAD')
734 # Detect if the repository migrated to main branch
735 if ret == 'origin/master':
736 try:
737 ret = run('rev-parse', '--abbrev-ref', 'origin/main')
738 run('remote', 'set-head', '-a', 'origin')
739 ret = run('rev-parse', '--abbrev-ref', 'origin/HEAD')
740 except subprocess2.CalledProcessError:
741 pass
742 return ret
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000743 except subprocess2.CalledProcessError:
Josip Sokcevic7e133ff2021-07-13 17:44:53 +0000744 return 'origin/main'
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000745
746
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000747def root():
Jeffrey Yasskin6b52dc22019-12-06 18:32:21 +0000748 return get_config('depot-tools.upstream', upstream_default())
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000749
750
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000751@contextlib.contextmanager
752def less(): # pragma: no cover
753 """Runs 'less' as context manager yielding its stdin as a PIPE.
754
755 Automatically checks if sys.stdout is a non-TTY stream. If so, it avoids
756 running less and just yields sys.stdout.
Edward Lemur0d462e92020-01-08 20:11:31 +0000757
758 The returned PIPE is opened on binary mode.
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000759 """
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +0000760 if not setup_color.IS_TTY:
Edward Lemur5e94b802019-11-26 21:44:08 +0000761 # On Python 3, sys.stdout doesn't accept bytes, and sys.stdout.buffer must
762 # be used.
763 yield getattr(sys.stdout, 'buffer', sys.stdout)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000764 return
765
766 # Run with the same options that git uses (see setup_pager in git repo).
767 # -F: Automatically quit if the output is less than one screen.
768 # -R: Don't escape ANSI color codes.
769 # -X: Don't clear the screen before starting.
770 cmd = ('less', '-FRX')
771 try:
772 proc = subprocess2.Popen(cmd, stdin=subprocess2.PIPE)
773 yield proc.stdin
774 finally:
Edward Lemurb800fde2020-01-10 23:04:44 +0000775 try:
776 proc.stdin.close()
777 except BrokenPipeError:
778 # BrokenPipeError is raised if proc has already completed,
779 pass
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000780 proc.wait()
781
782
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000783def run(*cmd, **kwargs):
784 """The same as run_with_stderr, except it only returns stdout."""
785 return run_with_stderr(*cmd, **kwargs)[0]
786
787
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000788def run_with_retcode(*cmd, **kwargs):
789 """Run a command but only return the status code."""
790 try:
791 run(*cmd, **kwargs)
792 return 0
793 except subprocess2.CalledProcessError as cpe:
794 return cpe.returncode
795
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000796def run_stream(*cmd, **kwargs):
797 """Runs a git command. Returns stdout as a PIPE (file-like object).
798
799 stderr is dropped to avoid races if the process outputs to both stdout and
800 stderr.
801 """
Edward Lesmescf06cad2020-12-14 22:03:23 +0000802 kwargs.setdefault('stderr', subprocess2.DEVNULL)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000803 kwargs.setdefault('stdout', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000804 kwargs.setdefault('shell', False)
iannucci@chromium.org21980022014-04-11 04:51:49 +0000805 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000806 proc = subprocess2.Popen(cmd, **kwargs)
807 return proc.stdout
808
809
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000810@contextlib.contextmanager
811def run_stream_with_retcode(*cmd, **kwargs):
812 """Runs a git command as context manager yielding stdout as a PIPE.
813
814 stderr is dropped to avoid races if the process outputs to both stdout and
815 stderr.
816
817 Raises subprocess2.CalledProcessError on nonzero return code.
818 """
Edward Lesmescf06cad2020-12-14 22:03:23 +0000819 kwargs.setdefault('stderr', subprocess2.DEVNULL)
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000820 kwargs.setdefault('stdout', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000821 kwargs.setdefault('shell', False)
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000822 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
823 try:
824 proc = subprocess2.Popen(cmd, **kwargs)
825 yield proc.stdout
826 finally:
827 retcode = proc.wait()
828 if retcode != 0:
829 raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(),
Josip Sokcevic72f991f2020-04-23 18:53:30 +0000830 b'', b'')
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000831
832
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000833def run_with_stderr(*cmd, **kwargs):
834 """Runs a git command.
835
836 Returns (stdout, stderr) as a pair of strings.
837
838 kwargs
839 autostrip (bool) - Strip the output. Defaults to True.
840 indata (str) - Specifies stdin data for the process.
841 """
842 kwargs.setdefault('stdin', subprocess2.PIPE)
843 kwargs.setdefault('stdout', subprocess2.PIPE)
844 kwargs.setdefault('stderr', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000845 kwargs.setdefault('shell', False)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000846 autostrip = kwargs.pop('autostrip', True)
847 indata = kwargs.pop('indata', None)
Edward Lemur12a537f2019-10-03 21:57:15 +0000848 decode = kwargs.pop('decode', True)
Orr Bernsteinb7e16d22023-07-14 11:00:55 +0000849 accepted_retcodes = kwargs.pop('accepted_retcodes', [0])
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000850
iannucci@chromium.org21980022014-04-11 04:51:49 +0000851 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000852 proc = subprocess2.Popen(cmd, **kwargs)
853 ret, err = proc.communicate(indata)
854 retcode = proc.wait()
Orr Bernsteinb7e16d22023-07-14 11:00:55 +0000855 if retcode not in accepted_retcodes:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000856 raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(), ret, err)
857
858 if autostrip:
Edward Lemur12a537f2019-10-03 21:57:15 +0000859 ret = (ret or b'').strip()
860 err = (err or b'').strip()
861
862 if decode:
863 ret = ret.decode('utf-8', 'replace')
864 err = err.decode('utf-8', 'replace')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000865
866 return ret, err
867
868
869def set_branch_config(branch, option, value, scope='local'):
870 set_config('branch.%s.%s' % (branch, option), value, scope=scope)
871
872
873def set_config(option, value, scope='local'):
874 run('config', '--' + scope, option, value)
875
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000876
sbc@chromium.org71437c02015-04-09 19:29:40 +0000877def get_dirty_files():
878 # Make sure index is up-to-date before running diff-index.
879 run_with_retcode('update-index', '--refresh', '-q')
Eli Ribble54434e72019-05-24 00:41:15 +0000880 return run('diff-index', '--ignore-submodules', '--name-status', 'HEAD')
sbc@chromium.org71437c02015-04-09 19:29:40 +0000881
882
883def is_dirty_git_tree(cmd):
iannuccie38699b2016-08-15 17:32:31 -0700884 w = lambda s: sys.stderr.write(s+"\n")
885
sbc@chromium.org71437c02015-04-09 19:29:40 +0000886 dirty = get_dirty_files()
887 if dirty:
Josip Sokcevicfcf9fc42022-09-27 21:59:01 +0000888 w('Cannot %s with a dirty tree. Commit%s or stash your changes first.' %
889 (cmd, '' if cmd == 'upload' else ', freeze'))
iannuccie38699b2016-08-15 17:32:31 -0700890 w('Uncommitted files: (git diff-index --name-status HEAD)')
891 w(dirty[:4096])
sbc@chromium.org71437c02015-04-09 19:29:40 +0000892 if len(dirty) > 4096: # pragma: no cover
iannuccie38699b2016-08-15 17:32:31 -0700893 w('... (run "git diff-index --name-status HEAD" to see full output).')
sbc@chromium.org71437c02015-04-09 19:29:40 +0000894 return True
895 return False
896
897
Greg NISBET923bcf82023-08-10 22:50:46 +0000898def status(ignore_submodules=None):
agable02b3c982016-06-22 07:51:22 -0700899 """Returns a parsed version of git-status.
900
Greg NISBET923bcf82023-08-10 22:50:46 +0000901 Args:
902 ignore_submodules (str|None): "all", "none", or None.
903 None is equivalent to "none".
904
agable02b3c982016-06-22 07:51:22 -0700905 Returns a generator of (current_name, (lstat, rstat, src)) pairs where:
906 * current_name is the name of the file
907 * lstat is the left status code letter from git-status
908 * rstat is the left status code letter from git-status
909 * src is the current name of the file, or the original name of the file
910 if lstat == 'R'
911 """
Greg NISBET923bcf82023-08-10 22:50:46 +0000912
913 ignore_submodules = ignore_submodules or 'none'
914 assert ignore_submodules in (
915 'all', 'none'), f'ignore_submodules value {ignore_submodules} is invalid'
916
agable02b3c982016-06-22 07:51:22 -0700917 stat_entry = collections.namedtuple('stat_entry', 'lstat rstat src')
918
919 def tokenizer(stream):
Raul Tambrec2f74c12019-03-19 05:55:53 +0000920 acc = BytesIO()
agable02b3c982016-06-22 07:51:22 -0700921 c = None
Edward Lemur12a537f2019-10-03 21:57:15 +0000922 while c != b'':
agable02b3c982016-06-22 07:51:22 -0700923 c = stream.read(1)
Edward Lemur12a537f2019-10-03 21:57:15 +0000924 if c in (None, b'', b'\0'):
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000925 if len(acc.getvalue()) > 0:
agable02b3c982016-06-22 07:51:22 -0700926 yield acc.getvalue()
Raul Tambrec2f74c12019-03-19 05:55:53 +0000927 acc = BytesIO()
agable02b3c982016-06-22 07:51:22 -0700928 else:
929 acc.write(c)
930
931 def parser(tokens):
932 while True:
Edward Lemur12a537f2019-10-03 21:57:15 +0000933 try:
934 status_dest = next(tokens).decode('utf-8')
935 except StopIteration:
936 return
agable02b3c982016-06-22 07:51:22 -0700937 stat, dest = status_dest[:2], status_dest[3:]
938 lstat, rstat = stat
939 if lstat == 'R':
Edward Lemur12a537f2019-10-03 21:57:15 +0000940 src = next(tokens).decode('utf-8')
agable02b3c982016-06-22 07:51:22 -0700941 else:
942 src = dest
943 yield (dest, stat_entry(lstat, rstat, src))
944
Greg NISBET923bcf82023-08-10 22:50:46 +0000945 return parser(
946 tokenizer(
947 run_stream('status',
948 '-z',
949 f'--ignore-submodules={ignore_submodules}',
950 bufsize=-1)))
agable02b3c982016-06-22 07:51:22 -0700951
952
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000953def squash_current_branch(header=None, merge_base=None):
Alan Cutter00017822016-12-20 17:39:59 +1100954 header = header or 'git squash commit for %s.' % current_branch()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000955 merge_base = merge_base or get_or_create_merge_base(current_branch())
956 log_msg = header + '\n'
957 if log_msg:
958 log_msg += '\n'
959 log_msg += run('log', '--reverse', '--format=%H%n%B', '%s..HEAD' % merge_base)
960 run('reset', '--soft', merge_base)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000961
962 if not get_dirty_files():
963 # Sometimes the squash can result in the same tree, meaning that there is
964 # nothing to commit at this point.
Raul Tambrec2f74c12019-03-19 05:55:53 +0000965 print('Nothing to commit; squashed branch is empty')
sbc@chromium.org71437c02015-04-09 19:29:40 +0000966 return False
Edward Lemur71681bf2019-10-09 23:46:20 +0000967 run('commit', '--no-verify', '-a', '-F', '-', indata=log_msg.encode('utf-8'))
sbc@chromium.org71437c02015-04-09 19:29:40 +0000968 return True
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000969
970
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000971def tags(*args):
972 return run('tag', *args).splitlines()
973
974
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000975def thaw():
976 took_action = False
Bruce Dawson4082f882023-05-15 17:14:17 +0000977 with run_stream('rev-list', 'HEAD') as stream:
978 for sha in stream:
979 sha = sha.strip().decode('utf-8')
980 msg = run('show', '--format=%f%b', '-s', 'HEAD')
981 match = FREEZE_MATCHER.match(msg)
982 if not match:
983 if not took_action:
984 return 'Nothing to thaw.'
985 break
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000986
Bruce Dawson4082f882023-05-15 17:14:17 +0000987 run('reset', '--' + FREEZE_SECTIONS[match.group(1)], sha)
988 took_action = True
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000989
990
991def topo_iter(branch_tree, top_down=True):
992 """Generates (branch, parent) in topographical order for a branch tree.
993
994 Given a tree:
995
996 A1
997 B1 B2
998 C1 C2 C3
999 D1
1000
1001 branch_tree would look like: {
1002 'D1': 'C3',
1003 'C3': 'B2',
1004 'B2': 'A1',
1005 'C1': 'B1',
1006 'C2': 'B1',
1007 'B1': 'A1',
1008 }
1009
1010 It is OK to have multiple 'root' nodes in your graph.
1011
1012 if top_down is True, items are yielded from A->D. Otherwise they're yielded
1013 from D->A. Within a layer the branches will be yielded in sorted order.
1014 """
1015 branch_tree = branch_tree.copy()
1016
1017 # TODO(iannucci): There is probably a more efficient way to do these.
1018 if top_down:
1019 while branch_tree:
Edward Lemur12a537f2019-10-03 21:57:15 +00001020 this_pass = [(b, p) for b, p in branch_tree.items()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001021 if p not in branch_tree]
1022 assert this_pass, "Branch tree has cycles: %r" % branch_tree
1023 for branch, parent in sorted(this_pass):
1024 yield branch, parent
1025 del branch_tree[branch]
1026 else:
1027 parent_to_branches = collections.defaultdict(set)
Edward Lemur12a537f2019-10-03 21:57:15 +00001028 for branch, parent in branch_tree.items():
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001029 parent_to_branches[parent].add(branch)
1030
1031 while branch_tree:
Edward Lemur12a537f2019-10-03 21:57:15 +00001032 this_pass = [(b, p) for b, p in branch_tree.items()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001033 if not parent_to_branches[b]]
1034 assert this_pass, "Branch tree has cycles: %r" % branch_tree
1035 for branch, parent in sorted(this_pass):
1036 yield branch, parent
1037 parent_to_branches[parent].discard(branch)
1038 del branch_tree[branch]
1039
1040
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +00001041def tree(treeref, recurse=False):
1042 """Returns a dict representation of a git tree object.
1043
1044 Args:
1045 treeref (str) - a git ref which resolves to a tree (commits count as trees).
qyearsley12fa6ff2016-08-24 09:18:40 -07001046 recurse (bool) - include all of the tree's descendants too. File names will
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +00001047 take the form of 'some/path/to/file'.
1048
1049 Return format:
1050 { 'file_name': (mode, type, ref) }
1051
1052 mode is an integer where:
1053 * 0040000 - Directory
1054 * 0100644 - Regular non-executable file
1055 * 0100664 - Regular non-executable group-writeable file
1056 * 0100755 - Regular executable file
1057 * 0120000 - Symbolic link
1058 * 0160000 - Gitlink
1059
1060 type is a string where it's one of 'blob', 'commit', 'tree', 'tag'.
1061
1062 ref is the hex encoded hash of the entry.
1063 """
1064 ret = {}
1065 opts = ['ls-tree', '--full-tree']
1066 if recurse:
1067 opts.append('-r')
1068 opts.append(treeref)
1069 try:
1070 for line in run(*opts).splitlines():
1071 mode, typ, ref, name = line.split(None, 3)
1072 ret[name] = (mode, typ, ref)
1073 except subprocess2.CalledProcessError:
1074 return None
1075 return ret
1076
1077
Mun Yong Jang781e71e2017-10-25 15:46:20 -07001078def get_remote_url(remote='origin'):
1079 try:
1080 return run('config', 'remote.%s.url' % remote)
1081 except subprocess2.CalledProcessError:
1082 return None
1083
1084
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +00001085def upstream(branch):
1086 try:
1087 return run('rev-parse', '--abbrev-ref', '--symbolic-full-name',
1088 branch+'@{upstream}')
1089 except subprocess2.CalledProcessError:
1090 return None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001091
agable@chromium.orgd629fb42014-10-01 09:40:10 +00001092
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001093def get_git_version():
1094 """Returns a tuple that contains the numeric components of the current git
1095 version."""
1096 version_string = run('--version')
1097 version_match = re.search(r'(\d+.)+(\d+)', version_string)
1098 version = version_match.group() if version_match else ''
1099
1100 return tuple(int(x) for x in version.split('.'))
1101
1102
calamity@chromium.org745ffa62014-09-08 01:03:19 +00001103def get_branches_info(include_tracking_status):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001104 format_string = (
1105 '--format=%(refname:short):%(objectname:short):%(upstream:short):')
1106
1107 # This is not covered by the depot_tools CQ which only has git version 1.8.
calamity@chromium.org745ffa62014-09-08 01:03:19 +00001108 if (include_tracking_status and
1109 get_git_version() >= MIN_UPSTREAM_TRACK_GIT_VERSION): # pragma: no cover
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001110 format_string += '%(upstream:track)'
1111
1112 info_map = {}
1113 data = run('for-each-ref', format_string, 'refs/heads')
calamity@chromium.org745ffa62014-09-08 01:03:19 +00001114 BranchesInfo = collections.namedtuple(
Gavin Mak8d7201b2020-09-17 19:21:38 +00001115 'BranchesInfo', 'hash upstream commits behind')
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001116 for line in data.splitlines():
1117 (branch, branch_hash, upstream_branch, tracking_status) = line.split(':')
1118
Gavin Mak8d7201b2020-09-17 19:21:38 +00001119 commits = None
Antonio Sartorie0dff202021-02-18 06:33:50 +00001120 if include_tracking_status:
1121 base = get_or_create_merge_base(branch)
1122 if base:
1123 commits_list = run('rev-list', '--count', branch, '^%s' % base, '--')
1124 commits = int(commits_list) or None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001125
1126 behind_match = re.search(r'behind (\d+)', tracking_status)
1127 behind = int(behind_match.group(1)) if behind_match else None
1128
calamity@chromium.org745ffa62014-09-08 01:03:19 +00001129 info_map[branch] = BranchesInfo(
Robert Iannuccid3acb162021-05-04 21:37:40 +00001130 hash=branch_hash, upstream=upstream_branch, commits=commits,
Gavin Mak8d7201b2020-09-17 19:21:38 +00001131 behind=behind)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00001132
1133 # Set None for upstreams which are not branches (e.g empty upstream, remotes
1134 # and deleted upstream branches).
1135 missing_upstreams = {}
1136 for info in info_map.values():
1137 if info.upstream not in info_map and info.upstream not in missing_upstreams:
1138 missing_upstreams[info.upstream] = None
1139
Edward Lemur12a537f2019-10-03 21:57:15 +00001140 result = info_map.copy()
1141 result.update(missing_upstreams)
1142 return result
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001143
1144
1145def make_workdir_common(repository, new_workdir, files_to_symlink,
scottmg@chromium.orgd4218d42015-10-07 23:49:20 +00001146 files_to_copy, symlink=None):
1147 if not symlink:
1148 symlink = os.symlink
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001149 os.makedirs(new_workdir)
1150 for entry in files_to_symlink:
scottmg@chromium.orgd4218d42015-10-07 23:49:20 +00001151 clone_file(repository, new_workdir, entry, symlink)
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001152 for entry in files_to_copy:
1153 clone_file(repository, new_workdir, entry, shutil.copy)
1154
1155
1156def make_workdir(repository, new_workdir):
1157 GIT_DIRECTORY_WHITELIST = [
1158 'config',
1159 'info',
1160 'hooks',
1161 'logs/refs',
1162 'objects',
1163 'packed-refs',
1164 'refs',
1165 'remotes',
1166 'rr-cache',
Richard He42033b22020-05-22 03:03:45 +00001167 'shallow',
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001168 ]
1169 make_workdir_common(repository, new_workdir, GIT_DIRECTORY_WHITELIST,
1170 ['HEAD'])
1171
1172
1173def clone_file(repository, new_workdir, link, operation):
1174 if not os.path.exists(os.path.join(repository, link)):
1175 return
1176 link_dir = os.path.dirname(os.path.join(new_workdir, link))
1177 if not os.path.exists(link_dir):
1178 os.makedirs(link_dir)
Henrique Ferreirofd4ad242018-01-10 12:19:18 +01001179 src = os.path.join(repository, link)
1180 if os.path.islink(src):
Henrique Ferreiroaea45d22018-02-19 09:48:36 +01001181 src = os.path.realpath(src)
Henrique Ferreirofd4ad242018-01-10 12:19:18 +01001182 operation(src, os.path.join(new_workdir, link))