blob: 03d99ee3f058cf0a0b8d6dd8363c36ebe06dfa92 [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
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000051# Retry a git operation if git returns a error response with any of these
52# messages. It's all observed 'bad' GoB responses so far.
53#
54# This list is inspired/derived from the one in ChromiumOS's Chromite:
55# <CHROMITE>/lib/git.py::GIT_TRANSIENT_ERRORS
56#
57# It was last imported from '7add3ac29564d98ac35ce426bc295e743e7c0c02'.
58GIT_TRANSIENT_ERRORS = (
59 # crbug.com/285832
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000060 r'!.*\[remote rejected\].*\(error in hook\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000061
62 # crbug.com/289932
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000063 r'!.*\[remote rejected\].*\(failed to lock\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000064
65 # crbug.com/307156
iannucci@chromium.org6e95d402014-08-29 22:10:55 +000066 r'!.*\[remote rejected\].*\(error in Gerrit backend\)',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000067
68 # crbug.com/285832
69 r'remote error: Internal Server Error',
70
71 # crbug.com/294449
72 r'fatal: Couldn\'t find remote ref ',
73
74 # crbug.com/220543
75 r'git fetch_pack: expected ACK/NAK, got',
76
77 # crbug.com/189455
78 r'protocol error: bad pack header',
79
80 # crbug.com/202807
81 r'The remote end hung up unexpectedly',
82
83 # crbug.com/298189
84 r'TLS packet with unexpected length was received',
85
86 # crbug.com/187444
87 r'RPC failed; result=\d+, HTTP code = \d+',
88
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000089 # crbug.com/388876
90 r'Connection timed out',
dnj@chromium.org45cddd62014-11-06 19:36:42 +000091
92 # crbug.com/430343
93 # TODO(dnj): Resync with Chromite.
94 r'The requested URL returned error: 5\d+',
dnj@chromium.orgde219ec2014-07-28 17:39:08 +000095)
96
97GIT_TRANSIENT_ERRORS_RE = re.compile('|'.join(GIT_TRANSIENT_ERRORS),
98 re.IGNORECASE)
99
raphael.kubo.da.costa@intel.com58d05b02015-06-24 08:54:41 +0000100# git's for-each-ref command first supported the upstream:track token in its
101# format string in version 1.9.0, but some usages were broken until 2.3.0.
102# See git commit b6160d95 for more information.
103MIN_UPSTREAM_TRACK_GIT_VERSION = (2, 3)
dnj@chromium.orgde219ec2014-07-28 17:39:08 +0000104
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000105class BadCommitRefException(Exception):
106 def __init__(self, refs):
107 msg = ('one of %s does not seem to be a valid commitref.' %
108 str(refs))
109 super(BadCommitRefException, self).__init__(msg)
110
111
112def memoize_one(**kwargs):
113 """Memoizes a single-argument pure function.
114
115 Values of None are not cached.
116
117 Kwargs:
118 threadsafe (bool) - REQUIRED. Specifies whether to use locking around
119 cache manipulation functions. This is a kwarg so that users of memoize_one
120 are forced to explicitly and verbosely pick True or False.
121
122 Adds three methods to the decorated function:
123 * get(key, default=None) - Gets the value for this key from the cache.
124 * set(key, value) - Sets the value for this key from the cache.
125 * clear() - Drops the entire contents of the cache. Useful for unittests.
126 * update(other) - Updates the contents of the cache from another dict.
127 """
128 assert 'threadsafe' in kwargs, 'Must specify threadsafe={True,False}'
129 threadsafe = kwargs['threadsafe']
130
131 if threadsafe:
132 def withlock(lock, f):
133 def inner(*args, **kwargs):
134 with lock:
135 return f(*args, **kwargs)
136 return inner
137 else:
138 def withlock(_lock, f):
139 return f
140
141 def decorator(f):
142 # Instantiate the lock in decorator, in case users of memoize_one do:
143 #
144 # memoizer = memoize_one(threadsafe=True)
145 #
146 # @memoizer
147 # def fn1(val): ...
148 #
149 # @memoizer
150 # def fn2(val): ...
151
152 lock = threading.Lock() if threadsafe else None
153 cache = {}
154 _get = withlock(lock, cache.get)
155 _set = withlock(lock, cache.__setitem__)
156
157 @functools.wraps(f)
158 def inner(arg):
159 ret = _get(arg)
160 if ret is None:
161 ret = f(arg)
162 if ret is not None:
163 _set(arg, ret)
164 return ret
165 inner.get = _get
166 inner.set = _set
167 inner.clear = withlock(lock, cache.clear)
168 inner.update = withlock(lock, cache.update)
169 return inner
170 return decorator
171
172
173def _ScopedPool_initer(orig, orig_args): # pragma: no cover
174 """Initializer method for ScopedPool's subprocesses.
175
176 This helps ScopedPool handle Ctrl-C's correctly.
177 """
178 signal.signal(signal.SIGINT, signal.SIG_IGN)
179 if orig:
180 orig(*orig_args)
181
182
183@contextlib.contextmanager
184def ScopedPool(*args, **kwargs):
185 """Context Manager which returns a multiprocessing.pool instance which
186 correctly deals with thrown exceptions.
187
188 *args - Arguments to multiprocessing.pool
189
190 Kwargs:
191 kind ('threads', 'procs') - The type of underlying coprocess to use.
192 **etc - Arguments to multiprocessing.pool
193 """
194 if kwargs.pop('kind', None) == 'threads':
195 pool = multiprocessing.pool.ThreadPool(*args, **kwargs)
196 else:
197 orig, orig_args = kwargs.get('initializer'), kwargs.get('initargs', ())
198 kwargs['initializer'] = _ScopedPool_initer
199 kwargs['initargs'] = orig, orig_args
200 pool = multiprocessing.pool.Pool(*args, **kwargs)
201
202 try:
203 yield pool
204 pool.close()
205 except:
206 pool.terminate()
207 raise
208 finally:
209 pool.join()
210
211
212class ProgressPrinter(object):
213 """Threaded single-stat status message printer."""
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000214 def __init__(self, fmt, enabled=None, fout=sys.stderr, period=0.5):
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000215 """Create a ProgressPrinter.
216
217 Use it as a context manager which produces a simple 'increment' method:
218
219 with ProgressPrinter('(%%(count)d/%d)' % 1000) as inc:
220 for i in xrange(1000):
221 # do stuff
222 if i % 10 == 0:
223 inc(10)
224
225 Args:
226 fmt - String format with a single '%(count)d' where the counter value
227 should go.
228 enabled (bool) - If this is None, will default to True if
229 logging.getLogger() is set to INFO or more verbose.
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000230 fout (file-like) - The stream to print status messages to.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000231 period (float) - The time in seconds for the printer thread to wait
232 between printing.
233 """
234 self.fmt = fmt
235 if enabled is None: # pragma: no cover
236 self.enabled = logging.getLogger().isEnabledFor(logging.INFO)
237 else:
238 self.enabled = enabled
239
240 self._count = 0
241 self._dead = False
242 self._dead_cond = threading.Condition()
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000243 self._stream = fout
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000244 self._thread = threading.Thread(target=self._run)
245 self._period = period
246
247 def _emit(self, s):
248 if self.enabled:
249 self._stream.write('\r' + s)
250 self._stream.flush()
251
252 def _run(self):
253 with self._dead_cond:
254 while not self._dead:
255 self._emit(self.fmt % {'count': self._count})
256 self._dead_cond.wait(self._period)
257 self._emit((self.fmt + '\n') % {'count': self._count})
258
259 def inc(self, amount=1):
260 self._count += amount
261
262 def __enter__(self):
263 self._thread.start()
264 return self.inc
265
266 def __exit__(self, _exc_type, _exc_value, _traceback):
267 self._dead = True
268 with self._dead_cond:
269 self._dead_cond.notifyAll()
270 self._thread.join()
271 del self._thread
272
273
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000274def once(function):
275 """@Decorates |function| so that it only performs its action once, no matter
276 how many times the decorated |function| is called."""
277 def _inner_gen():
278 yield function()
279 while True:
280 yield
281 return _inner_gen().next
282
283
284## Git functions
285
agable7aa2ddd2016-06-21 07:47:00 -0700286def die(message, *args):
287 print >> sys.stderr, textwrap.dedent(message % args)
288 sys.exit(1)
289
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000290
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +0000291def blame(filename, revision=None, porcelain=False, *_args):
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000292 command = ['blame']
293 if porcelain:
294 command.append('-p')
295 if revision is not None:
296 command.append(revision)
297 command.extend(['--', filename])
298 return run(*command)
299
300
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000301def branch_config(branch, option, default=None):
agable7aa2ddd2016-06-21 07:47:00 -0700302 return get_config('branch.%s.%s' % (branch, option), default=default)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000303
304
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000305def branch_config_map(option):
306 """Return {branch: <|option| value>} for all branches."""
307 try:
308 reg = re.compile(r'^branch\.(.*)\.%s$' % option)
agable7aa2ddd2016-06-21 07:47:00 -0700309 lines = get_config_regexp(reg.pattern)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000310 return {reg.match(k).group(1): v for k, v in (l.split() for l in lines)}
311 except subprocess2.CalledProcessError:
312 return {}
313
314
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000315def branches(*args):
akuegel@chromium.org58888e12015-06-09 15:26:37 +0000316 NO_BRANCH = ('* (no branch', '* (detached', '* (HEAD detached')
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000317
318 key = 'depot-tools.branch-limit'
agable7aa2ddd2016-06-21 07:47:00 -0700319 limit = get_config_int(key, 20)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000320
321 raw_branches = run('branch', *args).splitlines()
322
323 num = len(raw_branches)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000324
agable7aa2ddd2016-06-21 07:47:00 -0700325 if num > limit:
326 die("""\
327 Your git repo has too many branches (%d/%d) for this tool to work well.
328
329 You may adjust this limit by running:
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000330 git config %s <new_limit>
agable7aa2ddd2016-06-21 07:47:00 -0700331
332 You may also try cleaning up your old branches by running:
333 git cl archive
334 """, num, limit, key)
iannucci@chromium.org3f23cdf2014-04-15 20:02:44 +0000335
336 for line in raw_branches:
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000337 if line.startswith(NO_BRANCH):
338 continue
339 yield line.split()[-1]
340
341
agable7aa2ddd2016-06-21 07:47:00 -0700342def get_config(option, default=None):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000343 try:
344 return run('config', '--get', option) or default
345 except subprocess2.CalledProcessError:
346 return default
347
348
agable7aa2ddd2016-06-21 07:47:00 -0700349def get_config_int(option, default=0):
350 assert isinstance(default, int)
351 try:
352 return int(get_config(option, default))
353 except ValueError:
354 return default
355
356
357def get_config_list(option):
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000358 try:
359 return run('config', '--get-all', option).split()
360 except subprocess2.CalledProcessError:
361 return []
362
363
agable7aa2ddd2016-06-21 07:47:00 -0700364def get_config_regexp(pattern):
365 if IS_WIN: # pragma: no cover
366 # this madness is because we call git.bat which calls git.exe which calls
367 # bash.exe (or something to that effect). Each layer divides the number of
368 # ^'s by 2.
369 pattern = pattern.replace('^', '^' * 8)
370 return run('config', '--get-regexp', pattern).splitlines()
371
372
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000373def current_branch():
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000374 try:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000375 return run('rev-parse', '--abbrev-ref', 'HEAD')
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000376 except subprocess2.CalledProcessError:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000377 return None
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000378
379
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000380def del_branch_config(branch, option, scope='local'):
381 del_config('branch.%s.%s' % (branch, option), scope=scope)
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000382
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000383
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000384def del_config(option, scope='local'):
385 try:
386 run('config', '--' + scope, '--unset', option)
387 except subprocess2.CalledProcessError:
388 pass
389
390
mgiuca@chromium.org01d2cde2016-02-05 03:25:41 +0000391def diff(oldrev, newrev, *args):
392 return run('diff', oldrev, newrev, *args)
393
394
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000395def freeze():
396 took_action = False
agable02b3c982016-06-22 07:51:22 -0700397 key = 'depot-tools.freeze-size-limit'
398 MB = 2**20
399 limit_mb = get_config_int(key, 100)
400 untracked_bytes = 0
401
402 for f, s in status():
403 if is_unmerged(s):
404 die("Cannot freeze unmerged changes!")
405 if limit_mb > 0:
406 if s.lstat == '?':
407 untracked_bytes += os.stat(f).st_size
408 if untracked_bytes > limit_mb * MB:
409 die("""\
410 You appear to have too much untracked+unignored data in your git
411 checkout: %.1f / %d MB.
412
413 Run `git status` to see what it is.
414
415 In addition to making many git commands slower, this will prevent
416 depot_tools from freezing your in-progress changes.
417
418 You should add untracked data that you want to ignore to your repo's
419 .git/info/excludes
420 file. See `git help ignore` for the format of this file.
421
422 If this data is indended as part of your commit, you may adjust the
423 freeze limit by running:
424 git config %s <new_limit>
425 Where <new_limit> is an integer threshold in megabytes.""",
426 untracked_bytes / (MB * 1.0), limit_mb, key)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000427
428 try:
iannucci@chromium.org3b4f2282015-09-17 15:46:00 +0000429 run('commit', '--no-verify', '-m', FREEZE + '.indexed')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000430 took_action = True
431 except subprocess2.CalledProcessError:
432 pass
433
434 try:
435 run('add', '-A')
iannucci@chromium.org3b4f2282015-09-17 15:46:00 +0000436 run('commit', '--no-verify', '-m', FREEZE + '.unindexed')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000437 took_action = True
438 except subprocess2.CalledProcessError:
439 pass
440
441 if not took_action:
442 return 'Nothing to freeze.'
443
444
445def get_branch_tree():
446 """Get the dictionary of {branch: parent}, compatible with topo_iter.
447
448 Returns a tuple of (skipped, <branch_tree dict>) where skipped is a set of
449 branches without upstream branches defined.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000450 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000451 skipped = set()
452 branch_tree = {}
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000453
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000454 for branch in branches():
455 parent = upstream(branch)
456 if not parent:
457 skipped.add(branch)
458 continue
459 branch_tree[branch] = parent
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000460
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000461 return skipped, branch_tree
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000462
463
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000464def get_or_create_merge_base(branch, parent=None):
465 """Finds the configured merge base for branch.
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000466
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000467 If parent is supplied, it's used instead of calling upstream(branch).
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000468 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000469 base = branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000470 base_upstream = branch_config(branch, 'base-upstream')
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000471 parent = parent or upstream(branch)
sbc@chromium.org79706062015-01-14 21:18:12 +0000472 if parent is None or branch is None:
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000473 return None
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000474 actual_merge_base = run('merge-base', parent, branch)
475
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000476 if base_upstream != parent:
477 base = None
478 base_upstream = None
479
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000480 def is_ancestor(a, b):
481 return run_with_retcode('merge-base', '--is-ancestor', a, b) == 0
482
clemensh@chromium.orgc3fe99d2016-04-19 08:39:55 +0000483 if base and base != actual_merge_base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000484 if not is_ancestor(base, branch):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000485 logging.debug('Found WRONG pre-set merge-base for %s: %s', branch, base)
486 base = None
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000487 elif is_ancestor(base, actual_merge_base):
488 logging.debug('Found OLD pre-set merge-base for %s: %s', branch, base)
489 base = None
490 else:
491 logging.debug('Found pre-set merge-base for %s: %s', branch, base)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000492
493 if not base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000494 base = actual_merge_base
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000495 manual_merge_base(branch, base, parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000496
497 return base
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000498
499
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000500def hash_multi(*reflike):
501 return run('rev-parse', *reflike).splitlines()
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000502
503
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000504def hash_one(reflike, short=False):
505 args = ['rev-parse', reflike]
506 if short:
507 args.insert(1, '--short')
508 return run(*args)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000509
510
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000511def in_rebase():
512 git_dir = run('rev-parse', '--git-dir')
513 return (
514 os.path.exists(os.path.join(git_dir, 'rebase-merge')) or
515 os.path.exists(os.path.join(git_dir, 'rebase-apply')))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000516
517
518def intern_f(f, kind='blob'):
519 """Interns a file object into the git object store.
520
521 Args:
522 f (file-like object) - The file-like object to intern
523 kind (git object type) - One of 'blob', 'commit', 'tree', 'tag'.
524
525 Returns the git hash of the interned object (hex encoded).
526 """
527 ret = run('hash-object', '-t', kind, '-w', '--stdin', stdin=f)
528 f.close()
529 return ret
530
531
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000532def is_dormant(branch):
533 # TODO(iannucci): Do an oldness check?
534 return branch_config(branch, 'dormant', 'false') != 'false'
535
536
agable02b3c982016-06-22 07:51:22 -0700537def is_unmerged(stat_value):
538 return (
539 'U' in (stat_value.lstat, stat_value.rstat) or
540 ((stat_value.lstat == stat_value.rstat) and stat_value.lstat in 'AD')
541 )
542
543
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000544def manual_merge_base(branch, base, parent):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000545 set_branch_config(branch, 'base', base)
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000546 set_branch_config(branch, 'base-upstream', parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000547
548
549def mktree(treedict):
550 """Makes a git tree object and returns its hash.
551
552 See |tree()| for the values of mode, type, and ref.
553
554 Args:
555 treedict - { name: (mode, type, ref) }
556 """
557 with tempfile.TemporaryFile() as f:
558 for name, (mode, typ, ref) in treedict.iteritems():
559 f.write('%s %s %s\t%s\0' % (mode, typ, ref, name))
560 f.seek(0)
561 return run('mktree', '-z', stdin=f)
562
563
564def parse_commitrefs(*commitrefs):
565 """Returns binary encoded commit hashes for one or more commitrefs.
566
567 A commitref is anything which can resolve to a commit. Popular examples:
568 * 'HEAD'
569 * 'origin/master'
570 * 'cool_branch~2'
571 """
572 try:
573 return map(binascii.unhexlify, hash_multi(*commitrefs))
574 except subprocess2.CalledProcessError:
575 raise BadCommitRefException(commitrefs)
576
577
sbc@chromium.org384039b2014-10-13 21:01:00 +0000578RebaseRet = collections.namedtuple('RebaseRet', 'success stdout stderr')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000579
580
581def rebase(parent, start, branch, abort=False):
582 """Rebases |start|..|branch| onto the branch |parent|.
583
584 Args:
585 parent - The new parent ref for the rebased commits.
586 start - The commit to start from
587 branch - The branch to rebase
588 abort - If True, will call git-rebase --abort in the event that the rebase
589 doesn't complete successfully.
590
591 Returns a namedtuple with fields:
592 success - a boolean indicating that the rebase command completed
593 successfully.
594 message - if the rebase failed, this contains the stdout of the failed
595 rebase.
596 """
597 try:
598 args = ['--onto', parent, start, branch]
599 if TEST_MODE:
600 args.insert(0, '--committer-date-is-author-date')
601 run('rebase', *args)
sbc@chromium.org384039b2014-10-13 21:01:00 +0000602 return RebaseRet(True, '', '')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000603 except subprocess2.CalledProcessError as cpe:
604 if abort:
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000605 run_with_retcode('rebase', '--abort') # ignore failure
sbc@chromium.org384039b2014-10-13 21:01:00 +0000606 return RebaseRet(False, cpe.stdout, cpe.stderr)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000607
608
609def remove_merge_base(branch):
610 del_branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000611 del_branch_config(branch, 'base-upstream')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000612
613
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000614def repo_root():
615 """Returns the absolute path to the repository root."""
616 return run('rev-parse', '--show-toplevel')
617
618
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000619def root():
agable7aa2ddd2016-06-21 07:47:00 -0700620 return get_config('depot-tools.upstream', 'origin/master')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000621
622
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000623@contextlib.contextmanager
624def less(): # pragma: no cover
625 """Runs 'less' as context manager yielding its stdin as a PIPE.
626
627 Automatically checks if sys.stdout is a non-TTY stream. If so, it avoids
628 running less and just yields sys.stdout.
629 """
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +0000630 if not setup_color.IS_TTY:
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000631 yield sys.stdout
632 return
633
634 # Run with the same options that git uses (see setup_pager in git repo).
635 # -F: Automatically quit if the output is less than one screen.
636 # -R: Don't escape ANSI color codes.
637 # -X: Don't clear the screen before starting.
638 cmd = ('less', '-FRX')
639 try:
640 proc = subprocess2.Popen(cmd, stdin=subprocess2.PIPE)
641 yield proc.stdin
642 finally:
643 proc.stdin.close()
644 proc.wait()
645
646
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000647def run(*cmd, **kwargs):
648 """The same as run_with_stderr, except it only returns stdout."""
649 return run_with_stderr(*cmd, **kwargs)[0]
650
651
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000652def run_with_retcode(*cmd, **kwargs):
653 """Run a command but only return the status code."""
654 try:
655 run(*cmd, **kwargs)
656 return 0
657 except subprocess2.CalledProcessError as cpe:
658 return cpe.returncode
659
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000660def run_stream(*cmd, **kwargs):
661 """Runs a git command. Returns stdout as a PIPE (file-like object).
662
663 stderr is dropped to avoid races if the process outputs to both stdout and
664 stderr.
665 """
666 kwargs.setdefault('stderr', subprocess2.VOID)
667 kwargs.setdefault('stdout', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000668 kwargs.setdefault('shell', False)
iannucci@chromium.org21980022014-04-11 04:51:49 +0000669 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000670 proc = subprocess2.Popen(cmd, **kwargs)
671 return proc.stdout
672
673
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000674@contextlib.contextmanager
675def run_stream_with_retcode(*cmd, **kwargs):
676 """Runs a git command as context manager yielding stdout as a PIPE.
677
678 stderr is dropped to avoid races if the process outputs to both stdout and
679 stderr.
680
681 Raises subprocess2.CalledProcessError on nonzero return code.
682 """
683 kwargs.setdefault('stderr', subprocess2.VOID)
684 kwargs.setdefault('stdout', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000685 kwargs.setdefault('shell', False)
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000686 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
687 try:
688 proc = subprocess2.Popen(cmd, **kwargs)
689 yield proc.stdout
690 finally:
691 retcode = proc.wait()
692 if retcode != 0:
693 raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(),
694 None, None)
695
696
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000697def run_with_stderr(*cmd, **kwargs):
698 """Runs a git command.
699
700 Returns (stdout, stderr) as a pair of strings.
701
702 kwargs
703 autostrip (bool) - Strip the output. Defaults to True.
704 indata (str) - Specifies stdin data for the process.
705 """
706 kwargs.setdefault('stdin', subprocess2.PIPE)
707 kwargs.setdefault('stdout', subprocess2.PIPE)
708 kwargs.setdefault('stderr', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000709 kwargs.setdefault('shell', False)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000710 autostrip = kwargs.pop('autostrip', True)
711 indata = kwargs.pop('indata', None)
712
iannucci@chromium.org21980022014-04-11 04:51:49 +0000713 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000714 proc = subprocess2.Popen(cmd, **kwargs)
715 ret, err = proc.communicate(indata)
716 retcode = proc.wait()
717 if retcode != 0:
718 raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(), ret, err)
719
720 if autostrip:
721 ret = (ret or '').strip()
722 err = (err or '').strip()
723
724 return ret, err
725
726
727def set_branch_config(branch, option, value, scope='local'):
728 set_config('branch.%s.%s' % (branch, option), value, scope=scope)
729
730
731def set_config(option, value, scope='local'):
732 run('config', '--' + scope, option, value)
733
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000734
sbc@chromium.org71437c02015-04-09 19:29:40 +0000735def get_dirty_files():
736 # Make sure index is up-to-date before running diff-index.
737 run_with_retcode('update-index', '--refresh', '-q')
738 return run('diff-index', '--name-status', 'HEAD')
739
740
741def is_dirty_git_tree(cmd):
742 dirty = get_dirty_files()
743 if dirty:
744 print 'Cannot %s with a dirty tree. You must commit locally first.' % cmd
745 print 'Uncommitted files: (git diff-index --name-status HEAD)'
746 print dirty[:4096]
747 if len(dirty) > 4096: # pragma: no cover
748 print '... (run "git diff-index --name-status HEAD" to see full output).'
749 return True
750 return False
751
752
agable02b3c982016-06-22 07:51:22 -0700753def status():
754 """Returns a parsed version of git-status.
755
756 Returns a generator of (current_name, (lstat, rstat, src)) pairs where:
757 * current_name is the name of the file
758 * lstat is the left status code letter from git-status
759 * rstat is the left status code letter from git-status
760 * src is the current name of the file, or the original name of the file
761 if lstat == 'R'
762 """
763 stat_entry = collections.namedtuple('stat_entry', 'lstat rstat src')
764
765 def tokenizer(stream):
766 acc = StringIO()
767 c = None
768 while c != '':
769 c = stream.read(1)
770 if c in (None, '', '\0'):
771 if acc.len:
772 yield acc.getvalue()
773 acc = StringIO()
774 else:
775 acc.write(c)
776
777 def parser(tokens):
778 while True:
779 # Raises StopIteration if it runs out of tokens.
780 status_dest = next(tokens)
781 stat, dest = status_dest[:2], status_dest[3:]
782 lstat, rstat = stat
783 if lstat == 'R':
784 src = next(tokens)
785 else:
786 src = dest
787 yield (dest, stat_entry(lstat, rstat, src))
788
789 return parser(tokenizer(run_stream('status', '-z', bufsize=-1)))
790
791
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000792def squash_current_branch(header=None, merge_base=None):
793 header = header or 'git squash commit.'
794 merge_base = merge_base or get_or_create_merge_base(current_branch())
795 log_msg = header + '\n'
796 if log_msg:
797 log_msg += '\n'
798 log_msg += run('log', '--reverse', '--format=%H%n%B', '%s..HEAD' % merge_base)
799 run('reset', '--soft', merge_base)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000800
801 if not get_dirty_files():
802 # Sometimes the squash can result in the same tree, meaning that there is
803 # nothing to commit at this point.
804 print 'Nothing to commit; squashed branch is empty'
805 return False
maruel@chromium.org25b9ab22015-06-18 18:49:03 +0000806 run('commit', '--no-verify', '-a', '-F', '-', indata=log_msg)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000807 return True
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000808
809
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000810def tags(*args):
811 return run('tag', *args).splitlines()
812
813
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000814def thaw():
815 took_action = False
816 for sha in (s.strip() for s in run_stream('rev-list', 'HEAD').xreadlines()):
817 msg = run('show', '--format=%f%b', '-s', 'HEAD')
818 match = FREEZE_MATCHER.match(msg)
819 if not match:
820 if not took_action:
821 return 'Nothing to thaw.'
822 break
823
824 run('reset', '--' + FREEZE_SECTIONS[match.group(1)], sha)
825 took_action = True
826
827
828def topo_iter(branch_tree, top_down=True):
829 """Generates (branch, parent) in topographical order for a branch tree.
830
831 Given a tree:
832
833 A1
834 B1 B2
835 C1 C2 C3
836 D1
837
838 branch_tree would look like: {
839 'D1': 'C3',
840 'C3': 'B2',
841 'B2': 'A1',
842 'C1': 'B1',
843 'C2': 'B1',
844 'B1': 'A1',
845 }
846
847 It is OK to have multiple 'root' nodes in your graph.
848
849 if top_down is True, items are yielded from A->D. Otherwise they're yielded
850 from D->A. Within a layer the branches will be yielded in sorted order.
851 """
852 branch_tree = branch_tree.copy()
853
854 # TODO(iannucci): There is probably a more efficient way to do these.
855 if top_down:
856 while branch_tree:
857 this_pass = [(b, p) for b, p in branch_tree.iteritems()
858 if p not in branch_tree]
859 assert this_pass, "Branch tree has cycles: %r" % branch_tree
860 for branch, parent in sorted(this_pass):
861 yield branch, parent
862 del branch_tree[branch]
863 else:
864 parent_to_branches = collections.defaultdict(set)
865 for branch, parent in branch_tree.iteritems():
866 parent_to_branches[parent].add(branch)
867
868 while branch_tree:
869 this_pass = [(b, p) for b, p in branch_tree.iteritems()
870 if not parent_to_branches[b]]
871 assert this_pass, "Branch tree has cycles: %r" % branch_tree
872 for branch, parent in sorted(this_pass):
873 yield branch, parent
874 parent_to_branches[parent].discard(branch)
875 del branch_tree[branch]
876
877
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000878def tree(treeref, recurse=False):
879 """Returns a dict representation of a git tree object.
880
881 Args:
882 treeref (str) - a git ref which resolves to a tree (commits count as trees).
883 recurse (bool) - include all of the tree's decendants too. File names will
884 take the form of 'some/path/to/file'.
885
886 Return format:
887 { 'file_name': (mode, type, ref) }
888
889 mode is an integer where:
890 * 0040000 - Directory
891 * 0100644 - Regular non-executable file
892 * 0100664 - Regular non-executable group-writeable file
893 * 0100755 - Regular executable file
894 * 0120000 - Symbolic link
895 * 0160000 - Gitlink
896
897 type is a string where it's one of 'blob', 'commit', 'tree', 'tag'.
898
899 ref is the hex encoded hash of the entry.
900 """
901 ret = {}
902 opts = ['ls-tree', '--full-tree']
903 if recurse:
904 opts.append('-r')
905 opts.append(treeref)
906 try:
907 for line in run(*opts).splitlines():
908 mode, typ, ref, name = line.split(None, 3)
909 ret[name] = (mode, typ, ref)
910 except subprocess2.CalledProcessError:
911 return None
912 return ret
913
914
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000915def upstream(branch):
916 try:
917 return run('rev-parse', '--abbrev-ref', '--symbolic-full-name',
918 branch+'@{upstream}')
919 except subprocess2.CalledProcessError:
920 return None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000921
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000922
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000923def get_git_version():
924 """Returns a tuple that contains the numeric components of the current git
925 version."""
926 version_string = run('--version')
927 version_match = re.search(r'(\d+.)+(\d+)', version_string)
928 version = version_match.group() if version_match else ''
929
930 return tuple(int(x) for x in version.split('.'))
931
932
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000933def get_branches_info(include_tracking_status):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000934 format_string = (
935 '--format=%(refname:short):%(objectname:short):%(upstream:short):')
936
937 # This is not covered by the depot_tools CQ which only has git version 1.8.
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000938 if (include_tracking_status and
939 get_git_version() >= MIN_UPSTREAM_TRACK_GIT_VERSION): # pragma: no cover
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000940 format_string += '%(upstream:track)'
941
942 info_map = {}
943 data = run('for-each-ref', format_string, 'refs/heads')
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000944 BranchesInfo = collections.namedtuple(
945 'BranchesInfo', 'hash upstream ahead behind')
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000946 for line in data.splitlines():
947 (branch, branch_hash, upstream_branch, tracking_status) = line.split(':')
948
949 ahead_match = re.search(r'ahead (\d+)', tracking_status)
950 ahead = int(ahead_match.group(1)) if ahead_match else None
951
952 behind_match = re.search(r'behind (\d+)', tracking_status)
953 behind = int(behind_match.group(1)) if behind_match else None
954
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000955 info_map[branch] = BranchesInfo(
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000956 hash=branch_hash, upstream=upstream_branch, ahead=ahead, behind=behind)
957
958 # Set None for upstreams which are not branches (e.g empty upstream, remotes
959 # and deleted upstream branches).
960 missing_upstreams = {}
961 for info in info_map.values():
962 if info.upstream not in info_map and info.upstream not in missing_upstreams:
963 missing_upstreams[info.upstream] = None
964
965 return dict(info_map.items() + missing_upstreams.items())
sammc@chromium.org900a33f2015-09-29 06:57:09 +0000966
967
968def make_workdir_common(repository, new_workdir, files_to_symlink,
scottmg@chromium.orgd4218d42015-10-07 23:49:20 +0000969 files_to_copy, symlink=None):
970 if not symlink:
971 symlink = os.symlink
sammc@chromium.org900a33f2015-09-29 06:57:09 +0000972 os.makedirs(new_workdir)
973 for entry in files_to_symlink:
scottmg@chromium.orgd4218d42015-10-07 23:49:20 +0000974 clone_file(repository, new_workdir, entry, symlink)
sammc@chromium.org900a33f2015-09-29 06:57:09 +0000975 for entry in files_to_copy:
976 clone_file(repository, new_workdir, entry, shutil.copy)
977
978
979def make_workdir(repository, new_workdir):
980 GIT_DIRECTORY_WHITELIST = [
981 'config',
982 'info',
983 'hooks',
984 'logs/refs',
985 'objects',
986 'packed-refs',
987 'refs',
988 'remotes',
989 'rr-cache',
990 'svn'
991 ]
992 make_workdir_common(repository, new_workdir, GIT_DIRECTORY_WHITELIST,
993 ['HEAD'])
994
995
996def clone_file(repository, new_workdir, link, operation):
997 if not os.path.exists(os.path.join(repository, link)):
998 return
999 link_dir = os.path.dirname(os.path.join(new_workdir, link))
1000 if not os.path.exists(link_dir):
1001 os.makedirs(link_dir)
1002 operation(os.path.join(repository, link), os.path.join(new_workdir, link))