blob: 9ccbbc35a6344adc5cd85abf3dc09d02219c82c2 [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
agable96e179b2016-06-24 10:32:51 -0700434 add_errors = False
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000435 try:
agable96e179b2016-06-24 10:32:51 -0700436 run('add', '-A', '--ignore-errors')
437 except subprocess2.CalledProcessError:
438 add_errors = True
439
440 try:
iannucci@chromium.org3b4f2282015-09-17 15:46:00 +0000441 run('commit', '--no-verify', '-m', FREEZE + '.unindexed')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000442 took_action = True
443 except subprocess2.CalledProcessError:
444 pass
445
agable96e179b2016-06-24 10:32:51 -0700446 ret = []
447 if add_errors:
448 ret.append('Failed to index some unindexed files.')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000449 if not took_action:
agable96e179b2016-06-24 10:32:51 -0700450 ret.append('Nothing to freeze.')
451 return ' '.join(ret) or None
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000452
453
454def get_branch_tree():
455 """Get the dictionary of {branch: parent}, compatible with topo_iter.
456
457 Returns a tuple of (skipped, <branch_tree dict>) where skipped is a set of
458 branches without upstream branches defined.
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000459 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000460 skipped = set()
461 branch_tree = {}
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000462
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000463 for branch in branches():
464 parent = upstream(branch)
465 if not parent:
466 skipped.add(branch)
467 continue
468 branch_tree[branch] = parent
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000469
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000470 return skipped, branch_tree
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000471
472
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000473def get_or_create_merge_base(branch, parent=None):
474 """Finds the configured merge base for branch.
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000475
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000476 If parent is supplied, it's used instead of calling upstream(branch).
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000477 """
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000478 base = branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000479 base_upstream = branch_config(branch, 'base-upstream')
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000480 parent = parent or upstream(branch)
sbc@chromium.org79706062015-01-14 21:18:12 +0000481 if parent is None or branch is None:
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000482 return None
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000483 actual_merge_base = run('merge-base', parent, branch)
484
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000485 if base_upstream != parent:
486 base = None
487 base_upstream = None
488
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000489 def is_ancestor(a, b):
490 return run_with_retcode('merge-base', '--is-ancestor', a, b) == 0
491
clemensh@chromium.orgc3fe99d2016-04-19 08:39:55 +0000492 if base and base != actual_merge_base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000493 if not is_ancestor(base, branch):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000494 logging.debug('Found WRONG pre-set merge-base for %s: %s', branch, base)
495 base = None
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000496 elif is_ancestor(base, actual_merge_base):
497 logging.debug('Found OLD pre-set merge-base for %s: %s', branch, base)
498 base = None
499 else:
500 logging.debug('Found pre-set merge-base for %s: %s', branch, base)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000501
502 if not base:
iannucci@chromium.orgedeaa812014-03-26 21:27:47 +0000503 base = actual_merge_base
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000504 manual_merge_base(branch, base, parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000505
506 return base
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000507
508
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000509def hash_multi(*reflike):
510 return run('rev-parse', *reflike).splitlines()
iannucci@chromium.org97345eb2014-03-13 07:55:15 +0000511
512
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000513def hash_one(reflike, short=False):
514 args = ['rev-parse', reflike]
515 if short:
516 args.insert(1, '--short')
517 return run(*args)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000518
519
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000520def in_rebase():
521 git_dir = run('rev-parse', '--git-dir')
522 return (
523 os.path.exists(os.path.join(git_dir, 'rebase-merge')) or
524 os.path.exists(os.path.join(git_dir, 'rebase-apply')))
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000525
526
527def intern_f(f, kind='blob'):
528 """Interns a file object into the git object store.
529
530 Args:
531 f (file-like object) - The file-like object to intern
532 kind (git object type) - One of 'blob', 'commit', 'tree', 'tag'.
533
534 Returns the git hash of the interned object (hex encoded).
535 """
536 ret = run('hash-object', '-t', kind, '-w', '--stdin', stdin=f)
537 f.close()
538 return ret
539
540
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000541def is_dormant(branch):
542 # TODO(iannucci): Do an oldness check?
543 return branch_config(branch, 'dormant', 'false') != 'false'
544
545
agable02b3c982016-06-22 07:51:22 -0700546def is_unmerged(stat_value):
547 return (
548 'U' in (stat_value.lstat, stat_value.rstat) or
549 ((stat_value.lstat == stat_value.rstat) and stat_value.lstat in 'AD')
550 )
551
552
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000553def manual_merge_base(branch, base, parent):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000554 set_branch_config(branch, 'base', base)
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000555 set_branch_config(branch, 'base-upstream', parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000556
557
558def mktree(treedict):
559 """Makes a git tree object and returns its hash.
560
561 See |tree()| for the values of mode, type, and ref.
562
563 Args:
564 treedict - { name: (mode, type, ref) }
565 """
566 with tempfile.TemporaryFile() as f:
567 for name, (mode, typ, ref) in treedict.iteritems():
568 f.write('%s %s %s\t%s\0' % (mode, typ, ref, name))
569 f.seek(0)
570 return run('mktree', '-z', stdin=f)
571
572
573def parse_commitrefs(*commitrefs):
574 """Returns binary encoded commit hashes for one or more commitrefs.
575
576 A commitref is anything which can resolve to a commit. Popular examples:
577 * 'HEAD'
578 * 'origin/master'
579 * 'cool_branch~2'
580 """
581 try:
582 return map(binascii.unhexlify, hash_multi(*commitrefs))
583 except subprocess2.CalledProcessError:
584 raise BadCommitRefException(commitrefs)
585
586
sbc@chromium.org384039b2014-10-13 21:01:00 +0000587RebaseRet = collections.namedtuple('RebaseRet', 'success stdout stderr')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000588
589
590def rebase(parent, start, branch, abort=False):
591 """Rebases |start|..|branch| onto the branch |parent|.
592
593 Args:
594 parent - The new parent ref for the rebased commits.
595 start - The commit to start from
596 branch - The branch to rebase
597 abort - If True, will call git-rebase --abort in the event that the rebase
598 doesn't complete successfully.
599
600 Returns a namedtuple with fields:
601 success - a boolean indicating that the rebase command completed
602 successfully.
603 message - if the rebase failed, this contains the stdout of the failed
604 rebase.
605 """
606 try:
607 args = ['--onto', parent, start, branch]
608 if TEST_MODE:
609 args.insert(0, '--committer-date-is-author-date')
610 run('rebase', *args)
sbc@chromium.org384039b2014-10-13 21:01:00 +0000611 return RebaseRet(True, '', '')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000612 except subprocess2.CalledProcessError as cpe:
613 if abort:
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000614 run_with_retcode('rebase', '--abort') # ignore failure
sbc@chromium.org384039b2014-10-13 21:01:00 +0000615 return RebaseRet(False, cpe.stdout, cpe.stderr)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000616
617
618def remove_merge_base(branch):
619 del_branch_config(branch, 'base')
iannucci@chromium.org10fbe872014-05-16 22:31:13 +0000620 del_branch_config(branch, 'base-upstream')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000621
622
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000623def repo_root():
624 """Returns the absolute path to the repository root."""
625 return run('rev-parse', '--show-toplevel')
626
627
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000628def root():
agable7aa2ddd2016-06-21 07:47:00 -0700629 return get_config('depot-tools.upstream', 'origin/master')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000630
631
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000632@contextlib.contextmanager
633def less(): # pragma: no cover
634 """Runs 'less' as context manager yielding its stdin as a PIPE.
635
636 Automatically checks if sys.stdout is a non-TTY stream. If so, it avoids
637 running less and just yields sys.stdout.
638 """
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +0000639 if not setup_color.IS_TTY:
mgiuca@chromium.org81937562016-02-03 08:00:53 +0000640 yield sys.stdout
641 return
642
643 # Run with the same options that git uses (see setup_pager in git repo).
644 # -F: Automatically quit if the output is less than one screen.
645 # -R: Don't escape ANSI color codes.
646 # -X: Don't clear the screen before starting.
647 cmd = ('less', '-FRX')
648 try:
649 proc = subprocess2.Popen(cmd, stdin=subprocess2.PIPE)
650 yield proc.stdin
651 finally:
652 proc.stdin.close()
653 proc.wait()
654
655
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000656def run(*cmd, **kwargs):
657 """The same as run_with_stderr, except it only returns stdout."""
658 return run_with_stderr(*cmd, **kwargs)[0]
659
660
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000661def run_with_retcode(*cmd, **kwargs):
662 """Run a command but only return the status code."""
663 try:
664 run(*cmd, **kwargs)
665 return 0
666 except subprocess2.CalledProcessError as cpe:
667 return cpe.returncode
668
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000669def run_stream(*cmd, **kwargs):
670 """Runs a git command. Returns stdout as a PIPE (file-like object).
671
672 stderr is dropped to avoid races if the process outputs to both stdout and
673 stderr.
674 """
675 kwargs.setdefault('stderr', subprocess2.VOID)
676 kwargs.setdefault('stdout', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000677 kwargs.setdefault('shell', False)
iannucci@chromium.org21980022014-04-11 04:51:49 +0000678 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000679 proc = subprocess2.Popen(cmd, **kwargs)
680 return proc.stdout
681
682
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000683@contextlib.contextmanager
684def run_stream_with_retcode(*cmd, **kwargs):
685 """Runs a git command as context manager yielding stdout as a PIPE.
686
687 stderr is dropped to avoid races if the process outputs to both stdout and
688 stderr.
689
690 Raises subprocess2.CalledProcessError on nonzero return code.
691 """
692 kwargs.setdefault('stderr', subprocess2.VOID)
693 kwargs.setdefault('stdout', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000694 kwargs.setdefault('shell', False)
tandrii@chromium.org6c143102015-06-11 19:21:02 +0000695 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
696 try:
697 proc = subprocess2.Popen(cmd, **kwargs)
698 yield proc.stdout
699 finally:
700 retcode = proc.wait()
701 if retcode != 0:
702 raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(),
703 None, None)
704
705
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000706def run_with_stderr(*cmd, **kwargs):
707 """Runs a git command.
708
709 Returns (stdout, stderr) as a pair of strings.
710
711 kwargs
712 autostrip (bool) - Strip the output. Defaults to True.
713 indata (str) - Specifies stdin data for the process.
714 """
715 kwargs.setdefault('stdin', subprocess2.PIPE)
716 kwargs.setdefault('stdout', subprocess2.PIPE)
717 kwargs.setdefault('stderr', subprocess2.PIPE)
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +0000718 kwargs.setdefault('shell', False)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000719 autostrip = kwargs.pop('autostrip', True)
720 indata = kwargs.pop('indata', None)
721
iannucci@chromium.org21980022014-04-11 04:51:49 +0000722 cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000723 proc = subprocess2.Popen(cmd, **kwargs)
724 ret, err = proc.communicate(indata)
725 retcode = proc.wait()
726 if retcode != 0:
727 raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(), ret, err)
728
729 if autostrip:
730 ret = (ret or '').strip()
731 err = (err or '').strip()
732
733 return ret, err
734
735
736def set_branch_config(branch, option, value, scope='local'):
737 set_config('branch.%s.%s' % (branch, option), value, scope=scope)
738
739
740def set_config(option, value, scope='local'):
741 run('config', '--' + scope, option, value)
742
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000743
sbc@chromium.org71437c02015-04-09 19:29:40 +0000744def get_dirty_files():
745 # Make sure index is up-to-date before running diff-index.
746 run_with_retcode('update-index', '--refresh', '-q')
747 return run('diff-index', '--name-status', 'HEAD')
748
749
750def is_dirty_git_tree(cmd):
751 dirty = get_dirty_files()
752 if dirty:
753 print 'Cannot %s with a dirty tree. You must commit locally first.' % cmd
754 print 'Uncommitted files: (git diff-index --name-status HEAD)'
755 print dirty[:4096]
756 if len(dirty) > 4096: # pragma: no cover
757 print '... (run "git diff-index --name-status HEAD" to see full output).'
758 return True
759 return False
760
761
agable02b3c982016-06-22 07:51:22 -0700762def status():
763 """Returns a parsed version of git-status.
764
765 Returns a generator of (current_name, (lstat, rstat, src)) pairs where:
766 * current_name is the name of the file
767 * lstat is the left status code letter from git-status
768 * rstat is the left status code letter from git-status
769 * src is the current name of the file, or the original name of the file
770 if lstat == 'R'
771 """
772 stat_entry = collections.namedtuple('stat_entry', 'lstat rstat src')
773
774 def tokenizer(stream):
775 acc = StringIO()
776 c = None
777 while c != '':
778 c = stream.read(1)
779 if c in (None, '', '\0'):
780 if acc.len:
781 yield acc.getvalue()
782 acc = StringIO()
783 else:
784 acc.write(c)
785
786 def parser(tokens):
787 while True:
788 # Raises StopIteration if it runs out of tokens.
789 status_dest = next(tokens)
790 stat, dest = status_dest[:2], status_dest[3:]
791 lstat, rstat = stat
792 if lstat == 'R':
793 src = next(tokens)
794 else:
795 src = dest
796 yield (dest, stat_entry(lstat, rstat, src))
797
798 return parser(tokenizer(run_stream('status', '-z', bufsize=-1)))
799
800
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000801def squash_current_branch(header=None, merge_base=None):
802 header = header or 'git squash commit.'
803 merge_base = merge_base or get_or_create_merge_base(current_branch())
804 log_msg = header + '\n'
805 if log_msg:
806 log_msg += '\n'
807 log_msg += run('log', '--reverse', '--format=%H%n%B', '%s..HEAD' % merge_base)
808 run('reset', '--soft', merge_base)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000809
810 if not get_dirty_files():
811 # Sometimes the squash can result in the same tree, meaning that there is
812 # nothing to commit at this point.
813 print 'Nothing to commit; squashed branch is empty'
814 return False
maruel@chromium.org25b9ab22015-06-18 18:49:03 +0000815 run('commit', '--no-verify', '-a', '-F', '-', indata=log_msg)
sbc@chromium.org71437c02015-04-09 19:29:40 +0000816 return True
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000817
818
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000819def tags(*args):
820 return run('tag', *args).splitlines()
821
822
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000823def thaw():
824 took_action = False
825 for sha in (s.strip() for s in run_stream('rev-list', 'HEAD').xreadlines()):
826 msg = run('show', '--format=%f%b', '-s', 'HEAD')
827 match = FREEZE_MATCHER.match(msg)
828 if not match:
829 if not took_action:
830 return 'Nothing to thaw.'
831 break
832
833 run('reset', '--' + FREEZE_SECTIONS[match.group(1)], sha)
834 took_action = True
835
836
837def topo_iter(branch_tree, top_down=True):
838 """Generates (branch, parent) in topographical order for a branch tree.
839
840 Given a tree:
841
842 A1
843 B1 B2
844 C1 C2 C3
845 D1
846
847 branch_tree would look like: {
848 'D1': 'C3',
849 'C3': 'B2',
850 'B2': 'A1',
851 'C1': 'B1',
852 'C2': 'B1',
853 'B1': 'A1',
854 }
855
856 It is OK to have multiple 'root' nodes in your graph.
857
858 if top_down is True, items are yielded from A->D. Otherwise they're yielded
859 from D->A. Within a layer the branches will be yielded in sorted order.
860 """
861 branch_tree = branch_tree.copy()
862
863 # TODO(iannucci): There is probably a more efficient way to do these.
864 if top_down:
865 while branch_tree:
866 this_pass = [(b, p) for b, p in branch_tree.iteritems()
867 if p not in branch_tree]
868 assert this_pass, "Branch tree has cycles: %r" % branch_tree
869 for branch, parent in sorted(this_pass):
870 yield branch, parent
871 del branch_tree[branch]
872 else:
873 parent_to_branches = collections.defaultdict(set)
874 for branch, parent in branch_tree.iteritems():
875 parent_to_branches[parent].add(branch)
876
877 while branch_tree:
878 this_pass = [(b, p) for b, p in branch_tree.iteritems()
879 if not parent_to_branches[b]]
880 assert this_pass, "Branch tree has cycles: %r" % branch_tree
881 for branch, parent in sorted(this_pass):
882 yield branch, parent
883 parent_to_branches[parent].discard(branch)
884 del branch_tree[branch]
885
886
iannucci@chromium.orgaa74cf62013-11-19 20:00:49 +0000887def tree(treeref, recurse=False):
888 """Returns a dict representation of a git tree object.
889
890 Args:
891 treeref (str) - a git ref which resolves to a tree (commits count as trees).
892 recurse (bool) - include all of the tree's decendants too. File names will
893 take the form of 'some/path/to/file'.
894
895 Return format:
896 { 'file_name': (mode, type, ref) }
897
898 mode is an integer where:
899 * 0040000 - Directory
900 * 0100644 - Regular non-executable file
901 * 0100664 - Regular non-executable group-writeable file
902 * 0100755 - Regular executable file
903 * 0120000 - Symbolic link
904 * 0160000 - Gitlink
905
906 type is a string where it's one of 'blob', 'commit', 'tree', 'tag'.
907
908 ref is the hex encoded hash of the entry.
909 """
910 ret = {}
911 opts = ['ls-tree', '--full-tree']
912 if recurse:
913 opts.append('-r')
914 opts.append(treeref)
915 try:
916 for line in run(*opts).splitlines():
917 mode, typ, ref, name = line.split(None, 3)
918 ret[name] = (mode, typ, ref)
919 except subprocess2.CalledProcessError:
920 return None
921 return ret
922
923
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000924def upstream(branch):
925 try:
926 return run('rev-parse', '--abbrev-ref', '--symbolic-full-name',
927 branch+'@{upstream}')
928 except subprocess2.CalledProcessError:
929 return None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000930
agable@chromium.orgd629fb42014-10-01 09:40:10 +0000931
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000932def get_git_version():
933 """Returns a tuple that contains the numeric components of the current git
934 version."""
935 version_string = run('--version')
936 version_match = re.search(r'(\d+.)+(\d+)', version_string)
937 version = version_match.group() if version_match else ''
938
939 return tuple(int(x) for x in version.split('.'))
940
941
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000942def get_branches_info(include_tracking_status):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000943 format_string = (
944 '--format=%(refname:short):%(objectname:short):%(upstream:short):')
945
946 # This is not covered by the depot_tools CQ which only has git version 1.8.
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000947 if (include_tracking_status and
948 get_git_version() >= MIN_UPSTREAM_TRACK_GIT_VERSION): # pragma: no cover
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000949 format_string += '%(upstream:track)'
950
951 info_map = {}
952 data = run('for-each-ref', format_string, 'refs/heads')
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000953 BranchesInfo = collections.namedtuple(
954 'BranchesInfo', 'hash upstream ahead behind')
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000955 for line in data.splitlines():
956 (branch, branch_hash, upstream_branch, tracking_status) = line.split(':')
957
958 ahead_match = re.search(r'ahead (\d+)', tracking_status)
959 ahead = int(ahead_match.group(1)) if ahead_match else None
960
961 behind_match = re.search(r'behind (\d+)', tracking_status)
962 behind = int(behind_match.group(1)) if behind_match else None
963
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000964 info_map[branch] = BranchesInfo(
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000965 hash=branch_hash, upstream=upstream_branch, ahead=ahead, behind=behind)
966
967 # Set None for upstreams which are not branches (e.g empty upstream, remotes
968 # and deleted upstream branches).
969 missing_upstreams = {}
970 for info in info_map.values():
971 if info.upstream not in info_map and info.upstream not in missing_upstreams:
972 missing_upstreams[info.upstream] = None
973
974 return dict(info_map.items() + missing_upstreams.items())
sammc@chromium.org900a33f2015-09-29 06:57:09 +0000975
976
977def make_workdir_common(repository, new_workdir, files_to_symlink,
scottmg@chromium.orgd4218d42015-10-07 23:49:20 +0000978 files_to_copy, symlink=None):
979 if not symlink:
980 symlink = os.symlink
sammc@chromium.org900a33f2015-09-29 06:57:09 +0000981 os.makedirs(new_workdir)
982 for entry in files_to_symlink:
scottmg@chromium.orgd4218d42015-10-07 23:49:20 +0000983 clone_file(repository, new_workdir, entry, symlink)
sammc@chromium.org900a33f2015-09-29 06:57:09 +0000984 for entry in files_to_copy:
985 clone_file(repository, new_workdir, entry, shutil.copy)
986
987
988def make_workdir(repository, new_workdir):
989 GIT_DIRECTORY_WHITELIST = [
990 'config',
991 'info',
992 'hooks',
993 'logs/refs',
994 'objects',
995 'packed-refs',
996 'refs',
997 'remotes',
998 'rr-cache',
999 'svn'
1000 ]
1001 make_workdir_common(repository, new_workdir, GIT_DIRECTORY_WHITELIST,
1002 ['HEAD'])
1003
1004
1005def clone_file(repository, new_workdir, link, operation):
1006 if not os.path.exists(os.path.join(repository, link)):
1007 return
1008 link_dir = os.path.dirname(os.path.join(new_workdir, link))
1009 if not os.path.exists(link_dir):
1010 os.makedirs(link_dir)
1011 operation(os.path.join(repository, link), os.path.join(new_workdir, link))