git_common.py 30 KB

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