git_common.py 42 KB

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