git_common.py 37 KB

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