git_common.py 31 KB

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