git_common.py 33 KB

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