git_common.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  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_or_create_merge_base(branch, parent=None) -> Optional[str]:
  485. """Finds the configured merge base for branch.
  486. If parent is supplied, it's used instead of calling upstream(branch).
  487. """
  488. base: Optional[str] = branch_config(branch, 'base')
  489. base_upstream = branch_config(branch, 'base-upstream')
  490. parent = parent or upstream(branch)
  491. if parent is None or branch is None:
  492. return None
  493. actual_merge_base = run('merge-base', parent, branch)
  494. assert isinstance(actual_merge_base, str)
  495. if base_upstream != parent:
  496. base = None
  497. base_upstream = None
  498. def is_ancestor(a, b):
  499. return run_with_retcode('merge-base', '--is-ancestor', a, b) == 0
  500. if base and base != actual_merge_base:
  501. if not is_ancestor(base, branch):
  502. logging.debug('Found WRONG pre-set merge-base for %s: %s', branch,
  503. base)
  504. base = None
  505. elif is_ancestor(base, actual_merge_base):
  506. logging.debug('Found OLD pre-set merge-base for %s: %s', branch,
  507. base)
  508. base = None
  509. else:
  510. logging.debug('Found pre-set merge-base for %s: %s', branch, base)
  511. if not base:
  512. base = actual_merge_base
  513. manual_merge_base(branch, base, parent)
  514. assert isinstance(base, str)
  515. return base
  516. def hash_multi(*reflike):
  517. return run('rev-parse', *reflike).splitlines()
  518. def hash_one(reflike, short=False):
  519. args = ['rev-parse', reflike]
  520. if short:
  521. args.insert(1, '--short')
  522. return run(*args)
  523. def in_rebase():
  524. git_dir = run('rev-parse', '--git-dir')
  525. assert isinstance(git_dir, str)
  526. return (os.path.exists(os.path.join(git_dir, 'rebase-merge'))
  527. or os.path.exists(os.path.join(git_dir, 'rebase-apply')))
  528. def intern_f(f, kind='blob'):
  529. """Interns a file object into the git object store.
  530. Args:
  531. f (file-like object) - The file-like object to intern
  532. kind (git object type) - One of 'blob', 'commit', 'tree', 'tag'.
  533. Returns the git hash of the interned object (hex encoded).
  534. """
  535. ret = run('hash-object', '-t', kind, '-w', '--stdin', stdin=f)
  536. f.close()
  537. return ret
  538. def is_dormant(branch):
  539. # TODO(iannucci): Do an oldness check?
  540. return branch_config(branch, 'dormant', 'false') != 'false'
  541. def is_unmerged(stat_value):
  542. return ('U' in (stat_value.lstat, stat_value.rstat)
  543. or ((stat_value.lstat == stat_value.rstat)
  544. and stat_value.lstat in 'AD'))
  545. def manual_merge_base(branch, base, parent):
  546. set_branch_config(branch, 'base', base)
  547. set_branch_config(branch, 'base-upstream', parent)
  548. def mktree(treedict):
  549. """Makes a git tree object and returns its hash.
  550. See |tree()| for the values of mode, type, and ref.
  551. Args:
  552. treedict - { name: (mode, type, ref) }
  553. """
  554. with tempfile.TemporaryFile() as f:
  555. for name, (mode, typ, ref) in treedict.items():
  556. f.write(('%s %s %s\t%s\0' % (mode, typ, ref, name)).encode('utf-8'))
  557. f.seek(0)
  558. return run('mktree', '-z', stdin=f)
  559. def parse_commitrefs(*commitrefs):
  560. """Returns binary encoded commit hashes for one or more commitrefs.
  561. A commitref is anything which can resolve to a commit. Popular examples:
  562. * 'HEAD'
  563. * 'origin/main'
  564. * 'cool_branch~2'
  565. """
  566. hashes = []
  567. try:
  568. hashes = hash_multi(*commitrefs)
  569. return [binascii.unhexlify(h) for h in hashes]
  570. except subprocess2.CalledProcessError:
  571. raise BadCommitRefException(commitrefs)
  572. except binascii.Error as e:
  573. raise binascii.Error(f'{e}. Invalid hashes are {hashes}')
  574. RebaseRet = collections.namedtuple('RebaseRet', 'success stdout stderr')
  575. def rebase(parent, start, branch, abort=False, allow_gc=False):
  576. """Rebases |start|..|branch| onto the branch |parent|.
  577. Sets 'gc.auto=0' for the duration of this call to prevent the rebase from
  578. running a potentially slow garbage collection cycle.
  579. Args:
  580. parent - The new parent ref for the rebased commits.
  581. start - The commit to start from
  582. branch - The branch to rebase
  583. abort - If True, will call git-rebase --abort in the event that the
  584. rebase doesn't complete successfully.
  585. allow_gc - If True, sets "-c gc.auto=1" on the rebase call, rather than
  586. "-c gc.auto=0". Usually if you're doing a series of rebases,
  587. you'll only want to run a single gc pass at the end of all the
  588. rebase activity.
  589. Returns a namedtuple with fields:
  590. success - a boolean indicating that the rebase command completed
  591. successfully.
  592. message - if the rebase failed, this contains the stdout of the failed
  593. rebase.
  594. """
  595. try:
  596. args = [
  597. '-c',
  598. 'gc.auto={}'.format('1' if allow_gc else '0'),
  599. 'rebase',
  600. ]
  601. if TEST_MODE:
  602. args.append('--committer-date-is-author-date')
  603. args += [
  604. '--onto',
  605. parent,
  606. start,
  607. branch,
  608. ]
  609. run(*args)
  610. return RebaseRet(True, '', '')
  611. except subprocess2.CalledProcessError as cpe:
  612. if abort:
  613. run_with_retcode('rebase', '--abort') # ignore failure
  614. return RebaseRet(False, cpe.stdout.decode('utf-8', 'replace'),
  615. cpe.stderr.decode('utf-8', 'replace'))
  616. def remove_merge_base(branch):
  617. del_branch_config(branch, 'base')
  618. del_branch_config(branch, 'base-upstream')
  619. def repo_root():
  620. """Returns the absolute path to the repository root."""
  621. return run('rev-parse', '--show-toplevel')
  622. def upstream_default() -> str:
  623. """Returns the default branch name of the origin repository."""
  624. try:
  625. ret = run('rev-parse', '--abbrev-ref', 'origin/HEAD')
  626. # Detect if the repository migrated to main branch
  627. if ret == 'origin/master':
  628. try:
  629. ret = run('rev-parse', '--abbrev-ref', 'origin/main')
  630. run('remote', 'set-head', '-a', 'origin')
  631. ret = run('rev-parse', '--abbrev-ref', 'origin/HEAD')
  632. except subprocess2.CalledProcessError:
  633. pass
  634. assert isinstance(ret, str)
  635. return ret
  636. except subprocess2.CalledProcessError:
  637. return 'origin/main'
  638. def root():
  639. return get_config('depot-tools.upstream', upstream_default())
  640. @contextlib.contextmanager
  641. def less(): # pragma: no cover
  642. """Runs 'less' as context manager yielding its stdin as a PIPE.
  643. Automatically checks if sys.stdout is a non-TTY stream. If so, it avoids
  644. running less and just yields sys.stdout.
  645. The returned PIPE is opened on binary mode.
  646. """
  647. if not setup_color.IS_TTY:
  648. # On Python 3, sys.stdout doesn't accept bytes, and sys.stdout.buffer
  649. # must be used.
  650. yield getattr(sys.stdout, 'buffer', sys.stdout)
  651. return
  652. # Run with the same options that git uses (see setup_pager in git repo).
  653. # -F: Automatically quit if the output is less than one screen.
  654. # -R: Don't escape ANSI color codes.
  655. # -X: Don't clear the screen before starting.
  656. cmd = ('less', '-FRX')
  657. proc = subprocess2.Popen(cmd, stdin=subprocess2.PIPE)
  658. try:
  659. yield proc.stdin
  660. finally:
  661. assert proc.stdin is not None
  662. try:
  663. proc.stdin.close()
  664. except BrokenPipeError:
  665. # BrokenPipeError is raised if proc has already completed,
  666. pass
  667. proc.wait()
  668. def run(*cmd, **kwargs) -> str | bytes:
  669. """The same as run_with_stderr, except it only returns stdout."""
  670. return run_with_stderr(*cmd, **kwargs)[0]
  671. def run_with_retcode(*cmd, **kwargs):
  672. """Run a command but only return the status code."""
  673. try:
  674. run(*cmd, **kwargs)
  675. return 0
  676. except subprocess2.CalledProcessError as cpe:
  677. return cpe.returncode
  678. def run_stream(*cmd, **kwargs) -> typing.IO[AnyStr]:
  679. """Runs a git command. Returns stdout as a PIPE (file-like object).
  680. stderr is dropped to avoid races if the process outputs to both stdout and
  681. stderr.
  682. """
  683. kwargs.setdefault('stderr', subprocess2.DEVNULL)
  684. kwargs.setdefault('stdout', subprocess2.PIPE)
  685. kwargs.setdefault('shell', False)
  686. cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
  687. proc = subprocess2.Popen(cmd, **kwargs)
  688. assert proc.stdout is not None
  689. return proc.stdout
  690. @contextlib.contextmanager
  691. def run_stream_with_retcode(*cmd, **kwargs):
  692. """Runs a git command as context manager yielding stdout as a PIPE.
  693. stderr is dropped to avoid races if the process outputs to both stdout and
  694. stderr.
  695. Raises subprocess2.CalledProcessError on nonzero return code.
  696. """
  697. kwargs.setdefault('stderr', subprocess2.DEVNULL)
  698. kwargs.setdefault('stdout', subprocess2.PIPE)
  699. kwargs.setdefault('shell', False)
  700. cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
  701. proc = subprocess2.Popen(cmd, **kwargs)
  702. try:
  703. yield proc.stdout
  704. finally:
  705. retcode = proc.wait()
  706. if retcode != 0:
  707. raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(), b'',
  708. b'')
  709. def run_with_stderr(*cmd, **kwargs) -> Tuple[str, str] | Tuple[bytes, bytes]:
  710. """Runs a git command.
  711. Returns (stdout, stderr) as a pair of strings.
  712. If the command is `config` and the execution fails due to a lock failure,
  713. retry the execution at most 5 times with 0.2 interval.
  714. kwargs
  715. autostrip (bool) - Strip the output. Defaults to True.
  716. indata (str) - Specifies stdin data for the process.
  717. retry_lock (bool) - If true and the command is `config`,
  718. retry on lock failures. Defaults to True.
  719. """
  720. retry_cnt = 0
  721. if kwargs.pop('retry_lock', True) and len(cmd) > 0 and cmd[0] == 'config':
  722. retry_cnt = 5
  723. while True:
  724. try:
  725. return _run_with_stderr(*cmd, **kwargs)
  726. except subprocess2.CalledProcessError as ex:
  727. lock_err = 'could not lock config file .git/config: File exists'
  728. if retry_cnt > 0 and lock_err in str(ex):
  729. logging.error(ex)
  730. jitter = random.uniform(0, 0.2)
  731. time.sleep(0.1 + jitter)
  732. retry_cnt -= 1
  733. continue
  734. raise ex
  735. def _run_with_stderr(*cmd, **kwargs) -> Tuple[str, str] | Tuple[bytes, bytes]:
  736. """Runs a git command.
  737. Returns (stdout, stderr) as a pair of bytes or strings.
  738. kwargs
  739. autostrip (bool) - Strip the output. Defaults to True.
  740. decode (bool) - Whether to return strings. Defaults to True.
  741. indata (str) - Specifies stdin data for the process.
  742. """
  743. kwargs.setdefault('stdin', subprocess2.PIPE)
  744. kwargs.setdefault('stdout', subprocess2.PIPE)
  745. kwargs.setdefault('stderr', subprocess2.PIPE)
  746. kwargs.setdefault('shell', False)
  747. autostrip = kwargs.pop('autostrip', True)
  748. indata = kwargs.pop('indata', None)
  749. decode = kwargs.pop('decode', True)
  750. accepted_retcodes = kwargs.pop('accepted_retcodes', [0])
  751. cmd = (GIT_EXE, '-c', 'color.ui=never') + cmd
  752. proc = subprocess2.Popen(cmd, **kwargs)
  753. stdout, stderr = proc.communicate(indata)
  754. retcode = proc.wait()
  755. if retcode not in accepted_retcodes:
  756. raise subprocess2.CalledProcessError(retcode, cmd, os.getcwd(), stdout,
  757. stderr)
  758. if autostrip:
  759. stdout = (stdout or b'').strip()
  760. stderr = (stderr or b'').strip()
  761. if decode:
  762. return stdout.decode('utf-8',
  763. 'replace'), stderr.decode('utf-8', 'replace')
  764. return stdout, stderr
  765. def set_branch_config(branch,
  766. option,
  767. value,
  768. scope: scm.GitConfigScope = 'local'):
  769. set_config('branch.%s.%s' % (branch, option), value, scope=scope)
  770. def set_config(option, value, scope: scm.GitConfigScope = 'local'):
  771. scm.GIT.SetConfig(os.getcwd(), option, value, scope=scope)
  772. def get_dirty_files():
  773. # Make sure index is up-to-date before running diff-index.
  774. run_with_retcode('update-index', '--refresh', '-q')
  775. return run('diff-index', '--ignore-submodules', '--name-status', 'HEAD',
  776. '--')
  777. def is_dirty_git_tree(cmd):
  778. w = lambda s: sys.stderr.write(s + "\n")
  779. dirty = get_dirty_files()
  780. if dirty:
  781. w('Cannot %s with a dirty tree. Commit%s or stash your changes first.' %
  782. (cmd, '' if cmd == 'upload' else ', freeze'))
  783. w('Uncommitted files: (git diff-index --name-status HEAD)')
  784. w(dirty[:4096])
  785. if len(dirty) > 4096: # pragma: no cover
  786. w('... (run "git diff-index --name-status HEAD" to see full '
  787. 'output).')
  788. return True
  789. return False
  790. def status(ignore_submodules=None):
  791. """Returns a parsed version of git-status.
  792. Args:
  793. ignore_submodules (str|None): "all", "none", or None.
  794. None is equivalent to "none".
  795. Returns a generator of (current_name, (lstat, rstat, src)) pairs where:
  796. * current_name is the name of the file
  797. * lstat is the left status code letter from git-status
  798. * rstat is the right status code letter from git-status
  799. * src is the current name of the file, or the original name of the file
  800. if lstat == 'R'
  801. """
  802. ignore_submodules = ignore_submodules or 'none'
  803. assert ignore_submodules in (
  804. 'all',
  805. 'none'), f'ignore_submodules value {ignore_submodules} is invalid'
  806. stat_entry = collections.namedtuple('stat_entry', 'lstat rstat src')
  807. def tokenizer(stream):
  808. acc = BytesIO()
  809. c = None
  810. while c != b'':
  811. c = stream.read(1)
  812. if c in (None, b'', b'\0'):
  813. if len(acc.getvalue()) > 0:
  814. yield acc.getvalue()
  815. acc = BytesIO()
  816. else:
  817. acc.write(c)
  818. def parser(tokens):
  819. while True:
  820. try:
  821. status_dest = next(tokens).decode('utf-8')
  822. except StopIteration:
  823. return
  824. stat, dest = status_dest[:2], status_dest[3:]
  825. lstat, rstat = stat
  826. if lstat == 'R':
  827. src = next(tokens).decode('utf-8')
  828. else:
  829. src = dest
  830. yield (dest, stat_entry(lstat, rstat, src))
  831. return parser(
  832. tokenizer(
  833. run_stream('status',
  834. '-z',
  835. f'--ignore-submodules={ignore_submodules}',
  836. bufsize=-1)))
  837. def squash_current_branch(header=None, merge_base=None):
  838. header = header or 'git squash commit for %s.' % current_branch()
  839. merge_base = merge_base or get_or_create_merge_base(current_branch())
  840. log_msg = header + '\n'
  841. if log_msg:
  842. log_msg += '\n'
  843. output = run('log', '--reverse', '--format=%H%n%B', '%s..HEAD' % merge_base)
  844. assert isinstance(output, str)
  845. log_msg += output
  846. run('reset', '--soft', merge_base)
  847. if not get_dirty_files():
  848. # Sometimes the squash can result in the same tree, meaning that there
  849. # is nothing to commit at this point.
  850. print('Nothing to commit; squashed branch is empty')
  851. return False
  852. # git reset --soft will stage all changes so we can just commit those.
  853. # Note: Just before reset --soft is called, we may have git submodules
  854. # checked to an old commit (not latest state). We don't want to include
  855. # those in our commit.
  856. run('commit',
  857. '--no-verify',
  858. '-F',
  859. '-',
  860. indata=log_msg.encode('utf-8'))
  861. return True
  862. def tags(*args):
  863. return run('tag', *args).splitlines()
  864. def thaw():
  865. took_action = False
  866. with run_stream('rev-list', 'HEAD', '--') as stream:
  867. for sha in stream:
  868. sha = sha.strip().decode('utf-8')
  869. msg = run('show', '--format=%f%b', '-s', 'HEAD', '--')
  870. assert isinstance(msg, str)
  871. match = FREEZE_MATCHER.match(msg)
  872. if not match:
  873. if not took_action:
  874. return 'Nothing to thaw.'
  875. break
  876. run('reset', '--' + FREEZE_SECTIONS[match.group(1)], sha)
  877. took_action = True
  878. def topo_iter(branch_tree, top_down=True):
  879. """Generates (branch, parent) in topographical order for a branch tree.
  880. Given a tree:
  881. A1
  882. B1 B2
  883. C1 C2 C3
  884. D1
  885. branch_tree would look like: {
  886. 'D1': 'C3',
  887. 'C3': 'B2',
  888. 'B2': 'A1',
  889. 'C1': 'B1',
  890. 'C2': 'B1',
  891. 'B1': 'A1',
  892. }
  893. It is OK to have multiple 'root' nodes in your graph.
  894. if top_down is True, items are yielded from A->D. Otherwise they're yielded
  895. from D->A. Within a layer the branches will be yielded in sorted order.
  896. """
  897. branch_tree = branch_tree.copy()
  898. # TODO(iannucci): There is probably a more efficient way to do these.
  899. if top_down:
  900. while branch_tree:
  901. this_pass = [(b, p) for b, p in branch_tree.items()
  902. if p not in branch_tree]
  903. assert this_pass, "Branch tree has cycles: %r" % branch_tree
  904. for branch, parent in sorted(this_pass):
  905. yield branch, parent
  906. del branch_tree[branch]
  907. else:
  908. parent_to_branches = collections.defaultdict(set)
  909. for branch, parent in branch_tree.items():
  910. parent_to_branches[parent].add(branch)
  911. while branch_tree:
  912. this_pass = [(b, p) for b, p in branch_tree.items()
  913. if not parent_to_branches[b]]
  914. assert this_pass, "Branch tree has cycles: %r" % branch_tree
  915. for branch, parent in sorted(this_pass):
  916. yield branch, parent
  917. parent_to_branches[parent].discard(branch)
  918. del branch_tree[branch]
  919. def tree(treeref, recurse=False):
  920. """Returns a dict representation of a git tree object.
  921. Args:
  922. treeref (str) - a git ref which resolves to a tree (commits count as
  923. trees).
  924. recurse (bool) - include all of the tree's descendants too. File names
  925. will take the form of 'some/path/to/file'.
  926. Return format:
  927. { 'file_name': (mode, type, ref) }
  928. mode is an integer where:
  929. * 0040000 - Directory
  930. * 0100644 - Regular non-executable file
  931. * 0100664 - Regular non-executable group-writeable file
  932. * 0100755 - Regular executable file
  933. * 0120000 - Symbolic link
  934. * 0160000 - Gitlink
  935. type is a string where it's one of 'blob', 'commit', 'tree', 'tag'.
  936. ref is the hex encoded hash of the entry.
  937. """
  938. ret = {}
  939. opts = ['ls-tree', '--full-tree']
  940. if recurse:
  941. opts.append('-r')
  942. opts.append(treeref)
  943. try:
  944. for line in run(*opts).splitlines():
  945. mode, typ, ref, name = line.split(None, 3)
  946. ret[name] = (mode, typ, ref)
  947. except subprocess2.CalledProcessError:
  948. return None
  949. return ret
  950. def get_remote_url(remote='origin'):
  951. return scm.GIT.GetConfig(os.getcwd(), 'remote.%s.url' % remote)
  952. def upstream(branch):
  953. try:
  954. return run('rev-parse', '--abbrev-ref', '--symbolic-full-name',
  955. branch + '@{upstream}')
  956. except subprocess2.CalledProcessError:
  957. return None
  958. @functools.lru_cache
  959. def check_git_version(
  960. min_version: Tuple[int] = GIT_MIN_VERSION) -> Optional[str]:
  961. """Checks whether git is installed, and its version meets the recommended
  962. minimum version, which defaults to GIT_MIN_VERSION if not specified.
  963. Returns:
  964. - the remediation action to take.
  965. """
  966. if gclient_utils.IsEnvCog():
  967. # No remediation action required in a non-git environment.
  968. return None
  969. min_tag = '.'.join(str(x) for x in min_version)
  970. if shutil.which(GIT_EXE) is None:
  971. # git command was not found.
  972. return ('git command not found.\n'
  973. f'Please install version >={min_tag} of git.\n'
  974. 'See instructions at\n'
  975. 'https://git-scm.com/book/en/v2/Getting-Started-Installing-Git')
  976. if meets_git_version(min_version):
  977. # git version is sufficient; no remediation action necessary.
  978. return None
  979. # git is installed but older than the recommended version.
  980. tag = '.'.join(str(x) for x in get_git_version()) or 'unknown'
  981. return ('git update is recommended.\n'
  982. f'Installed git version is {tag};\n'
  983. f'depot_tools recommends version {min_tag} or later.')
  984. def meets_git_version(min_version: Tuple[int]) -> bool:
  985. """Returns whether the current git version meets the minimum specified."""
  986. return get_git_version() >= min_version
  987. @functools.lru_cache(maxsize=1)
  988. def get_git_version():
  989. """Returns a tuple that contains the numeric components of the current git
  990. version."""
  991. version_string = run('--version')
  992. return _extract_git_tuple(version_string)
  993. def _extract_git_tuple(version_string):
  994. version_match = re.search(r'(\d+.)+(\d+)', version_string)
  995. if version_match:
  996. version = version_match.group()
  997. return tuple(int(x) for x in version.split('.'))
  998. return tuple()
  999. def get_num_commits(branch):
  1000. base = get_or_create_merge_base(branch)
  1001. if base:
  1002. commits_list = run('rev-list', '--count', branch, '^%s' % base, '--')
  1003. return int(commits_list) or None
  1004. return None
  1005. def get_branches_info(include_tracking_status):
  1006. format_string = (
  1007. '--format=%(refname:short):%(objectname:short):%(upstream:short):')
  1008. # This is not covered by the depot_tools CQ which only has git version 1.8.
  1009. if (include_tracking_status and get_git_version() >=
  1010. MIN_UPSTREAM_TRACK_GIT_VERSION): # pragma: no cover
  1011. format_string += '%(upstream:track)'
  1012. info_map = {}
  1013. data = run('for-each-ref', format_string, 'refs/heads')
  1014. assert isinstance(data, str)
  1015. BranchesInfo = collections.namedtuple('BranchesInfo',
  1016. 'hash upstream commits behind')
  1017. for line in data.splitlines():
  1018. (branch, branch_hash, upstream_branch,
  1019. tracking_status) = line.split(':')
  1020. commits = None
  1021. if include_tracking_status:
  1022. commits = get_num_commits(branch)
  1023. behind_match = re.search(r'behind (\d+)', tracking_status)
  1024. behind = int(behind_match.group(1)) if behind_match else None
  1025. info_map[branch] = BranchesInfo(hash=branch_hash,
  1026. upstream=upstream_branch,
  1027. commits=commits,
  1028. behind=behind)
  1029. # Set None for upstreams which are not branches (e.g empty upstream, remotes
  1030. # and deleted upstream branches).
  1031. missing_upstreams = {}
  1032. for info in info_map.values():
  1033. if (info.upstream not in info_map
  1034. and info.upstream not in missing_upstreams):
  1035. missing_upstreams[info.upstream] = None
  1036. result = info_map.copy()
  1037. result.update(missing_upstreams)
  1038. return result
  1039. def make_workdir_common(repository,
  1040. new_workdir,
  1041. files_to_symlink,
  1042. files_to_copy,
  1043. symlink=None):
  1044. if not symlink:
  1045. symlink = os.symlink
  1046. os.makedirs(new_workdir)
  1047. for entry in files_to_symlink:
  1048. clone_file(repository, new_workdir, entry, symlink)
  1049. for entry in files_to_copy:
  1050. clone_file(repository, new_workdir, entry, shutil.copy)
  1051. def make_workdir(repository, new_workdir):
  1052. GIT_DIRECTORY_WHITELIST = [
  1053. 'config',
  1054. 'info',
  1055. 'hooks',
  1056. 'logs/refs',
  1057. 'objects',
  1058. 'packed-refs',
  1059. 'refs',
  1060. 'remotes',
  1061. 'rr-cache',
  1062. 'shallow',
  1063. ]
  1064. make_workdir_common(repository, new_workdir, GIT_DIRECTORY_WHITELIST,
  1065. ['HEAD'])
  1066. def clone_file(repository, new_workdir, link, operation):
  1067. if not os.path.exists(os.path.join(repository, link)):
  1068. return
  1069. link_dir = os.path.dirname(os.path.join(new_workdir, link))
  1070. if not os.path.exists(link_dir):
  1071. os.makedirs(link_dir)
  1072. src = os.path.join(repository, link)
  1073. if os.path.islink(src):
  1074. src = os.path.realpath(src)
  1075. operation(src, os.path.join(new_workdir, link))