git_common.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. # Copyright 2014 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. # Monkeypatch IMapIterator so that Ctrl-C can kill everything properly.
  5. # Derived from https://gist.github.com/aljungberg/626518
  6. import multiprocessing.pool
  7. from multiprocessing.pool import IMapIterator
  8. def wrapper(func):
  9. def wrap(self, timeout=None):
  10. return func(self, timeout=timeout or 1e100)
  11. return wrap
  12. IMapIterator.next = wrapper(IMapIterator.next)
  13. IMapIterator.__next__ = IMapIterator.next
  14. # TODO(iannucci): Monkeypatch all other 'wait' methods too.
  15. import binascii
  16. import collections
  17. import contextlib
  18. import functools
  19. import logging
  20. import os
  21. import re
  22. import setup_color
  23. import shutil
  24. import signal
  25. import sys
  26. import tempfile
  27. import textwrap
  28. import threading
  29. import subprocess2
  30. from StringIO import StringIO
  31. ROOT = os.path.abspath(os.path.dirname(__file__))
  32. IS_WIN = sys.platform == 'win32'
  33. GIT_EXE = ROOT+'\\git.bat' if IS_WIN else 'git'
  34. TEST_MODE = False
  35. FREEZE = 'FREEZE'
  36. FREEZE_SECTIONS = {
  37. 'indexed': 'soft',
  38. 'unindexed': 'mixed'
  39. }
  40. FREEZE_MATCHER = re.compile(r'%s.(%s)' % (FREEZE, '|'.join(FREEZE_SECTIONS)))
  41. # Retry a git operation if git returns a error response with any of these
  42. # messages. It's all observed 'bad' GoB responses so far.
  43. #
  44. # This list is inspired/derived from the one in ChromiumOS's Chromite:
  45. # <CHROMITE>/lib/git.py::GIT_TRANSIENT_ERRORS
  46. #
  47. # It was last imported from '7add3ac29564d98ac35ce426bc295e743e7c0c02'.
  48. GIT_TRANSIENT_ERRORS = (
  49. # crbug.com/285832
  50. r'!.*\[remote rejected\].*\(error in hook\)',
  51. # crbug.com/289932
  52. r'!.*\[remote rejected\].*\(failed to lock\)',
  53. # crbug.com/307156
  54. r'!.*\[remote rejected\].*\(error in Gerrit backend\)',
  55. # crbug.com/285832
  56. r'remote error: Internal Server Error',
  57. # crbug.com/294449
  58. r'fatal: Couldn\'t find remote ref ',
  59. # crbug.com/220543
  60. r'git fetch_pack: expected ACK/NAK, got',
  61. # crbug.com/189455
  62. r'protocol error: bad pack header',
  63. # crbug.com/202807
  64. r'The remote end hung up unexpectedly',
  65. # crbug.com/298189
  66. r'TLS packet with unexpected length was received',
  67. # crbug.com/187444
  68. r'RPC failed; result=\d+, HTTP code = \d+',
  69. # crbug.com/388876
  70. r'Connection timed out',
  71. # crbug.com/430343
  72. # TODO(dnj): Resync with Chromite.
  73. r'The requested URL returned error: 5\d+',
  74. r'Connection reset by peer',
  75. r'Unable to look up',
  76. r'Couldn\'t resolve host',
  77. )
  78. GIT_TRANSIENT_ERRORS_RE = re.compile('|'.join(GIT_TRANSIENT_ERRORS),
  79. re.IGNORECASE)
  80. # git's for-each-ref command first supported the upstream:track token in its
  81. # format string in version 1.9.0, but some usages were broken until 2.3.0.
  82. # See git commit b6160d95 for more information.
  83. MIN_UPSTREAM_TRACK_GIT_VERSION = (2, 3)
  84. class BadCommitRefException(Exception):
  85. def __init__(self, refs):
  86. msg = ('one of %s does not seem to be a valid commitref.' %
  87. str(refs))
  88. super(BadCommitRefException, self).__init__(msg)
  89. def memoize_one(**kwargs):
  90. """Memoizes a single-argument pure function.
  91. Values of None are not cached.
  92. Kwargs:
  93. threadsafe (bool) - REQUIRED. Specifies whether to use locking around
  94. cache manipulation functions. This is a kwarg so that users of memoize_one
  95. are forced to explicitly and verbosely pick True or False.
  96. Adds three methods to the decorated function:
  97. * get(key, default=None) - Gets the value for this key from the cache.
  98. * set(key, value) - Sets the value for this key from the cache.
  99. * clear() - Drops the entire contents of the cache. Useful for unittests.
  100. * update(other) - Updates the contents of the cache from another dict.
  101. """
  102. assert 'threadsafe' in kwargs, 'Must specify threadsafe={True,False}'
  103. threadsafe = kwargs['threadsafe']
  104. if threadsafe:
  105. def withlock(lock, f):
  106. def inner(*args, **kwargs):
  107. with lock:
  108. return f(*args, **kwargs)
  109. return inner
  110. else:
  111. def withlock(_lock, f):
  112. return f
  113. def decorator(f):
  114. # Instantiate the lock in decorator, in case users of memoize_one do:
  115. #
  116. # memoizer = memoize_one(threadsafe=True)
  117. #
  118. # @memoizer
  119. # def fn1(val): ...
  120. #
  121. # @memoizer
  122. # def fn2(val): ...
  123. lock = threading.Lock() if threadsafe else None
  124. cache = {}
  125. _get = withlock(lock, cache.get)
  126. _set = withlock(lock, cache.__setitem__)
  127. @functools.wraps(f)
  128. def inner(arg):
  129. ret = _get(arg)
  130. if ret is None:
  131. ret = f(arg)
  132. if ret is not None:
  133. _set(arg, ret)
  134. return ret
  135. inner.get = _get
  136. inner.set = _set
  137. inner.clear = withlock(lock, cache.clear)
  138. inner.update = withlock(lock, cache.update)
  139. return inner
  140. return decorator
  141. def _ScopedPool_initer(orig, orig_args): # pragma: no cover
  142. """Initializer method for ScopedPool's subprocesses.
  143. This helps ScopedPool handle Ctrl-C's correctly.
  144. """
  145. signal.signal(signal.SIGINT, signal.SIG_IGN)
  146. if orig:
  147. orig(*orig_args)
  148. @contextlib.contextmanager
  149. def ScopedPool(*args, **kwargs):
  150. """Context Manager which returns a multiprocessing.pool instance which
  151. correctly deals with thrown exceptions.
  152. *args - Arguments to multiprocessing.pool
  153. Kwargs:
  154. kind ('threads', 'procs') - The type of underlying coprocess to use.
  155. **etc - Arguments to multiprocessing.pool
  156. """
  157. if kwargs.pop('kind', None) == 'threads':
  158. pool = multiprocessing.pool.ThreadPool(*args, **kwargs)
  159. else:
  160. orig, orig_args = kwargs.get('initializer'), kwargs.get('initargs', ())
  161. kwargs['initializer'] = _ScopedPool_initer
  162. kwargs['initargs'] = orig, orig_args
  163. pool = multiprocessing.pool.Pool(*args, **kwargs)
  164. try:
  165. yield pool
  166. pool.close()
  167. except:
  168. pool.terminate()
  169. raise
  170. finally:
  171. pool.join()
  172. class ProgressPrinter(object):
  173. """Threaded single-stat status message printer."""
  174. def __init__(self, fmt, enabled=None, fout=sys.stderr, period=0.5):
  175. """Create a ProgressPrinter.
  176. Use it as a context manager which produces a simple 'increment' method:
  177. with ProgressPrinter('(%%(count)d/%d)' % 1000) as inc:
  178. for i in xrange(1000):
  179. # do stuff
  180. if i % 10 == 0:
  181. inc(10)
  182. Args:
  183. fmt - String format with a single '%(count)d' where the counter value
  184. should go.
  185. enabled (bool) - If this is None, will default to True if
  186. logging.getLogger() is set to INFO or more verbose.
  187. fout (file-like) - The stream to print status messages to.
  188. period (float) - The time in seconds for the printer thread to wait
  189. between printing.
  190. """
  191. self.fmt = fmt
  192. if enabled is None: # pragma: no cover
  193. self.enabled = logging.getLogger().isEnabledFor(logging.INFO)
  194. else:
  195. self.enabled = enabled
  196. self._count = 0
  197. self._dead = False
  198. self._dead_cond = threading.Condition()
  199. self._stream = fout
  200. self._thread = threading.Thread(target=self._run)
  201. self._period = period
  202. def _emit(self, s):
  203. if self.enabled:
  204. self._stream.write('\r' + s)
  205. self._stream.flush()
  206. def _run(self):
  207. with self._dead_cond:
  208. while not self._dead:
  209. self._emit(self.fmt % {'count': self._count})
  210. self._dead_cond.wait(self._period)
  211. self._emit((self.fmt + '\n') % {'count': self._count})
  212. def inc(self, amount=1):
  213. self._count += amount
  214. def __enter__(self):
  215. self._thread.start()
  216. return self.inc
  217. def __exit__(self, _exc_type, _exc_value, _traceback):
  218. self._dead = True
  219. with self._dead_cond:
  220. self._dead_cond.notifyAll()
  221. self._thread.join()
  222. del self._thread
  223. def once(function):
  224. """@Decorates |function| so that it only performs its action once, no matter
  225. how many times the decorated |function| is called."""
  226. def _inner_gen():
  227. yield function()
  228. while True:
  229. yield
  230. return _inner_gen().next
  231. ## Git functions
  232. def die(message, *args):
  233. print >> sys.stderr, textwrap.dedent(message % args)
  234. sys.exit(1)
  235. def blame(filename, revision=None, porcelain=False, abbrev=None, *_args):
  236. command = ['blame']
  237. if porcelain:
  238. command.append('-p')
  239. if revision is not None:
  240. command.append(revision)
  241. if abbrev is not None:
  242. command.append('--abbrev=%d' % abbrev)
  243. command.extend(['--', filename])
  244. return run(*command)
  245. def branch_config(branch, option, default=None):
  246. return get_config('branch.%s.%s' % (branch, option), default=default)
  247. def branch_config_map(option):
  248. """Return {branch: <|option| value>} for all branches."""
  249. try:
  250. reg = re.compile(r'^branch\.(.*)\.%s$' % option)
  251. lines = get_config_regexp(reg.pattern)
  252. return {reg.match(k).group(1): v for k, v in (l.split() for l in lines)}
  253. except subprocess2.CalledProcessError:
  254. return {}
  255. def branches(*args):
  256. NO_BRANCH = ('* (no branch', '* (detached', '* (HEAD detached')
  257. key = 'depot-tools.branch-limit'
  258. limit = get_config_int(key, 20)
  259. raw_branches = run('branch', *args).splitlines()
  260. num = len(raw_branches)
  261. if num > limit:
  262. die("""\
  263. Your git repo has too many branches (%d/%d) for this tool to work well.
  264. You may adjust this limit by running:
  265. git config %s <new_limit>
  266. You may also try cleaning up your old branches by running:
  267. git cl archive
  268. """, num, limit, key)
  269. for line in raw_branches:
  270. if line.startswith(NO_BRANCH):
  271. continue
  272. yield line.split()[-1]
  273. def get_config(option, default=None):
  274. try:
  275. return run('config', '--get', option) or default
  276. except subprocess2.CalledProcessError:
  277. return default
  278. def get_config_int(option, default=0):
  279. assert isinstance(default, int)
  280. try:
  281. return int(get_config(option, default))
  282. except ValueError:
  283. return default
  284. def get_config_list(option):
  285. try:
  286. return run('config', '--get-all', option).split()
  287. except subprocess2.CalledProcessError:
  288. return []
  289. def get_config_regexp(pattern):
  290. if IS_WIN: # pragma: no cover
  291. # this madness is because we call git.bat which calls git.exe which calls
  292. # bash.exe (or something to that effect). Each layer divides the number of
  293. # ^'s by 2.
  294. pattern = pattern.replace('^', '^' * 8)
  295. return run('config', '--get-regexp', pattern).splitlines()
  296. def current_branch():
  297. try:
  298. return run('rev-parse', '--abbrev-ref', 'HEAD')
  299. except subprocess2.CalledProcessError:
  300. return None
  301. def del_branch_config(branch, option, scope='local'):
  302. del_config('branch.%s.%s' % (branch, option), scope=scope)
  303. def del_config(option, scope='local'):
  304. try:
  305. run('config', '--' + scope, '--unset', option)
  306. except subprocess2.CalledProcessError:
  307. pass
  308. def diff(oldrev, newrev, *args):
  309. return run('diff', oldrev, newrev, *args)
  310. def freeze():
  311. took_action = False
  312. key = 'depot-tools.freeze-size-limit'
  313. MB = 2**20
  314. limit_mb = get_config_int(key, 100)
  315. untracked_bytes = 0
  316. root_path = repo_root()
  317. for f, s in status():
  318. if is_unmerged(s):
  319. die("Cannot freeze unmerged changes!")
  320. if limit_mb > 0:
  321. if s.lstat == '?':
  322. untracked_bytes += os.stat(os.path.join(root_path, f)).st_size
  323. if untracked_bytes > limit_mb * MB:
  324. die("""\
  325. You appear to have too much untracked+unignored data in your git
  326. checkout: %.1f / %d MB.
  327. Run `git status` to see what it is.
  328. In addition to making many git commands slower, this will prevent
  329. depot_tools from freezing your in-progress changes.
  330. You should add untracked data that you want to ignore to your repo's
  331. .git/info/exclude
  332. file. See `git help ignore` for the format of this file.
  333. If this data is indended as part of your commit, you may adjust the
  334. freeze limit by running:
  335. git config %s <new_limit>
  336. Where <new_limit> is an integer threshold in megabytes.""",
  337. untracked_bytes / (MB * 1.0), limit_mb, key)
  338. try:
  339. run('commit', '--no-verify', '-m', FREEZE + '.indexed')
  340. took_action = True
  341. except subprocess2.CalledProcessError:
  342. pass
  343. add_errors = False
  344. try:
  345. run('add', '-A', '--ignore-errors')
  346. except subprocess2.CalledProcessError:
  347. add_errors = True
  348. try:
  349. run('commit', '--no-verify', '-m', FREEZE + '.unindexed')
  350. took_action = True
  351. except subprocess2.CalledProcessError:
  352. pass
  353. ret = []
  354. if add_errors:
  355. ret.append('Failed to index some unindexed files.')
  356. if not took_action:
  357. ret.append('Nothing to freeze.')
  358. return ' '.join(ret) or None
  359. def get_branch_tree():
  360. """Get the dictionary of {branch: parent}, compatible with topo_iter.
  361. Returns a tuple of (skipped, <branch_tree dict>) where skipped is a set of
  362. branches without upstream branches defined.
  363. """
  364. skipped = set()
  365. branch_tree = {}
  366. for branch in branches():
  367. parent = upstream(branch)
  368. if not parent:
  369. skipped.add(branch)
  370. continue
  371. branch_tree[branch] = parent
  372. return skipped, branch_tree
  373. def get_or_create_merge_base(branch, parent=None):
  374. """Finds the configured merge base for branch.
  375. If parent is supplied, it's used instead of calling upstream(branch).
  376. """
  377. base = branch_config(branch, 'base')
  378. base_upstream = branch_config(branch, 'base-upstream')
  379. parent = parent or upstream(branch)
  380. if parent is None or branch is None:
  381. return None
  382. actual_merge_base = run('merge-base', parent, branch)
  383. if base_upstream != parent:
  384. base = None
  385. base_upstream = None
  386. def is_ancestor(a, b):
  387. return run_with_retcode('merge-base', '--is-ancestor', a, b) == 0
  388. if base and base != actual_merge_base:
  389. if not is_ancestor(base, branch):
  390. logging.debug('Found WRONG pre-set merge-base for %s: %s', branch, base)
  391. base = None
  392. elif is_ancestor(base, actual_merge_base):
  393. logging.debug('Found OLD pre-set merge-base for %s: %s', branch, base)
  394. base = None
  395. else:
  396. logging.debug('Found pre-set merge-base for %s: %s', branch, base)
  397. if not base:
  398. base = actual_merge_base
  399. manual_merge_base(branch, base, parent)
  400. return base
  401. def hash_multi(*reflike):
  402. return run('rev-parse', *reflike).splitlines()
  403. def hash_one(reflike, short=False):
  404. args = ['rev-parse', reflike]
  405. if short:
  406. args.insert(1, '--short')
  407. return run(*args)
  408. def in_rebase():
  409. git_dir = run('rev-parse', '--git-dir')
  410. return (
  411. os.path.exists(os.path.join(git_dir, 'rebase-merge')) or
  412. os.path.exists(os.path.join(git_dir, 'rebase-apply')))
  413. def intern_f(f, kind='blob'):
  414. """Interns a file object into the git object store.
  415. Args:
  416. f (file-like object) - The file-like object to intern
  417. kind (git object type) - One of 'blob', 'commit', 'tree', 'tag'.
  418. Returns the git hash of the interned object (hex encoded).
  419. """
  420. ret = run('hash-object', '-t', kind, '-w', '--stdin', stdin=f)
  421. f.close()
  422. return ret
  423. def is_dormant(branch):
  424. # TODO(iannucci): Do an oldness check?
  425. return branch_config(branch, 'dormant', 'false') != 'false'
  426. def is_unmerged(stat_value):
  427. return (
  428. 'U' in (stat_value.lstat, stat_value.rstat) or
  429. ((stat_value.lstat == stat_value.rstat) and stat_value.lstat in 'AD')
  430. )
  431. def manual_merge_base(branch, base, parent):
  432. set_branch_config(branch, 'base', base)
  433. set_branch_config(branch, 'base-upstream', parent)
  434. def mktree(treedict):
  435. """Makes a git tree object and returns its hash.
  436. See |tree()| for the values of mode, type, and ref.
  437. Args:
  438. treedict - { name: (mode, type, ref) }
  439. """
  440. with tempfile.TemporaryFile() as f:
  441. for name, (mode, typ, ref) in treedict.iteritems():
  442. f.write('%s %s %s\t%s\0' % (mode, typ, ref, name))
  443. f.seek(0)
  444. return run('mktree', '-z', stdin=f)
  445. def parse_commitrefs(*commitrefs):
  446. """Returns binary encoded commit hashes for one or more commitrefs.
  447. A commitref is anything which can resolve to a commit. Popular examples:
  448. * 'HEAD'
  449. * 'origin/master'
  450. * 'cool_branch~2'
  451. """
  452. try:
  453. return map(binascii.unhexlify, hash_multi(*commitrefs))
  454. except subprocess2.CalledProcessError:
  455. raise BadCommitRefException(commitrefs)
  456. RebaseRet = collections.namedtuple('RebaseRet', 'success stdout stderr')
  457. def rebase(parent, start, branch, abort=False):
  458. """Rebases |start|..|branch| onto the branch |parent|.
  459. Args:
  460. parent - The new parent ref for the rebased commits.
  461. start - The commit to start from
  462. branch - The branch to rebase
  463. abort - If True, will call git-rebase --abort in the event that the rebase
  464. doesn't complete successfully.
  465. Returns a namedtuple with fields:
  466. success - a boolean indicating that the rebase command completed
  467. successfully.
  468. message - if the rebase failed, this contains the stdout of the failed
  469. rebase.
  470. """
  471. try:
  472. args = ['--onto', parent, start, branch]
  473. if TEST_MODE:
  474. args.insert(0, '--committer-date-is-author-date')
  475. run('rebase', *args)
  476. return RebaseRet(True, '', '')
  477. except subprocess2.CalledProcessError as cpe:
  478. if abort:
  479. run_with_retcode('rebase', '--abort') # ignore failure
  480. return RebaseRet(False, cpe.stdout, cpe.stderr)
  481. def remove_merge_base(branch):
  482. del_branch_config(branch, 'base')
  483. del_branch_config(branch, 'base-upstream')
  484. def repo_root():
  485. """Returns the absolute path to the repository root."""
  486. return run('rev-parse', '--show-toplevel')
  487. def root():
  488. return get_config('depot-tools.upstream', 'origin/master')
  489. @contextlib.contextmanager
  490. def less(): # pragma: no cover
  491. """Runs 'less' as context manager yielding its stdin as a PIPE.
  492. Automatically checks if sys.stdout is a non-TTY stream. If so, it avoids
  493. running less and just yields sys.stdout.
  494. """
  495. if not setup_color.IS_TTY:
  496. yield sys.stdout
  497. return
  498. # Run with the same options that git uses (see setup_pager in git repo).
  499. # -F: Automatically quit if the output is less than one screen.
  500. # -R: Don't escape ANSI color codes.
  501. # -X: Don't clear the screen before starting.
  502. cmd = ('less', '-FRX')
  503. try:
  504. proc = subprocess2.Popen(cmd, stdin=subprocess2.PIPE)
  505. yield proc.stdin
  506. finally:
  507. proc.stdin.close()
  508. proc.wait()
  509. def run(*cmd, **kwargs):
  510. """The same as run_with_stderr, except it only returns stdout."""
  511. return run_with_stderr(*cmd, **kwargs)[0]
  512. def run_with_retcode(*cmd, **kwargs):
  513. """Run a command but only return the status code."""
  514. try:
  515. run(*cmd, **kwargs)
  516. return 0
  517. except subprocess2.CalledProcessError as cpe:
  518. return cpe.returncode
  519. def run_stream(*cmd, **kwargs):
  520. """Runs a git command. Returns stdout as a PIPE (file-like object).
  521. stderr is dropped to avoid races if the process outputs to both stdout and
  522. stderr.
  523. """
  524. kwargs.setdefault('stderr', subprocess2.VOID)
  525. kwargs.setdefault('stdout', subprocess2.PIPE)
  526. kwargs.setdefault('shell', False)
  527. cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
  528. proc = subprocess2.Popen(cmd, **kwargs)
  529. return proc.stdout
  530. @contextlib.contextmanager
  531. def run_stream_with_retcode(*cmd, **kwargs):
  532. """Runs a git command as context manager yielding stdout as a PIPE.
  533. stderr is dropped to avoid races if the process outputs to both stdout and
  534. stderr.
  535. Raises subprocess2.CalledProcessError on nonzero return code.
  536. """
  537. kwargs.setdefault('stderr', subprocess2.VOID)
  538. kwargs.setdefault('stdout', subprocess2.PIPE)
  539. kwargs.setdefault('shell', False)
  540. cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
  541. try:
  542. proc = subprocess2.Popen(cmd, **kwargs)
  543. yield proc.stdout
  544. finally:
  545. retcode = proc.wait()
  546. if retcode != 0:
  547. raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(),
  548. None, None)
  549. def run_with_stderr(*cmd, **kwargs):
  550. """Runs a git command.
  551. Returns (stdout, stderr) as a pair of strings.
  552. kwargs
  553. autostrip (bool) - Strip the output. Defaults to True.
  554. indata (str) - Specifies stdin data for the process.
  555. """
  556. kwargs.setdefault('stdin', subprocess2.PIPE)
  557. kwargs.setdefault('stdout', subprocess2.PIPE)
  558. kwargs.setdefault('stderr', subprocess2.PIPE)
  559. kwargs.setdefault('shell', False)
  560. autostrip = kwargs.pop('autostrip', True)
  561. indata = kwargs.pop('indata', None)
  562. cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
  563. proc = subprocess2.Popen(cmd, **kwargs)
  564. ret, err = proc.communicate(indata)
  565. retcode = proc.wait()
  566. if retcode != 0:
  567. raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(), ret, err)
  568. if autostrip:
  569. ret = (ret or '').strip()
  570. err = (err or '').strip()
  571. return ret, err
  572. def set_branch_config(branch, option, value, scope='local'):
  573. set_config('branch.%s.%s' % (branch, option), value, scope=scope)
  574. def set_config(option, value, scope='local'):
  575. run('config', '--' + scope, option, value)
  576. def get_dirty_files():
  577. # Make sure index is up-to-date before running diff-index.
  578. run_with_retcode('update-index', '--refresh', '-q')
  579. return run('diff-index', '--name-status', 'HEAD')
  580. def is_dirty_git_tree(cmd):
  581. w = lambda s: sys.stderr.write(s+"\n")
  582. dirty = get_dirty_files()
  583. if dirty:
  584. w('Cannot %s with a dirty tree. Commit, freeze or stash your changes first.'
  585. % cmd)
  586. w('Uncommitted files: (git diff-index --name-status HEAD)')
  587. w(dirty[:4096])
  588. if len(dirty) > 4096: # pragma: no cover
  589. w('... (run "git diff-index --name-status HEAD" to see full output).')
  590. return True
  591. return False
  592. def status():
  593. """Returns a parsed version of git-status.
  594. Returns a generator of (current_name, (lstat, rstat, src)) pairs where:
  595. * current_name is the name of the file
  596. * lstat is the left status code letter from git-status
  597. * rstat is the left status code letter from git-status
  598. * src is the current name of the file, or the original name of the file
  599. if lstat == 'R'
  600. """
  601. stat_entry = collections.namedtuple('stat_entry', 'lstat rstat src')
  602. def tokenizer(stream):
  603. acc = StringIO()
  604. c = None
  605. while c != '':
  606. c = stream.read(1)
  607. if c in (None, '', '\0'):
  608. if acc.len:
  609. yield acc.getvalue()
  610. acc = StringIO()
  611. else:
  612. acc.write(c)
  613. def parser(tokens):
  614. while True:
  615. # Raises StopIteration if it runs out of tokens.
  616. status_dest = next(tokens)
  617. stat, dest = status_dest[:2], status_dest[3:]
  618. lstat, rstat = stat
  619. if lstat == 'R':
  620. src = next(tokens)
  621. else:
  622. src = dest
  623. yield (dest, stat_entry(lstat, rstat, src))
  624. return parser(tokenizer(run_stream('status', '-z', bufsize=-1)))
  625. def squash_current_branch(header=None, merge_base=None):
  626. header = header or 'git squash commit for %s.' % current_branch()
  627. merge_base = merge_base or get_or_create_merge_base(current_branch())
  628. log_msg = header + '\n'
  629. if log_msg:
  630. log_msg += '\n'
  631. log_msg += run('log', '--reverse', '--format=%H%n%B', '%s..HEAD' % merge_base)
  632. run('reset', '--soft', merge_base)
  633. if not get_dirty_files():
  634. # Sometimes the squash can result in the same tree, meaning that there is
  635. # nothing to commit at this point.
  636. print 'Nothing to commit; squashed branch is empty'
  637. return False
  638. run('commit', '--no-verify', '-a', '-F', '-', indata=log_msg)
  639. return True
  640. def tags(*args):
  641. return run('tag', *args).splitlines()
  642. def thaw():
  643. took_action = False
  644. for sha in (s.strip() for s in run_stream('rev-list', 'HEAD').xreadlines()):
  645. msg = run('show', '--format=%f%b', '-s', 'HEAD')
  646. match = FREEZE_MATCHER.match(msg)
  647. if not match:
  648. if not took_action:
  649. return 'Nothing to thaw.'
  650. break
  651. run('reset', '--' + FREEZE_SECTIONS[match.group(1)], sha)
  652. took_action = True
  653. def topo_iter(branch_tree, top_down=True):
  654. """Generates (branch, parent) in topographical order for a branch tree.
  655. Given a tree:
  656. A1
  657. B1 B2
  658. C1 C2 C3
  659. D1
  660. branch_tree would look like: {
  661. 'D1': 'C3',
  662. 'C3': 'B2',
  663. 'B2': 'A1',
  664. 'C1': 'B1',
  665. 'C2': 'B1',
  666. 'B1': 'A1',
  667. }
  668. It is OK to have multiple 'root' nodes in your graph.
  669. if top_down is True, items are yielded from A->D. Otherwise they're yielded
  670. from D->A. Within a layer the branches will be yielded in sorted order.
  671. """
  672. branch_tree = branch_tree.copy()
  673. # TODO(iannucci): There is probably a more efficient way to do these.
  674. if top_down:
  675. while branch_tree:
  676. this_pass = [(b, p) for b, p in branch_tree.iteritems()
  677. if p not in branch_tree]
  678. assert this_pass, "Branch tree has cycles: %r" % branch_tree
  679. for branch, parent in sorted(this_pass):
  680. yield branch, parent
  681. del branch_tree[branch]
  682. else:
  683. parent_to_branches = collections.defaultdict(set)
  684. for branch, parent in branch_tree.iteritems():
  685. parent_to_branches[parent].add(branch)
  686. while branch_tree:
  687. this_pass = [(b, p) for b, p in branch_tree.iteritems()
  688. if not parent_to_branches[b]]
  689. assert this_pass, "Branch tree has cycles: %r" % branch_tree
  690. for branch, parent in sorted(this_pass):
  691. yield branch, parent
  692. parent_to_branches[parent].discard(branch)
  693. del branch_tree[branch]
  694. def tree(treeref, recurse=False):
  695. """Returns a dict representation of a git tree object.
  696. Args:
  697. treeref (str) - a git ref which resolves to a tree (commits count as trees).
  698. recurse (bool) - include all of the tree's descendants too. File names will
  699. take the form of 'some/path/to/file'.
  700. Return format:
  701. { 'file_name': (mode, type, ref) }
  702. mode is an integer where:
  703. * 0040000 - Directory
  704. * 0100644 - Regular non-executable file
  705. * 0100664 - Regular non-executable group-writeable file
  706. * 0100755 - Regular executable file
  707. * 0120000 - Symbolic link
  708. * 0160000 - Gitlink
  709. type is a string where it's one of 'blob', 'commit', 'tree', 'tag'.
  710. ref is the hex encoded hash of the entry.
  711. """
  712. ret = {}
  713. opts = ['ls-tree', '--full-tree']
  714. if recurse:
  715. opts.append('-r')
  716. opts.append(treeref)
  717. try:
  718. for line in run(*opts).splitlines():
  719. mode, typ, ref, name = line.split(None, 3)
  720. ret[name] = (mode, typ, ref)
  721. except subprocess2.CalledProcessError:
  722. return None
  723. return ret
  724. def upstream(branch):
  725. try:
  726. return run('rev-parse', '--abbrev-ref', '--symbolic-full-name',
  727. branch+'@{upstream}')
  728. except subprocess2.CalledProcessError:
  729. return None
  730. def get_git_version():
  731. """Returns a tuple that contains the numeric components of the current git
  732. version."""
  733. version_string = run('--version')
  734. version_match = re.search(r'(\d+.)+(\d+)', version_string)
  735. version = version_match.group() if version_match else ''
  736. return tuple(int(x) for x in version.split('.'))
  737. def get_branches_info(include_tracking_status):
  738. format_string = (
  739. '--format=%(refname:short):%(objectname:short):%(upstream:short):')
  740. # This is not covered by the depot_tools CQ which only has git version 1.8.
  741. if (include_tracking_status and
  742. get_git_version() >= MIN_UPSTREAM_TRACK_GIT_VERSION): # pragma: no cover
  743. format_string += '%(upstream:track)'
  744. info_map = {}
  745. data = run('for-each-ref', format_string, 'refs/heads')
  746. BranchesInfo = collections.namedtuple(
  747. 'BranchesInfo', 'hash upstream ahead behind')
  748. for line in data.splitlines():
  749. (branch, branch_hash, upstream_branch, tracking_status) = line.split(':')
  750. ahead_match = re.search(r'ahead (\d+)', tracking_status)
  751. ahead = int(ahead_match.group(1)) if ahead_match else None
  752. behind_match = re.search(r'behind (\d+)', tracking_status)
  753. behind = int(behind_match.group(1)) if behind_match else None
  754. info_map[branch] = BranchesInfo(
  755. hash=branch_hash, upstream=upstream_branch, ahead=ahead, behind=behind)
  756. # Set None for upstreams which are not branches (e.g empty upstream, remotes
  757. # and deleted upstream branches).
  758. missing_upstreams = {}
  759. for info in info_map.values():
  760. if info.upstream not in info_map and info.upstream not in missing_upstreams:
  761. missing_upstreams[info.upstream] = None
  762. return dict(info_map.items() + missing_upstreams.items())
  763. def make_workdir_common(repository, new_workdir, files_to_symlink,
  764. files_to_copy, symlink=None):
  765. if not symlink:
  766. symlink = os.symlink
  767. os.makedirs(new_workdir)
  768. for entry in files_to_symlink:
  769. clone_file(repository, new_workdir, entry, symlink)
  770. for entry in files_to_copy:
  771. clone_file(repository, new_workdir, entry, shutil.copy)
  772. def make_workdir(repository, new_workdir):
  773. GIT_DIRECTORY_WHITELIST = [
  774. 'config',
  775. 'info',
  776. 'hooks',
  777. 'logs/refs',
  778. 'objects',
  779. 'packed-refs',
  780. 'refs',
  781. 'remotes',
  782. 'rr-cache',
  783. ]
  784. make_workdir_common(repository, new_workdir, GIT_DIRECTORY_WHITELIST,
  785. ['HEAD'])
  786. def clone_file(repository, new_workdir, link, operation):
  787. if not os.path.exists(os.path.join(repository, link)):
  788. return
  789. link_dir = os.path.dirname(os.path.join(new_workdir, link))
  790. if not os.path.exists(link_dir):
  791. os.makedirs(link_dir)
  792. operation(os.path.join(repository, link), os.path.join(new_workdir, link))