git_common.py 45 KB

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