git_common.py 37 KB

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