git_common.py 32 KB

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