git_common.py 30 KB

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