git_common.py 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  1. # Copyright 2014 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. # Monkeypatch IMapIterator so that Ctrl-C can kill everything properly.
  5. # Derived from https://gist.github.com/aljungberg/626518
  6. import multiprocessing.pool
  7. import sys
  8. import threading
  9. from multiprocessing.pool import IMapIterator
  10. def wrapper(func):
  11. def wrap(self, timeout=None):
  12. default_timeout = (1 << 31 if sys.version_info.major == 2 else
  13. threading.TIMEOUT_MAX)
  14. return func(self, timeout=timeout or default_timeout)
  15. return wrap
  16. IMapIterator.next = wrapper(IMapIterator.next)
  17. IMapIterator.__next__ = IMapIterator.next
  18. # TODO(iannucci): Monkeypatch all other 'wait' methods too.
  19. import binascii
  20. import collections
  21. import contextlib
  22. import functools
  23. import logging
  24. import os
  25. import re
  26. import setup_color
  27. import shutil
  28. import signal
  29. import tempfile
  30. import textwrap
  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/+/HEAD/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. # unindexed tracks all the files which are unindexed but we want to add to
  339. # the `FREEZE.unindexed` commit.
  340. unindexed = []
  341. # will be set to true if there are any indexed files to commit.
  342. have_indexed_files = False
  343. for f, s in status():
  344. if is_unmerged(s):
  345. die("Cannot freeze unmerged changes!")
  346. if s.lstat not in ' ?':
  347. # This covers all changes to indexed files.
  348. # lstat = ' ' means that the file is tracked and modified, but wasn't
  349. # added yet.
  350. # lstat = '?' means that the file is untracked.
  351. have_indexed_files = True
  352. else:
  353. unindexed.append(f.encode('utf-8'))
  354. if s.lstat == '?' and limit_mb > 0:
  355. untracked_bytes += os.lstat(os.path.join(root_path, f)).st_size
  356. if limit_mb > 0 and untracked_bytes > limit_mb * MB:
  357. die("""\
  358. You appear to have too much untracked+unignored data in your git
  359. checkout: %.1f / %d MB.
  360. Run `git status` to see what it is.
  361. In addition to making many git commands slower, this will prevent
  362. depot_tools from freezing your in-progress changes.
  363. You should add untracked data that you want to ignore to your repo's
  364. .git/info/exclude
  365. file. See `git help ignore` for the format of this file.
  366. If this data is intended as part of your commit, you may adjust the
  367. freeze limit by running:
  368. git config %s <new_limit>
  369. Where <new_limit> is an integer threshold in megabytes.""",
  370. untracked_bytes / (MB * 1.0), limit_mb, key)
  371. if have_indexed_files:
  372. try:
  373. run('commit', '--no-verify', '-m', f'{FREEZE}.indexed')
  374. took_action = True
  375. except subprocess2.CalledProcessError:
  376. pass
  377. add_errors = False
  378. if unindexed:
  379. try:
  380. run('add',
  381. '--pathspec-from-file',
  382. '-',
  383. '--ignore-errors',
  384. indata=b'\n'.join(unindexed),
  385. cwd=root_path)
  386. except subprocess2.CalledProcessError:
  387. add_errors = True
  388. try:
  389. run('commit', '--no-verify', '-m', f'{FREEZE}.unindexed')
  390. took_action = True
  391. except subprocess2.CalledProcessError:
  392. pass
  393. ret = []
  394. if add_errors:
  395. ret.append('Failed to index some unindexed files.')
  396. if not took_action:
  397. ret.append('Nothing to freeze.')
  398. return ' '.join(ret) or None
  399. def get_branch_tree(use_limit=False):
  400. """Get the dictionary of {branch: parent}, compatible with topo_iter.
  401. Returns a tuple of (skipped, <branch_tree dict>) where skipped is a set of
  402. branches without upstream branches defined.
  403. """
  404. skipped = set()
  405. branch_tree = {}
  406. for branch in branches(use_limit=use_limit):
  407. parent = upstream(branch)
  408. if not parent:
  409. skipped.add(branch)
  410. continue
  411. branch_tree[branch] = parent
  412. return skipped, branch_tree
  413. def get_or_create_merge_base(branch, parent=None):
  414. """Finds the configured merge base for branch.
  415. If parent is supplied, it's used instead of calling upstream(branch).
  416. """
  417. base = branch_config(branch, 'base')
  418. base_upstream = branch_config(branch, 'base-upstream')
  419. parent = parent or upstream(branch)
  420. if parent is None or branch is None:
  421. return None
  422. actual_merge_base = run('merge-base', parent, branch)
  423. if base_upstream != parent:
  424. base = None
  425. base_upstream = None
  426. def is_ancestor(a, b):
  427. return run_with_retcode('merge-base', '--is-ancestor', a, b) == 0
  428. if base and base != actual_merge_base:
  429. if not is_ancestor(base, branch):
  430. logging.debug('Found WRONG pre-set merge-base for %s: %s', branch, base)
  431. base = None
  432. elif is_ancestor(base, actual_merge_base):
  433. logging.debug('Found OLD pre-set merge-base for %s: %s', branch, base)
  434. base = None
  435. else:
  436. logging.debug('Found pre-set merge-base for %s: %s', branch, base)
  437. if not base:
  438. base = actual_merge_base
  439. manual_merge_base(branch, base, parent)
  440. return base
  441. def hash_multi(*reflike):
  442. return run('rev-parse', *reflike).splitlines()
  443. def hash_one(reflike, short=False):
  444. args = ['rev-parse', reflike]
  445. if short:
  446. args.insert(1, '--short')
  447. return run(*args)
  448. def in_rebase():
  449. git_dir = run('rev-parse', '--git-dir')
  450. return (
  451. os.path.exists(os.path.join(git_dir, 'rebase-merge')) or
  452. os.path.exists(os.path.join(git_dir, 'rebase-apply')))
  453. def intern_f(f, kind='blob'):
  454. """Interns a file object into the git object store.
  455. Args:
  456. f (file-like object) - The file-like object to intern
  457. kind (git object type) - One of 'blob', 'commit', 'tree', 'tag'.
  458. Returns the git hash of the interned object (hex encoded).
  459. """
  460. ret = run('hash-object', '-t', kind, '-w', '--stdin', stdin=f)
  461. f.close()
  462. return ret
  463. def is_dormant(branch):
  464. # TODO(iannucci): Do an oldness check?
  465. return branch_config(branch, 'dormant', 'false') != 'false'
  466. def is_unmerged(stat_value):
  467. return (
  468. 'U' in (stat_value.lstat, stat_value.rstat) or
  469. ((stat_value.lstat == stat_value.rstat) and stat_value.lstat in 'AD')
  470. )
  471. def manual_merge_base(branch, base, parent):
  472. set_branch_config(branch, 'base', base)
  473. set_branch_config(branch, 'base-upstream', parent)
  474. def mktree(treedict):
  475. """Makes a git tree object and returns its hash.
  476. See |tree()| for the values of mode, type, and ref.
  477. Args:
  478. treedict - { name: (mode, type, ref) }
  479. """
  480. with tempfile.TemporaryFile() as f:
  481. for name, (mode, typ, ref) in treedict.items():
  482. f.write(('%s %s %s\t%s\0' % (mode, typ, ref, name)).encode('utf-8'))
  483. f.seek(0)
  484. return run('mktree', '-z', stdin=f)
  485. def parse_commitrefs(*commitrefs):
  486. """Returns binary encoded commit hashes for one or more commitrefs.
  487. A commitref is anything which can resolve to a commit. Popular examples:
  488. * 'HEAD'
  489. * 'origin/main'
  490. * 'cool_branch~2'
  491. """
  492. try:
  493. return [binascii.unhexlify(h) for h in hash_multi(*commitrefs)]
  494. except subprocess2.CalledProcessError:
  495. raise BadCommitRefException(commitrefs)
  496. RebaseRet = collections.namedtuple('RebaseRet', 'success stdout stderr')
  497. def rebase(parent, start, branch, abort=False, allow_gc=False):
  498. """Rebases |start|..|branch| onto the branch |parent|.
  499. Sets 'gc.auto=0' for the duration of this call to prevent the rebase from
  500. running a potentially slow garbage collection cycle.
  501. Args:
  502. parent - The new parent ref for the rebased commits.
  503. start - The commit to start from
  504. branch - The branch to rebase
  505. abort - If True, will call git-rebase --abort in the event that the rebase
  506. doesn't complete successfully.
  507. allow_gc - If True, sets "-c gc.auto=1" on the rebase call, rather than
  508. "-c gc.auto=0". Usually if you're doing a series of rebases,
  509. you'll only want to run a single gc pass at the end of all the
  510. rebase activity.
  511. Returns a namedtuple with fields:
  512. success - a boolean indicating that the rebase command completed
  513. successfully.
  514. message - if the rebase failed, this contains the stdout of the failed
  515. rebase.
  516. """
  517. try:
  518. args = [
  519. '-c', 'gc.auto={}'.format('1' if allow_gc else '0'),
  520. 'rebase',
  521. ]
  522. if TEST_MODE:
  523. args.append('--committer-date-is-author-date')
  524. args += [
  525. '--onto', parent, start, branch,
  526. ]
  527. run(*args)
  528. return RebaseRet(True, '', '')
  529. except subprocess2.CalledProcessError as cpe:
  530. if abort:
  531. run_with_retcode('rebase', '--abort') # ignore failure
  532. return RebaseRet(False, cpe.stdout.decode('utf-8', 'replace'),
  533. cpe.stderr.decode('utf-8', 'replace'))
  534. def remove_merge_base(branch):
  535. del_branch_config(branch, 'base')
  536. del_branch_config(branch, 'base-upstream')
  537. def repo_root():
  538. """Returns the absolute path to the repository root."""
  539. return run('rev-parse', '--show-toplevel')
  540. def upstream_default():
  541. """Returns the default branch name of the origin repository."""
  542. try:
  543. ret = run('rev-parse', '--abbrev-ref', 'origin/HEAD')
  544. # Detect if the repository migrated to main branch
  545. if ret == 'origin/master':
  546. try:
  547. ret = run('rev-parse', '--abbrev-ref', 'origin/main')
  548. run('remote', 'set-head', '-a', 'origin')
  549. ret = run('rev-parse', '--abbrev-ref', 'origin/HEAD')
  550. except subprocess2.CalledProcessError:
  551. pass
  552. return ret
  553. except subprocess2.CalledProcessError:
  554. return 'origin/main'
  555. def root():
  556. return get_config('depot-tools.upstream', upstream_default())
  557. @contextlib.contextmanager
  558. def less(): # pragma: no cover
  559. """Runs 'less' as context manager yielding its stdin as a PIPE.
  560. Automatically checks if sys.stdout is a non-TTY stream. If so, it avoids
  561. running less and just yields sys.stdout.
  562. The returned PIPE is opened on binary mode.
  563. """
  564. if not setup_color.IS_TTY:
  565. # On Python 3, sys.stdout doesn't accept bytes, and sys.stdout.buffer must
  566. # be used.
  567. yield getattr(sys.stdout, 'buffer', sys.stdout)
  568. return
  569. # Run with the same options that git uses (see setup_pager in git repo).
  570. # -F: Automatically quit if the output is less than one screen.
  571. # -R: Don't escape ANSI color codes.
  572. # -X: Don't clear the screen before starting.
  573. cmd = ('less', '-FRX')
  574. try:
  575. proc = subprocess2.Popen(cmd, stdin=subprocess2.PIPE)
  576. yield proc.stdin
  577. finally:
  578. try:
  579. proc.stdin.close()
  580. except BrokenPipeError:
  581. # BrokenPipeError is raised if proc has already completed,
  582. pass
  583. proc.wait()
  584. def run(*cmd, **kwargs):
  585. """The same as run_with_stderr, except it only returns stdout."""
  586. return run_with_stderr(*cmd, **kwargs)[0]
  587. def run_with_retcode(*cmd, **kwargs):
  588. """Run a command but only return the status code."""
  589. try:
  590. run(*cmd, **kwargs)
  591. return 0
  592. except subprocess2.CalledProcessError as cpe:
  593. return cpe.returncode
  594. def run_stream(*cmd, **kwargs):
  595. """Runs a git command. Returns stdout as a PIPE (file-like object).
  596. stderr is dropped to avoid races if the process outputs to both stdout and
  597. stderr.
  598. """
  599. kwargs.setdefault('stderr', subprocess2.DEVNULL)
  600. kwargs.setdefault('stdout', subprocess2.PIPE)
  601. kwargs.setdefault('shell', False)
  602. cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
  603. proc = subprocess2.Popen(cmd, **kwargs)
  604. return proc.stdout
  605. @contextlib.contextmanager
  606. def run_stream_with_retcode(*cmd, **kwargs):
  607. """Runs a git command as context manager yielding stdout as a PIPE.
  608. stderr is dropped to avoid races if the process outputs to both stdout and
  609. stderr.
  610. Raises subprocess2.CalledProcessError on nonzero return code.
  611. """
  612. kwargs.setdefault('stderr', subprocess2.DEVNULL)
  613. kwargs.setdefault('stdout', subprocess2.PIPE)
  614. kwargs.setdefault('shell', False)
  615. cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
  616. try:
  617. proc = subprocess2.Popen(cmd, **kwargs)
  618. yield proc.stdout
  619. finally:
  620. retcode = proc.wait()
  621. if retcode != 0:
  622. raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(),
  623. b'', b'')
  624. def run_with_stderr(*cmd, **kwargs):
  625. """Runs a git command.
  626. Returns (stdout, stderr) as a pair of strings.
  627. kwargs
  628. autostrip (bool) - Strip the output. Defaults to True.
  629. indata (str) - Specifies stdin data for the process.
  630. """
  631. kwargs.setdefault('stdin', subprocess2.PIPE)
  632. kwargs.setdefault('stdout', subprocess2.PIPE)
  633. kwargs.setdefault('stderr', subprocess2.PIPE)
  634. kwargs.setdefault('shell', False)
  635. autostrip = kwargs.pop('autostrip', True)
  636. indata = kwargs.pop('indata', None)
  637. decode = kwargs.pop('decode', True)
  638. accepted_retcodes = kwargs.pop('accepted_retcodes', [0])
  639. cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
  640. proc = subprocess2.Popen(cmd, **kwargs)
  641. ret, err = proc.communicate(indata)
  642. retcode = proc.wait()
  643. if retcode not in accepted_retcodes:
  644. raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(), ret, err)
  645. if autostrip:
  646. ret = (ret or b'').strip()
  647. err = (err or b'').strip()
  648. if decode:
  649. ret = ret.decode('utf-8', 'replace')
  650. err = err.decode('utf-8', 'replace')
  651. return ret, err
  652. def set_branch_config(branch, option, value, scope='local'):
  653. set_config('branch.%s.%s' % (branch, option), value, scope=scope)
  654. def set_config(option, value, scope='local'):
  655. run('config', '--' + scope, option, value)
  656. def get_dirty_files():
  657. # Make sure index is up-to-date before running diff-index.
  658. run_with_retcode('update-index', '--refresh', '-q')
  659. return run('diff-index', '--ignore-submodules', '--name-status', 'HEAD')
  660. def is_dirty_git_tree(cmd):
  661. w = lambda s: sys.stderr.write(s+"\n")
  662. dirty = get_dirty_files()
  663. if dirty:
  664. w('Cannot %s with a dirty tree. Commit%s or stash your changes first.' %
  665. (cmd, '' if cmd == 'upload' else ', freeze'))
  666. w('Uncommitted files: (git diff-index --name-status HEAD)')
  667. w(dirty[:4096])
  668. if len(dirty) > 4096: # pragma: no cover
  669. w('... (run "git diff-index --name-status HEAD" to see full output).')
  670. return True
  671. return False
  672. def status():
  673. """Returns a parsed version of git-status.
  674. Returns a generator of (current_name, (lstat, rstat, src)) pairs where:
  675. * current_name is the name of the file
  676. * lstat is the left status code letter from git-status
  677. * rstat is the left status code letter from git-status
  678. * src is the current name of the file, or the original name of the file
  679. if lstat == 'R'
  680. """
  681. stat_entry = collections.namedtuple('stat_entry', 'lstat rstat src')
  682. def tokenizer(stream):
  683. acc = BytesIO()
  684. c = None
  685. while c != b'':
  686. c = stream.read(1)
  687. if c in (None, b'', b'\0'):
  688. if len(acc.getvalue()) > 0:
  689. yield acc.getvalue()
  690. acc = BytesIO()
  691. else:
  692. acc.write(c)
  693. def parser(tokens):
  694. while True:
  695. try:
  696. status_dest = next(tokens).decode('utf-8')
  697. except StopIteration:
  698. return
  699. stat, dest = status_dest[:2], status_dest[3:]
  700. lstat, rstat = stat
  701. if lstat == 'R':
  702. src = next(tokens).decode('utf-8')
  703. else:
  704. src = dest
  705. yield (dest, stat_entry(lstat, rstat, src))
  706. return parser(tokenizer(run_stream('status', '-z', bufsize=-1)))
  707. def squash_current_branch(header=None, merge_base=None):
  708. header = header or 'git squash commit for %s.' % current_branch()
  709. merge_base = merge_base or get_or_create_merge_base(current_branch())
  710. log_msg = header + '\n'
  711. if log_msg:
  712. log_msg += '\n'
  713. log_msg += run('log', '--reverse', '--format=%H%n%B', '%s..HEAD' % merge_base)
  714. run('reset', '--soft', merge_base)
  715. if not get_dirty_files():
  716. # Sometimes the squash can result in the same tree, meaning that there is
  717. # nothing to commit at this point.
  718. print('Nothing to commit; squashed branch is empty')
  719. return False
  720. run('commit', '--no-verify', '-a', '-F', '-', indata=log_msg.encode('utf-8'))
  721. return True
  722. def tags(*args):
  723. return run('tag', *args).splitlines()
  724. def thaw():
  725. took_action = False
  726. with run_stream('rev-list', 'HEAD') as stream:
  727. for sha in stream:
  728. sha = sha.strip().decode('utf-8')
  729. msg = run('show', '--format=%f%b', '-s', 'HEAD')
  730. match = FREEZE_MATCHER.match(msg)
  731. if not match:
  732. if not took_action:
  733. return 'Nothing to thaw.'
  734. break
  735. run('reset', '--' + FREEZE_SECTIONS[match.group(1)], sha)
  736. took_action = True
  737. def topo_iter(branch_tree, top_down=True):
  738. """Generates (branch, parent) in topographical order for a branch tree.
  739. Given a tree:
  740. A1
  741. B1 B2
  742. C1 C2 C3
  743. D1
  744. branch_tree would look like: {
  745. 'D1': 'C3',
  746. 'C3': 'B2',
  747. 'B2': 'A1',
  748. 'C1': 'B1',
  749. 'C2': 'B1',
  750. 'B1': 'A1',
  751. }
  752. It is OK to have multiple 'root' nodes in your graph.
  753. if top_down is True, items are yielded from A->D. Otherwise they're yielded
  754. from D->A. Within a layer the branches will be yielded in sorted order.
  755. """
  756. branch_tree = branch_tree.copy()
  757. # TODO(iannucci): There is probably a more efficient way to do these.
  758. if top_down:
  759. while branch_tree:
  760. this_pass = [(b, p) for b, p in branch_tree.items()
  761. if p not in branch_tree]
  762. assert this_pass, "Branch tree has cycles: %r" % branch_tree
  763. for branch, parent in sorted(this_pass):
  764. yield branch, parent
  765. del branch_tree[branch]
  766. else:
  767. parent_to_branches = collections.defaultdict(set)
  768. for branch, parent in branch_tree.items():
  769. parent_to_branches[parent].add(branch)
  770. while branch_tree:
  771. this_pass = [(b, p) for b, p in branch_tree.items()
  772. if not parent_to_branches[b]]
  773. assert this_pass, "Branch tree has cycles: %r" % branch_tree
  774. for branch, parent in sorted(this_pass):
  775. yield branch, parent
  776. parent_to_branches[parent].discard(branch)
  777. del branch_tree[branch]
  778. def tree(treeref, recurse=False):
  779. """Returns a dict representation of a git tree object.
  780. Args:
  781. treeref (str) - a git ref which resolves to a tree (commits count as trees).
  782. recurse (bool) - include all of the tree's descendants too. File names will
  783. take the form of 'some/path/to/file'.
  784. Return format:
  785. { 'file_name': (mode, type, ref) }
  786. mode is an integer where:
  787. * 0040000 - Directory
  788. * 0100644 - Regular non-executable file
  789. * 0100664 - Regular non-executable group-writeable file
  790. * 0100755 - Regular executable file
  791. * 0120000 - Symbolic link
  792. * 0160000 - Gitlink
  793. type is a string where it's one of 'blob', 'commit', 'tree', 'tag'.
  794. ref is the hex encoded hash of the entry.
  795. """
  796. ret = {}
  797. opts = ['ls-tree', '--full-tree']
  798. if recurse:
  799. opts.append('-r')
  800. opts.append(treeref)
  801. try:
  802. for line in run(*opts).splitlines():
  803. mode, typ, ref, name = line.split(None, 3)
  804. ret[name] = (mode, typ, ref)
  805. except subprocess2.CalledProcessError:
  806. return None
  807. return ret
  808. def get_remote_url(remote='origin'):
  809. try:
  810. return run('config', 'remote.%s.url' % remote)
  811. except subprocess2.CalledProcessError:
  812. return None
  813. def upstream(branch):
  814. try:
  815. return run('rev-parse', '--abbrev-ref', '--symbolic-full-name',
  816. branch+'@{upstream}')
  817. except subprocess2.CalledProcessError:
  818. return None
  819. def get_git_version():
  820. """Returns a tuple that contains the numeric components of the current git
  821. version."""
  822. version_string = run('--version')
  823. version_match = re.search(r'(\d+.)+(\d+)', version_string)
  824. version = version_match.group() if version_match else ''
  825. return tuple(int(x) for x in version.split('.'))
  826. def get_branches_info(include_tracking_status):
  827. format_string = (
  828. '--format=%(refname:short):%(objectname:short):%(upstream:short):')
  829. # This is not covered by the depot_tools CQ which only has git version 1.8.
  830. if (include_tracking_status and
  831. get_git_version() >= MIN_UPSTREAM_TRACK_GIT_VERSION): # pragma: no cover
  832. format_string += '%(upstream:track)'
  833. info_map = {}
  834. data = run('for-each-ref', format_string, 'refs/heads')
  835. BranchesInfo = collections.namedtuple(
  836. 'BranchesInfo', 'hash upstream commits behind')
  837. for line in data.splitlines():
  838. (branch, branch_hash, upstream_branch, tracking_status) = line.split(':')
  839. commits = None
  840. if include_tracking_status:
  841. base = get_or_create_merge_base(branch)
  842. if base:
  843. commits_list = run('rev-list', '--count', branch, '^%s' % base, '--')
  844. commits = int(commits_list) or None
  845. behind_match = re.search(r'behind (\d+)', tracking_status)
  846. behind = int(behind_match.group(1)) if behind_match else None
  847. info_map[branch] = BranchesInfo(
  848. hash=branch_hash, upstream=upstream_branch, commits=commits,
  849. behind=behind)
  850. # Set None for upstreams which are not branches (e.g empty upstream, remotes
  851. # and deleted upstream branches).
  852. missing_upstreams = {}
  853. for info in info_map.values():
  854. if info.upstream not in info_map and info.upstream not in missing_upstreams:
  855. missing_upstreams[info.upstream] = None
  856. result = info_map.copy()
  857. result.update(missing_upstreams)
  858. return result
  859. def make_workdir_common(repository, new_workdir, files_to_symlink,
  860. files_to_copy, symlink=None):
  861. if not symlink:
  862. symlink = os.symlink
  863. os.makedirs(new_workdir)
  864. for entry in files_to_symlink:
  865. clone_file(repository, new_workdir, entry, symlink)
  866. for entry in files_to_copy:
  867. clone_file(repository, new_workdir, entry, shutil.copy)
  868. def make_workdir(repository, new_workdir):
  869. GIT_DIRECTORY_WHITELIST = [
  870. 'config',
  871. 'info',
  872. 'hooks',
  873. 'logs/refs',
  874. 'objects',
  875. 'packed-refs',
  876. 'refs',
  877. 'remotes',
  878. 'rr-cache',
  879. 'shallow',
  880. ]
  881. make_workdir_common(repository, new_workdir, GIT_DIRECTORY_WHITELIST,
  882. ['HEAD'])
  883. def clone_file(repository, new_workdir, link, operation):
  884. if not os.path.exists(os.path.join(repository, link)):
  885. return
  886. link_dir = os.path.dirname(os.path.join(new_workdir, link))
  887. if not os.path.exists(link_dir):
  888. os.makedirs(link_dir)
  889. src = os.path.join(repository, link)
  890. if os.path.islink(src):
  891. src = os.path.realpath(src)
  892. operation(src, os.path.join(new_workdir, link))