blob: 78767e7621ea8786936931e8393a6356d460df5d [file] [log] [blame]
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00001# Copyright 2014 The Chromium Authors. All rights reserved.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +00002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5# Monkeypatch IMapIterator so that Ctrl-C can kill everything properly.
6# Derived from https://gist.github.com/aljungberg/626518
7import multiprocessing.pool
8from multiprocessing.pool import IMapIterator
9def wrapper(func):
10 def wrap(self, timeout=None):
11 return func(self, timeout=timeout or 1e100)
12 return wrap
13IMapIterator.next = wrapper(IMapIterator.next)
14IMapIterator.__next__ = IMapIterator.next
15# TODO(iannucci): Monkeypatch all other 'wait' methods too.
16
17
18import binascii
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000019import collections
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000020import contextlib
21import functools
22import logging
iannucci@chromium.org97345eb2014-03-13 07:55:15 +000023import os
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000024import re
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +000025import setup_color
sammc@chromium.org900a33f2015-09-29 06:57:09 +000026import shutil
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000027import signal
28import sys
29import tempfile
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +000030import textwrap
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000031import threading
32
33import subprocess2
34
agable02b3c982016-06-22 07:51:22 -070035from StringIO import StringIO
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000036
agable02b3c982016-06-22 07:51:22 -070037
38ROOT = os.path.abspath(os.path.dirname(__file__))
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +000039IS_WIN = sys.platform == 'win32'
40GIT_EXE = ROOT+'\\git.bat' if IS_WIN else 'git'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000041TEST_MODE = False
42
43FREEZE = 'FREEZE'
44FREEZE_SECTIONS = {
45 'indexed': 'soft',
46 'unindexed': 'mixed'
47}
48FREEZE_MATCHER = re.compile(r'%s.(%s)' % (FREEZE, '|'.join(FREEZE_SECTIONS)))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +000049
50
Dan Jacques2f8b0c12017-04-05 12:57:21 -070051# NOTE: This list is DEPRECATED in favor of the Infra Git wrapper:
52# https://chromium.googlesource.com/infra/infra/+/master/go/src/infra/tools/git
53#
54# New entries should be added to the Git wrapper, NOT to this list. "git_retry"
55# is, similarly, being deprecated in favor of the Git wrapper.
56#
57# ---
58#
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000059# Retry a git operation if git returns a error response with any of these
60# messages. It's all observed 'bad' GoB responses so far.
61#
62# This list is inspired/derived from the one in ChromiumOS's Chromite:
63# <CHROMITE>/lib/git.py::GIT_TRANSIENT_ERRORS
64#
65# It was last imported from '7add3ac29564d98ac35ce426bc295e743e7c0c02'.
66GIT_TRANSIENT_ERRORS = (
67 # crbug.com/285832
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000068 r'!.*\[remote rejected\].*\(error in hook\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000069
70 # crbug.com/289932
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000071 r'!.*\[remote rejected\].*\(failed to lock\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000072
73 # crbug.com/307156
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000074 r'!.*\[remote rejected\].*\(error in Gerrit backend\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000075
76 # crbug.com/285832
77 r'remote error: Internal Server Error',
78
79 # crbug.com/294449
80 r'fatal: Couldn\'t find remote ref ',
81
82 # crbug.com/220543
83 r'git fetch_pack: expected ACK/NAK, got',
84
85 # crbug.com/189455
86 r'protocol error: bad pack header',
87
88 # crbug.com/202807
89 r'The remote end hung up unexpectedly',
90
91 # crbug.com/298189
92 r'TLS packet with unexpected length was received',
93
94 # crbug.com/187444
95 r'RPC failed; result=\d+, HTTP code = \d+',
96
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000097 # crbug.com/388876
98 r'Connection timed out',
dnj@chromium.org45cddd62014-11-06 19:36:42 +000099
100 # crbug.com/430343
101 # TODO(dnj): Resync with Chromite.
102 r'The requested URL returned error: 5\d+',
Arikonb3a21482016-07-22 10:12:24 -0700103
104 r'Connection reset by peer',
105
106 r'Unable to look up',
107
108 r'Couldn\'t resolve host',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +0000109)
110
111GIT_TRANSIENT_ERRORS_RE = re.compile('|'.join(GIT_TRANSIENT_ERRORS),
112 re.IGNORECASE)
113
raphael.kubo.da.costa@intel.com58d05b02015-06-24 08:54:41 +0000114# git's for-each-ref command first supported the upstream:track token in its
115# format string in version 1.9.0, but some usages were broken until 2.3.0.
116# See git commit b6160d95 for more information.
117MIN_UPSTREAM_TRACK_GIT_VERSION = (2, 3)
dnj@chromium.orgde219ec2014-07-28 17:39:08 +0000118
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000119class BadCommitRefException(Exception):
120 def __init__(self, refs):
121 msg = ('one of %s does not seem to be a valid commitref.' %
122 str(refs))
123 super(BadCommitRefException, self).__init__(msg)
124
125
126def memoize_one(**kwargs):
127 """Memoizes a single-argument pure function.
128
129 Values of None are not cached.
130
131 Kwargs:
132 threadsafe (bool) - REQUIRED. Specifies whether to use locking around
133 cache manipulation functions. This is a kwarg so that users of memoize_one
134 are forced to explicitly and verbosely pick True or False.
135
136 Adds three methods to the decorated function:
137 * get(key, default=None) - Gets the value for this key from the cache.
138 * set(key, value) - Sets the value for this key from the cache.
139 * clear() - Drops the entire contents of the cache. Useful for unittests.
140 * update(other) - Updates the contents of the cache from another dict.
141 """
142 assert 'threadsafe' in kwargs, 'Must specify threadsafe={True,False}'
143 threadsafe = kwargs['threadsafe']
144
145 if threadsafe:
146 def withlock(lock, f):
147 def inner(*args, **kwargs):
148 with lock:
149 return f(*args, **kwargs)
150 return inner
151 else:
152 def withlock(_lock, f):
153 return f
154
155 def decorator(f):
156 # Instantiate the lock in decorator, in case users of memoize_one do:
157 #
158 # memoizer = memoize_one(threadsafe=True)
159 #
160 # @memoizer
161 # def fn1(val): ...
162 #
163 # @memoizer
164 # def fn2(val): ...
165
166 lock = threading.Lock() if threadsafe else None
167 cache = {}
168 _get = withlock(lock, cache.get)
169 _set = withlock(lock, cache.__setitem__)
170
171 @functools.wraps(f)
172 def inner(arg):
173 ret = _get(arg)
174 if ret is None:
175 ret = f(arg)
176 if ret is not None:
177 _set(arg, ret)
178 return ret
179 inner.get = _get
180 inner.set = _set
181 inner.clear = withlock(lock, cache.clear)
182 inner.update = withlock(lock, cache.update)
183 return inner
184 return decorator
185
186
187def _ScopedPool_initer(orig, orig_args): # pragma: no cover
188 """Initializer method for ScopedPool's subprocesses.
189
190 This helps ScopedPool handle Ctrl-C's correctly.
191 """
192 signal.signal(signal.SIGINT, signal.SIG_IGN)
193 if orig:
194 orig(*orig_args)
195
196
197@contextlib.contextmanager
198def ScopedPool(*args, **kwargs):
199 """Context Manager which returns a multiprocessing.pool instance which
200 correctly deals with thrown exceptions.
201
202 *args - Arguments to multiprocessing.pool
203
204 Kwargs:
205 kind ('threads', 'procs') - The type of underlying coprocess to use.
206 **etc - Arguments to multiprocessing.pool
207 """
208 if kwargs.pop('kind', None) == 'threads':
209 pool = multiprocessing.pool.ThreadPool(*args, **kwargs)
210 else:
211 orig, orig_args = kwargs.get('initializer'), kwargs.get('initargs', ())
212 kwargs['initializer'] = _ScopedPool_initer
213 kwargs['initargs'] = orig, orig_args
214 pool = multiprocessing.pool.Pool(*args, **kwargs)
215
216 try:
217 yield pool
218 pool.close()
219 except:
220 pool.terminate()
221 raise
222 finally:
223 pool.join()
224
225
226class ProgressPrinter(object):
227 """Threaded single-stat status message printer."""
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000228 def __init__(self, fmt, enabled=None, fout=sys.stderr, period=0.5):
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000229 """Create a ProgressPrinter.
230
231 Use it as a context manager which produces a simple 'increment' method:
232
233 with ProgressPrinter('(%%(count)d/%d)' % 1000) as inc:
234 for i in xrange(1000):
235 # do stuff
236 if i % 10 == 0:
237 inc(10)
238
239 Args:
240 fmt - String format with a single '%(count)d' where the counter value
241 should go.
242 enabled (bool) - If this is None, will default to True if
243 logging.getLogger() is set to INFO or more verbose.
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000244 fout (file-like) - The stream to print status messages to.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000245 period (float) - The time in seconds for the printer thread to wait
246 between printing.
247 """
248 self.fmt = fmt
249 if enabled is None: # pragma: no cover
250 self.enabled = logging.getLogger().isEnabledFor(logging.INFO)
251 else:
252 self.enabled = enabled
253
254 self._count = 0
255 self._dead = False
256 self._dead_cond = threading.Condition()
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000257 self._stream = fout
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000258 self._thread = threading.Thread(target=self._run)
259 self._period = period
260
261 def _emit(self, s):
262 if self.enabled:
263 self._stream.write('\r' + s)
264 self._stream.flush()
265
266 def _run(self):
267 with self._dead_cond:
268 while not self._dead:
269 self._emit(self.fmt % {'count': self._count})
270 self._dead_cond.wait(self._period)
271 self._emit((self.fmt + '\n') % {'count': self._count})
272
273 def inc(self, amount=1):
274 self._count += amount
275
276 def __enter__(self):
277 self._thread.start()
278 return self.inc
279
280 def __exit__(self, _exc_type, _exc_value, _traceback):
281 self._dead = True
282 with self._dead_cond:
283 self._dead_cond.notifyAll()
284 self._thread.join()
285 del self._thread
286
287
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000288def once(function):
289 """@Decorates |function| so that it only performs its action once, no matter
290 how many times the decorated |function| is called."""
291 def _inner_gen():
292 yield function()
293 while True:
294 yield
295 return _inner_gen().next
296
297
298## Git functions
299
agable7aa2ddd2016-06-21 07:47:00 -0700300def die(message, *args):
301 print >> sys.stderr, textwrap.dedent(message % args)
302 sys.exit(1)
303
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000304
Mark Mentovaif548d082017-03-08 13:32:00 -0500305def blame(filename, revision=None, porcelain=False, abbrev=None, *_args):
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000306 command = ['blame']
307 if porcelain:
308 command.append('-p')
309 if revision is not None:
310 command.append(revision)
Mark Mentovaif548d082017-03-08 13:32:00 -0500311 if abbrev is not None:
312 command.append('--abbrev=%d' % abbrev)
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000313 command.extend(['--', filename])
314 return run(*command)
315
316
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000317def branch_config(branch, option, default=None):
agable7aa2ddd2016-06-21 07:47:00 -0700318 return get_config('branch.%s.%s' % (branch, option), default=default)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000319
320
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000321def branch_config_map(option):
322 """Return {branch: <|option| value>} for all branches."""
323 try:
324 reg = re.compile(r'^branch\.(.*)\.%s$' % option)
agable7aa2ddd2016-06-21 07:47:00 -0700325 lines = get_config_regexp(reg.pattern)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000326 return {reg.match(k).group(1): v for k, v in (l.split() for l in lines)}
327 except subprocess2.CalledProcessError:
328 return {}
329
330
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000331def branches(*args):
akuegel@chromium.org58888e12015-06-09 15:26:37 +0000332 NO_BRANCH = ('* (no branch', '* (detached', '* (HEAD detached')
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000333
334 key = 'depot-tools.branch-limit'
agable7aa2ddd2016-06-21 07:47:00 -0700335 limit = get_config_int(key, 20)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000336
337 raw_branches = run('branch', *args).splitlines()
338
339 num = len(raw_branches)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000340
agable7aa2ddd2016-06-21 07:47:00 -0700341 if num > limit:
342 die("""\
343 Your git repo has too many branches (%d/%d) for this tool to work well.
344
345 You may adjust this limit by running:
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000346 git config %s <new_limit>
agable7aa2ddd2016-06-21 07:47:00 -0700347
348 You may also try cleaning up your old branches by running:
349 git cl archive
350 """, num, limit, key)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000351
352 for line in raw_branches:
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000353 if line.startswith(NO_BRANCH):
354 continue
355 yield line.split()[-1]
356
357
agable7aa2ddd2016-06-21 07:47:00 -0700358def get_config(option, default=None):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000359 try:
360 return run('config', '--get', option) or default
361 except subprocess2.CalledProcessError:
362 return default
363
364
agable7aa2ddd2016-06-21 07:47:00 -0700365def get_config_int(option, default=0):
366 assert isinstance(default, int)
367 try:
368 return int(get_config(option, default))
369 except ValueError:
370 return default
371
372
373def get_config_list(option):
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000374 try:
375 return run('config', '--get-all', option).split()
376 except subprocess2.CalledProcessError:
377 return []
378
379
agable7aa2ddd2016-06-21 07:47:00 -0700380def get_config_regexp(pattern):
381 if IS_WIN: # pragma: no cover
382 # this madness is because we call git.bat which calls git.exe which calls
383 # bash.exe (or something to that effect). Each layer divides the number of
384 # ^'s by 2.
385 pattern = pattern.replace('^', '^' * 8)
386 return run('config', '--get-regexp', pattern).splitlines()
387
388
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000389def current_branch():
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000390 try:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000391 return run('rev-parse', '--abbrev-ref', 'HEAD')
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000392 except subprocess2.CalledProcessError:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000393 return None
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000394
395
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000396def del_branch_config(branch, option, scope='local'):
397 del_config('branch.%s.%s' % (branch, option), scope=scope)
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000398
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000399
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000400def del_config(option, scope='local'):
401 try:
402 run('config', '--' + scope, '--unset', option)
403 except subprocess2.CalledProcessError:
404 pass
405
406
mgiuca@chromium.org01d2cde2016-02-05 03:25:41 +0000407def diff(oldrev, newrev, *args):
408 return run('diff', oldrev, newrev, *args)
409
410
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000411def freeze():
412 took_action = False
agable02b3c982016-06-22 07:51:22 -0700413 key = 'depot-tools.freeze-size-limit'
414 MB = 2**20
415 limit_mb = get_config_int(key, 100)
416 untracked_bytes = 0
417
iannuccieaca0332016-08-03 16:46:50 -0700418 root_path = repo_root()
419
agable02b3c982016-06-22 07:51:22 -0700420 for f, s in status():
421 if is_unmerged(s):
422 die("Cannot freeze unmerged changes!")
423 if limit_mb > 0:
424 if s.lstat == '?':
iannuccieaca0332016-08-03 16:46:50 -0700425 untracked_bytes += os.stat(os.path.join(root_path, f)).st_size
agable02b3c982016-06-22 07:51:22 -0700426 if untracked_bytes > limit_mb * MB:
427 die("""\
428 You appear to have too much untracked+unignored data in your git
429 checkout: %.1f / %d MB.
430
431 Run `git status` to see what it is.
432
433 In addition to making many git commands slower, this will prevent
434 depot_tools from freezing your in-progress changes.
435
436 You should add untracked data that you want to ignore to your repo's
Marc-Antoine Ruel328b00f2017-02-04 17:44:21 -0500437 .git/info/exclude
agable02b3c982016-06-22 07:51:22 -0700438 file. See `git help ignore` for the format of this file.
439
440 If this data is indended as part of your commit, you may adjust the
441 freeze limit by running:
442 git config %s <new_limit>
443 Where <new_limit> is an integer threshold in megabytes.""",
444 untracked_bytes / (MB * 1.0), limit_mb, key)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000445
446 try:
iannucci@chromium.org3b4f2282015-09-17 15:46:00 +0000447 run('commit', '--no-verify', '-m', FREEZE + '.indexed')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000448 took_action = True
449 except subprocess2.CalledProcessError:
450 pass
451
agable96e179b2016-06-24 10:32:51 -0700452 add_errors = False
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000453 try:
agable96e179b2016-06-24 10:32:51 -0700454 run('add', '-A', '--ignore-errors')
455 except subprocess2.CalledProcessError:
456 add_errors = True
457
458 try:
iannucci@chromium.org3b4f2282015-09-17 15:46:00 +0000459 run('commit', '--no-verify', '-m', FREEZE + '.unindexed')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000460 took_action = True
461 except subprocess2.CalledProcessError:
462 pass
463
agable96e179b2016-06-24 10:32:51 -0700464 ret = []
465 if add_errors:
466 ret.append('Failed to index some unindexed files.')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000467 if not took_action:
agable96e179b2016-06-24 10:32:51 -0700468 ret.append('Nothing to freeze.')
469 return ' '.join(ret) or None
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000470
471
472def get_branch_tree():
473 """Get the dictionary of {branch: parent}, compatible with topo_iter.
474
475 Returns a tuple of (skipped, <branch_tree dict>) where skipped is a set of
476 branches without upstream branches defined.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000477 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000478 skipped = set()
479 branch_tree = {}
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000480
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000481 for branch in branches():
482 parent = upstream(branch)
483 if not parent:
484 skipped.add(branch)
485 continue
486 branch_tree[branch] = parent
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000487
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000488 return skipped, branch_tree
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000489
490
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000491def get_or_create_merge_base(branch, parent=None):
492 """Finds the configured merge base for branch.
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000493
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000494 If parent is supplied, it's used instead of calling upstream(branch).
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000495 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000496 base = branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000497 base_upstream = branch_config(branch, 'base-upstream')
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000498 parent = parent or upstream(branch)
sbc@chromium.org79706062015-01-14 21:18:12 +0000499 if parent is None or branch is None:
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000500 return None
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000501 actual_merge_base = run('merge-base', parent, branch)
502
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000503 if base_upstream != parent:
504 base = None
505 base_upstream = None
506
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000507 def is_ancestor(a, b):
508 return run_with_retcode('merge-base', '--is-ancestor', a, b) == 0
509
clemensh@chromium.orgc3fe99d2016-04-19 08:39:55 +0000510 if base and base != actual_merge_base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000511 if not is_ancestor(base, branch):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000512 logging.debug('Found WRONG pre-set merge-base for %s: %s', branch, base)
513 base = None
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000514 elif is_ancestor(base, actual_merge_base):
515 logging.debug('Found OLD pre-set merge-base for %s: %s', branch, base)
516 base = None
517 else:
518 logging.debug('Found pre-set merge-base for %s: %s', branch, base)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000519
520 if not base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000521 base = actual_merge_base
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000522 manual_merge_base(branch, base, parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000523
524 return base
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000525
526
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000527def hash_multi(*reflike):
528 return run('rev-parse', *reflike).splitlines()
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000529
530
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000531def hash_one(reflike, short=False):
532 args = ['rev-parse', reflike]
533 if short:
534 args.insert(1, '--short')
535 return run(*args)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000536
537
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000538def in_rebase():
539 git_dir = run('rev-parse', '--git-dir')
540 return (
541 os.path.exists(os.path.join(git_dir, 'rebase-merge')) or
542 os.path.exists(os.path.join(git_dir, 'rebase-apply')))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000543
544
545def intern_f(f, kind='blob'):
546 """Interns a file object into the git object store.
547
548 Args:
549 f (file-like object) - The file-like object to intern
550 kind (git object type) - One of 'blob', 'commit', 'tree', 'tag'.
551
552 Returns the git hash of the interned object (hex encoded).
553 """
554 ret = run('hash-object', '-t', kind, '-w', '--stdin', stdin=f)
555 f.close()
556 return ret
557
558
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000559def is_dormant(branch):
560 # TODO(iannucci): Do an oldness check?
561 return branch_config(branch, 'dormant', 'false') != 'false'
562
563
agable02b3c982016-06-22 07:51:22 -0700564def is_unmerged(stat_value):
565 return (
566 'U' in (stat_value.lstat, stat_value.rstat) or
567 ((stat_value.lstat == stat_value.rstat) and stat_value.lstat in 'AD')
568 )
569
570
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000571def manual_merge_base(branch, base, parent):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000572 set_branch_config(branch, 'base', base)
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000573 set_branch_config(branch, 'base-upstream', parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000574
575
576def mktree(treedict):
577 """Makes a git tree object and returns its hash.
578
579 See |tree()| for the values of mode, type, and ref.
580
581 Args:
582 treedict - { name: (mode, type, ref) }
583 """
584 with tempfile.TemporaryFile() as f:
585 for name, (mode, typ, ref) in treedict.iteritems():
586 f.write('%s %s %s\t%s\0' % (mode, typ, ref, name))
587 f.seek(0)
588 return run('mktree', '-z', stdin=f)
589
590
591def parse_commitrefs(*commitrefs):
592 """Returns binary encoded commit hashes for one or more commitrefs.
593
594 A commitref is anything which can resolve to a commit. Popular examples:
595 * 'HEAD'
596 * 'origin/master'
597 * 'cool_branch~2'
598 """
599 try:
600 return map(binascii.unhexlify, hash_multi(*commitrefs))
601 except subprocess2.CalledProcessError:
602 raise BadCommitRefException(commitrefs)
603
604
sbc@chromium.org384039b2014-10-13 21:01:00 +0000605RebaseRet = collections.namedtuple('RebaseRet', 'success stdout stderr')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000606
607
608def rebase(parent, start, branch, abort=False):
609 """Rebases |start|..|branch| onto the branch |parent|.
610
611 Args:
612 parent - The new parent ref for the rebased commits.
613 start - The commit to start from
614 branch - The branch to rebase
615 abort - If True, will call git-rebase --abort in the event that the rebase
616 doesn't complete successfully.
617
618 Returns a namedtuple with fields:
619 success - a boolean indicating that the rebase command completed
620 successfully.
621 message - if the rebase failed, this contains the stdout of the failed
622 rebase.
623 """
624 try:
625 args = ['--onto', parent, start, branch]
626 if TEST_MODE:
627 args.insert(0, '--committer-date-is-author-date')
628 run('rebase', *args)
sbc@chromium.org384039b2014-10-13 21:01:00 +0000629 return RebaseRet(True, '', '')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000630 except subprocess2.CalledProcessError as cpe:
631 if abort:
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000632 run_with_retcode('rebase', '--abort') # ignore failure
sbc@chromium.org384039b2014-10-13 21:01:00 +0000633 return RebaseRet(False, cpe.stdout, cpe.stderr)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000634
635
636def remove_merge_base(branch):
637 del_branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000638 del_branch_config(branch, 'base-upstream')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000639
640
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000641def repo_root():
642 """Returns the absolute path to the repository root."""
643 return run('rev-parse', '--show-toplevel')
644
645
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000646def root():
agable7aa2ddd2016-06-21 07:47:00 -0700647 return get_config('depot-tools.upstream', 'origin/master')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000648
649
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000650@contextlib.contextmanager
651def less(): # pragma: no cover
652 """Runs 'less' as context manager yielding its stdin as a PIPE.
653
654 Automatically checks if sys.stdout is a non-TTY stream. If so, it avoids
655 running less and just yields sys.stdout.
656 """
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +0000657 if not setup_color.IS_TTY:
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000658 yield sys.stdout
659 return
660
661 # Run with the same options that git uses (see setup_pager in git repo).
662 # -F: Automatically quit if the output is less than one screen.
663 # -R: Don't escape ANSI color codes.
664 # -X: Don't clear the screen before starting.
665 cmd = ('less', '-FRX')
666 try:
667 proc = subprocess2.Popen(cmd, stdin=subprocess2.PIPE)
668 yield proc.stdin
669 finally:
670 proc.stdin.close()
671 proc.wait()
672
673
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000674def run(*cmd, **kwargs):
675 """The same as run_with_stderr, except it only returns stdout."""
676 return run_with_stderr(*cmd, **kwargs)[0]
677
678
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000679def run_with_retcode(*cmd, **kwargs):
680 """Run a command but only return the status code."""
681 try:
682 run(*cmd, **kwargs)
683 return 0
684 except subprocess2.CalledProcessError as cpe:
685 return cpe.returncode
686
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000687def run_stream(*cmd, **kwargs):
688 """Runs a git command. Returns stdout as a PIPE (file-like object).
689
690 stderr is dropped to avoid races if the process outputs to both stdout and
691 stderr.
692 """
693 kwargs.setdefault('stderr', subprocess2.VOID)
694 kwargs.setdefault('stdout', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000695 kwargs.setdefault('shell', False)
iannucci@chromium.org21980022014-04-11 04:51:49 +0000696 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000697 proc = subprocess2.Popen(cmd, **kwargs)
698 return proc.stdout
699
700
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000701@contextlib.contextmanager
702def run_stream_with_retcode(*cmd, **kwargs):
703 """Runs a git command as context manager yielding stdout as a PIPE.
704
705 stderr is dropped to avoid races if the process outputs to both stdout and
706 stderr.
707
708 Raises subprocess2.CalledProcessError on nonzero return code.
709 """
710 kwargs.setdefault('stderr', subprocess2.VOID)
711 kwargs.setdefault('stdout', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000712 kwargs.setdefault('shell', False)
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000713 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
714 try:
715 proc = subprocess2.Popen(cmd, **kwargs)
716 yield proc.stdout
717 finally:
718 retcode = proc.wait()
719 if retcode != 0:
720 raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(),
721 None, None)
722
723
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000724def run_with_stderr(*cmd, **kwargs):
725 """Runs a git command.
726
727 Returns (stdout, stderr) as a pair of strings.
728
729 kwargs
730 autostrip (bool) - Strip the output. Defaults to True.
731 indata (str) - Specifies stdin data for the process.
732 """
733 kwargs.setdefault('stdin', subprocess2.PIPE)
734 kwargs.setdefault('stdout', subprocess2.PIPE)
735 kwargs.setdefault('stderr', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000736 kwargs.setdefault('shell', False)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000737 autostrip = kwargs.pop('autostrip', True)
738 indata = kwargs.pop('indata', None)
739
iannucci@chromium.org21980022014-04-11 04:51:49 +0000740 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000741 proc = subprocess2.Popen(cmd, **kwargs)
742 ret, err = proc.communicate(indata)
743 retcode = proc.wait()
744 if retcode != 0:
745 raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(), ret, err)
746
747 if autostrip:
748 ret = (ret or '').strip()
749 err = (err or '').strip()
750
751 return ret, err
752
753
754def set_branch_config(branch, option, value, scope='local'):
755 set_config('branch.%s.%s' % (branch, option), value, scope=scope)
756
757
758def set_config(option, value, scope='local'):
759 run('config', '--' + scope, option, value)
760
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000761
sbc@chromium.org71437c02015-04-09 19:29:40 +0000762def get_dirty_files():
763 # Make sure index is up-to-date before running diff-index.
764 run_with_retcode('update-index', '--refresh', '-q')
765 return run('diff-index', '--name-status', 'HEAD')
766
767
768def is_dirty_git_tree(cmd):
iannuccie38699b2016-08-15 17:32:31 -0700769 w = lambda s: sys.stderr.write(s+"\n")
770
sbc@chromium.org71437c02015-04-09 19:29:40 +0000771 dirty = get_dirty_files()
772 if dirty:
iannuccie38699b2016-08-15 17:32:31 -0700773 w('Cannot %s with a dirty tree. Commit, freeze or stash your changes first.'
774 % cmd)
775 w('Uncommitted files: (git diff-index --name-status HEAD)')
776 w(dirty[:4096])
sbc@chromium.org71437c02015-04-09 19:29:40 +0000777 if len(dirty) > 4096: # pragma: no cover
iannuccie38699b2016-08-15 17:32:31 -0700778 w('... (run "git diff-index --name-status HEAD" to see full output).')
sbc@chromium.org71437c02015-04-09 19:29:40 +0000779 return True
780 return False
781
782
agable02b3c982016-06-22 07:51:22 -0700783def status():
784 """Returns a parsed version of git-status.
785
786 Returns a generator of (current_name, (lstat, rstat, src)) pairs where:
787 * current_name is the name of the file
788 * lstat is the left status code letter from git-status
789 * rstat is the left status code letter from git-status
790 * src is the current name of the file, or the original name of the file
791 if lstat == 'R'
792 """
793 stat_entry = collections.namedtuple('stat_entry', 'lstat rstat src')
794
795 def tokenizer(stream):
796 acc = StringIO()
797 c = None
798 while c != '':
799 c = stream.read(1)
800 if c in (None, '', '\0'):
801 if acc.len:
802 yield acc.getvalue()
803 acc = StringIO()
804 else:
805 acc.write(c)
806
807 def parser(tokens):
808 while True:
809 # Raises StopIteration if it runs out of tokens.
810 status_dest = next(tokens)
811 stat, dest = status_dest[:2], status_dest[3:]
812 lstat, rstat = stat
813 if lstat == 'R':
814 src = next(tokens)
815 else:
816 src = dest
817 yield (dest, stat_entry(lstat, rstat, src))
818
819 return parser(tokenizer(run_stream('status', '-z', bufsize=-1)))
820
821
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000822def squash_current_branch(header=None, merge_base=None):
Alan Cutter00017822016-12-20 17:39:59 +1100823 header = header or 'git squash commit for %s.' % current_branch()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000824 merge_base = merge_base or get_or_create_merge_base(current_branch())
825 log_msg = header + '\n'
826 if log_msg:
827 log_msg += '\n'
828 log_msg += run('log', '--reverse', '--format=%H%n%B', '%s..HEAD' % merge_base)
829 run('reset', '--soft', merge_base)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000830
831 if not get_dirty_files():
832 # Sometimes the squash can result in the same tree, meaning that there is
833 # nothing to commit at this point.
834 print 'Nothing to commit; squashed branch is empty'
835 return False
maruel@chromium.org25b9ab22015-06-18 18:49:03 +0000836 run('commit', '--no-verify', '-a', '-F', '-', indata=log_msg)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000837 return True
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000838
839
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000840def tags(*args):
841 return run('tag', *args).splitlines()
842
843
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000844def thaw():
845 took_action = False
846 for sha in (s.strip() for s in run_stream('rev-list', 'HEAD').xreadlines()):
847 msg = run('show', '--format=%f%b', '-s', 'HEAD')
848 match = FREEZE_MATCHER.match(msg)
849 if not match:
850 if not took_action:
851 return 'Nothing to thaw.'
852 break
853
854 run('reset', '--' + FREEZE_SECTIONS[match.group(1)], sha)
855 took_action = True
856
857
858def topo_iter(branch_tree, top_down=True):
859 """Generates (branch, parent) in topographical order for a branch tree.
860
861 Given a tree:
862
863 A1
864 B1 B2
865 C1 C2 C3
866 D1
867
868 branch_tree would look like: {
869 'D1': 'C3',
870 'C3': 'B2',
871 'B2': 'A1',
872 'C1': 'B1',
873 'C2': 'B1',
874 'B1': 'A1',
875 }
876
877 It is OK to have multiple 'root' nodes in your graph.
878
879 if top_down is True, items are yielded from A->D. Otherwise they're yielded
880 from D->A. Within a layer the branches will be yielded in sorted order.
881 """
882 branch_tree = branch_tree.copy()
883
884 # TODO(iannucci): There is probably a more efficient way to do these.
885 if top_down:
886 while branch_tree:
887 this_pass = [(b, p) for b, p in branch_tree.iteritems()
888 if p not in branch_tree]
889 assert this_pass, "Branch tree has cycles: %r" % branch_tree
890 for branch, parent in sorted(this_pass):
891 yield branch, parent
892 del branch_tree[branch]
893 else:
894 parent_to_branches = collections.defaultdict(set)
895 for branch, parent in branch_tree.iteritems():
896 parent_to_branches[parent].add(branch)
897
898 while branch_tree:
899 this_pass = [(b, p) for b, p in branch_tree.iteritems()
900 if not parent_to_branches[b]]
901 assert this_pass, "Branch tree has cycles: %r" % branch_tree
902 for branch, parent in sorted(this_pass):
903 yield branch, parent
904 parent_to_branches[parent].discard(branch)
905 del branch_tree[branch]
906
907
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000908def tree(treeref, recurse=False):
909 """Returns a dict representation of a git tree object.
910
911 Args:
912 treeref (str) - a git ref which resolves to a tree (commits count as trees).
qyearsley12fa6ff2016-08-24 09:18:40 -0700913 recurse (bool) - include all of the tree's descendants too. File names will
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000914 take the form of 'some/path/to/file'.
915
916 Return format:
917 { 'file_name': (mode, type, ref) }
918
919 mode is an integer where:
920 * 0040000 - Directory
921 * 0100644 - Regular non-executable file
922 * 0100664 - Regular non-executable group-writeable file
923 * 0100755 - Regular executable file
924 * 0120000 - Symbolic link
925 * 0160000 - Gitlink
926
927 type is a string where it's one of 'blob', 'commit', 'tree', 'tag'.
928
929 ref is the hex encoded hash of the entry.
930 """
931 ret = {}
932 opts = ['ls-tree', '--full-tree']
933 if recurse:
934 opts.append('-r')
935 opts.append(treeref)
936 try:
937 for line in run(*opts).splitlines():
938 mode, typ, ref, name = line.split(None, 3)
939 ret[name] = (mode, typ, ref)
940 except subprocess2.CalledProcessError:
941 return None
942 return ret
943
944
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000945def upstream(branch):
946 try:
947 return run('rev-parse', '--abbrev-ref', '--symbolic-full-name',
948 branch+'@{upstream}')
949 except subprocess2.CalledProcessError:
950 return None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000951
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000952
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000953def get_git_version():
954 """Returns a tuple that contains the numeric components of the current git
955 version."""
956 version_string = run('--version')
957 version_match = re.search(r'(\d+.)+(\d+)', version_string)
958 version = version_match.group() if version_match else ''
959
960 return tuple(int(x) for x in version.split('.'))
961
962
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000963def get_branches_info(include_tracking_status):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000964 format_string = (
965 '--format=%(refname:short):%(objectname:short):%(upstream:short):')
966
967 # This is not covered by the depot_tools CQ which only has git version 1.8.
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000968 if (include_tracking_status and
969 get_git_version() >= MIN_UPSTREAM_TRACK_GIT_VERSION): # pragma: no cover
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000970 format_string += '%(upstream:track)'
971
972 info_map = {}
973 data = run('for-each-ref', format_string, 'refs/heads')
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000974 BranchesInfo = collections.namedtuple(
975 'BranchesInfo', 'hash upstream ahead behind')
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000976 for line in data.splitlines():
977 (branch, branch_hash, upstream_branch, tracking_status) = line.split(':')
978
979 ahead_match = re.search(r'ahead (\d+)', tracking_status)
980 ahead = int(ahead_match.group(1)) if ahead_match else None
981
982 behind_match = re.search(r'behind (\d+)', tracking_status)
983 behind = int(behind_match.group(1)) if behind_match else None
984
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000985 info_map[branch] = BranchesInfo(
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000986 hash=branch_hash, upstream=upstream_branch, ahead=ahead, behind=behind)
987
988 # Set None for upstreams which are not branches (e.g empty upstream, remotes
989 # and deleted upstream branches).
990 missing_upstreams = {}
991 for info in info_map.values():
992 if info.upstream not in info_map and info.upstream not in missing_upstreams:
993 missing_upstreams[info.upstream] = None
994
995 return dict(info_map.items() + missing_upstreams.items())
sammc@chromium.org900a33f2015-09-29 06:57:09 +0000996
997
998def make_workdir_common(repository, new_workdir, files_to_symlink,
scottmg@chromium.orgd4218d42015-10-07 23:49:20 +0000999 files_to_copy, symlink=None):
1000 if not symlink:
1001 symlink = os.symlink
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001002 os.makedirs(new_workdir)
1003 for entry in files_to_symlink:
scottmg@chromium.orgd4218d42015-10-07 23:49:20 +00001004 clone_file(repository, new_workdir, entry, symlink)
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001005 for entry in files_to_copy:
1006 clone_file(repository, new_workdir, entry, shutil.copy)
1007
1008
1009def make_workdir(repository, new_workdir):
1010 GIT_DIRECTORY_WHITELIST = [
1011 'config',
1012 'info',
1013 'hooks',
1014 'logs/refs',
1015 'objects',
1016 'packed-refs',
1017 'refs',
1018 'remotes',
1019 'rr-cache',
sammc@chromium.org900a33f2015-09-29 06:57:09 +00001020 ]
1021 make_workdir_common(repository, new_workdir, GIT_DIRECTORY_WHITELIST,
1022 ['HEAD'])
1023
1024
1025def clone_file(repository, new_workdir, link, operation):
1026 if not os.path.exists(os.path.join(repository, link)):
1027 return
1028 link_dir = os.path.dirname(os.path.join(new_workdir, link))
1029 if not os.path.exists(link_dir):
1030 os.makedirs(link_dir)
1031 operation(os.path.join(repository, link), os.path.join(new_workdir, link))