git_cache.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. #!/usr/bin/env python
  2. # Copyright 2014 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """A git command for managing a local cache of git repositories."""
  6. from __future__ import print_function
  7. import contextlib
  8. import errno
  9. import logging
  10. import optparse
  11. import os
  12. import re
  13. import subprocess
  14. import sys
  15. import tempfile
  16. import threading
  17. import time
  18. try:
  19. import urlparse
  20. except ImportError: # For Py3 compatibility
  21. import urllib.parse as urlparse
  22. from download_from_google_storage import Gsutil
  23. import gclient_utils
  24. import lockfile
  25. import subcommand
  26. # Analogous to gc.autopacklimit git config.
  27. GC_AUTOPACKLIMIT = 50
  28. GIT_CACHE_CORRUPT_MESSAGE = 'WARNING: The Git cache is corrupt.'
  29. try:
  30. # pylint: disable=undefined-variable
  31. WinErr = WindowsError
  32. except NameError:
  33. class WinErr(Exception):
  34. pass
  35. class ClobberNeeded(Exception):
  36. pass
  37. def exponential_backoff_retry(fn, excs=(Exception,), name=None, count=10,
  38. sleep_time=0.25, printerr=None):
  39. """Executes |fn| up to |count| times, backing off exponentially.
  40. Args:
  41. fn (callable): The function to execute. If this raises a handled
  42. exception, the function will retry with exponential backoff.
  43. excs (tuple): A tuple of Exception types to handle. If one of these is
  44. raised by |fn|, a retry will be attempted. If |fn| raises an Exception
  45. that is not in this list, it will immediately pass through. If |excs|
  46. is empty, the Exception base class will be used.
  47. name (str): Optional operation name to print in the retry string.
  48. count (int): The number of times to try before allowing the exception to
  49. pass through.
  50. sleep_time (float): The initial number of seconds to sleep in between
  51. retries. This will be doubled each retry.
  52. printerr (callable): Function that will be called with the error string upon
  53. failures. If None, |logging.warning| will be used.
  54. Returns: The return value of the successful fn.
  55. """
  56. printerr = printerr or logging.warning
  57. for i in range(count):
  58. try:
  59. return fn()
  60. except excs as e:
  61. if (i+1) >= count:
  62. raise
  63. printerr('Retrying %s in %.2f second(s) (%d / %d attempts): %s' % (
  64. (name or 'operation'), sleep_time, (i+1), count, e))
  65. time.sleep(sleep_time)
  66. sleep_time *= 2
  67. class Mirror(object):
  68. git_exe = 'git.bat' if sys.platform.startswith('win') else 'git'
  69. gsutil_exe = os.path.join(
  70. os.path.dirname(os.path.abspath(__file__)), 'gsutil.py')
  71. cachepath_lock = threading.Lock()
  72. UNSET_CACHEPATH = object()
  73. # Used for tests
  74. _GIT_CONFIG_LOCATION = []
  75. @staticmethod
  76. def parse_fetch_spec(spec):
  77. """Parses and canonicalizes a fetch spec.
  78. Returns (fetchspec, value_regex), where value_regex can be used
  79. with 'git config --replace-all'.
  80. """
  81. parts = spec.split(':', 1)
  82. src = parts[0].lstrip('+').rstrip('/')
  83. if not src.startswith('refs/'):
  84. src = 'refs/heads/%s' % src
  85. dest = parts[1].rstrip('/') if len(parts) > 1 else src
  86. regex = r'\+%s:.*' % src.replace('*', r'\*')
  87. return ('+%s:%s' % (src, dest), regex)
  88. def __init__(self, url, refs=None, print_func=None):
  89. self.url = url
  90. self.fetch_specs = set([self.parse_fetch_spec(ref) for ref in (refs or [])])
  91. self.basedir = self.UrlToCacheDir(url)
  92. self.mirror_path = os.path.join(self.GetCachePath(), self.basedir)
  93. if print_func:
  94. self.print = self.print_without_file
  95. self.print_func = print_func
  96. else:
  97. self.print = print
  98. def print_without_file(self, message, **_kwargs):
  99. self.print_func(message)
  100. @contextlib.contextmanager
  101. def print_duration_of(self, what):
  102. start = time.time()
  103. try:
  104. yield
  105. finally:
  106. self.print('%s took %.1f minutes' % (what, (time.time() - start) / 60.0))
  107. @property
  108. def bootstrap_bucket(self):
  109. b = os.getenv('OVERRIDE_BOOTSTRAP_BUCKET')
  110. if b:
  111. return b
  112. u = urlparse.urlparse(self.url)
  113. if u.netloc == 'chromium.googlesource.com':
  114. return 'chromium-git-cache'
  115. # Not recognized.
  116. return None
  117. @property
  118. def _gs_path(self):
  119. return 'gs://%s/v2/%s' % (self.bootstrap_bucket, self.basedir)
  120. @classmethod
  121. def FromPath(cls, path):
  122. return cls(cls.CacheDirToUrl(path))
  123. @staticmethod
  124. def UrlToCacheDir(url):
  125. """Convert a git url to a normalized form for the cache dir path."""
  126. if os.path.isdir(url):
  127. # Ignore the drive letter in Windows
  128. url = os.path.splitdrive(url)[1]
  129. return url.replace('-', '--').replace(os.sep, '-')
  130. parsed = urlparse.urlparse(url)
  131. norm_url = parsed.netloc + parsed.path
  132. if norm_url.endswith('.git'):
  133. norm_url = norm_url[:-len('.git')]
  134. # Use the same dir for authenticated URLs and unauthenticated URLs.
  135. norm_url = norm_url.replace('googlesource.com/a/', 'googlesource.com/')
  136. return norm_url.replace('-', '--').replace('/', '-').lower()
  137. @staticmethod
  138. def CacheDirToUrl(path):
  139. """Convert a cache dir path to its corresponding url."""
  140. netpath = re.sub(r'\b-\b', '/', os.path.basename(path)).replace('--', '-')
  141. return 'https://%s' % netpath
  142. @classmethod
  143. def SetCachePath(cls, cachepath):
  144. with cls.cachepath_lock:
  145. setattr(cls, 'cachepath', cachepath)
  146. @classmethod
  147. def GetCachePath(cls):
  148. with cls.cachepath_lock:
  149. if not hasattr(cls, 'cachepath'):
  150. try:
  151. cachepath = subprocess.check_output(
  152. [cls.git_exe, 'config'] +
  153. cls._GIT_CONFIG_LOCATION +
  154. ['cache.cachepath']).decode('utf-8', 'ignore').strip()
  155. except subprocess.CalledProcessError:
  156. cachepath = os.environ.get('GIT_CACHE_PATH', cls.UNSET_CACHEPATH)
  157. setattr(cls, 'cachepath', cachepath)
  158. ret = getattr(cls, 'cachepath')
  159. if ret is cls.UNSET_CACHEPATH:
  160. raise RuntimeError('No cache.cachepath git configuration or '
  161. '$GIT_CACHE_PATH is set.')
  162. return ret
  163. @staticmethod
  164. def _GetMostRecentCacheDirectory(ls_out_set):
  165. ready_file_pattern = re.compile(r'.*/(\d+).ready$')
  166. ready_dirs = []
  167. for name in ls_out_set:
  168. m = ready_file_pattern.match(name)
  169. # Given <path>/<number>.ready,
  170. # we are interested in <path>/<number> directory
  171. if m and (name[:-len('.ready')] + '/') in ls_out_set:
  172. ready_dirs.append((int(m.group(1)), name[:-len('.ready')]))
  173. if not ready_dirs:
  174. return None
  175. return max(ready_dirs)[1]
  176. def Rename(self, src, dst):
  177. # This is somehow racy on Windows.
  178. # Catching OSError because WindowsError isn't portable and
  179. # pylint complains.
  180. exponential_backoff_retry(
  181. lambda: os.rename(src, dst),
  182. excs=(OSError,),
  183. name='rename [%s] => [%s]' % (src, dst),
  184. printerr=self.print)
  185. def RunGit(self, cmd, **kwargs):
  186. """Run git in a subprocess."""
  187. cwd = kwargs.setdefault('cwd', self.mirror_path)
  188. kwargs.setdefault('print_stdout', False)
  189. kwargs.setdefault('filter_fn', self.print)
  190. env = kwargs.get('env') or kwargs.setdefault('env', os.environ.copy())
  191. env.setdefault('GIT_ASKPASS', 'true')
  192. env.setdefault('SSH_ASKPASS', 'true')
  193. self.print('running "git %s" in "%s"' % (' '.join(cmd), cwd))
  194. gclient_utils.CheckCallAndFilter([self.git_exe] + cmd, **kwargs)
  195. def config(self, cwd=None, reset_fetch_config=False):
  196. if cwd is None:
  197. cwd = self.mirror_path
  198. if reset_fetch_config:
  199. try:
  200. self.RunGit(['config', '--unset-all', 'remote.origin.fetch'], cwd=cwd)
  201. except subprocess.CalledProcessError as e:
  202. # If exit code was 5, it means we attempted to unset a config that
  203. # didn't exist. Ignore it.
  204. if e.returncode != 5:
  205. raise
  206. # Don't run git-gc in a daemon. Bad things can happen if it gets killed.
  207. try:
  208. self.RunGit(['config', 'gc.autodetach', '0'], cwd=cwd)
  209. except subprocess.CalledProcessError:
  210. # Hard error, need to clobber.
  211. raise ClobberNeeded()
  212. # Don't combine pack files into one big pack file. It's really slow for
  213. # repositories, and there's no way to track progress and make sure it's
  214. # not stuck.
  215. if self.supported_project():
  216. self.RunGit(['config', 'gc.autopacklimit', '0'], cwd=cwd)
  217. # Allocate more RAM for cache-ing delta chains, for better performance
  218. # of "Resolving deltas".
  219. self.RunGit(['config', 'core.deltaBaseCacheLimit',
  220. gclient_utils.DefaultDeltaBaseCacheLimit()], cwd=cwd)
  221. self.RunGit(['config', 'remote.origin.url', self.url], cwd=cwd)
  222. self.RunGit(['config', '--replace-all', 'remote.origin.fetch',
  223. '+refs/heads/*:refs/heads/*', r'\+refs/heads/\*:.*'], cwd=cwd)
  224. for spec, value_regex in self.fetch_specs:
  225. self.RunGit(
  226. ['config', '--replace-all', 'remote.origin.fetch', spec, value_regex],
  227. cwd=cwd)
  228. def bootstrap_repo(self, directory):
  229. """Bootstrap the repo from Google Storage if possible.
  230. More apt-ly named bootstrap_repo_from_cloud_if_possible_else_do_nothing().
  231. """
  232. if not self.bootstrap_bucket:
  233. return False
  234. gsutil = Gsutil(self.gsutil_exe, boto_path=None)
  235. # Get the most recent version of the directory.
  236. # This is determined from the most recent version of a .ready file.
  237. # The .ready file is only uploaded when an entire directory has been
  238. # uploaded to GS.
  239. _, ls_out, ls_err = gsutil.check_call('ls', self._gs_path)
  240. ls_out_set = set(ls_out.strip().splitlines())
  241. latest_dir = self._GetMostRecentCacheDirectory(ls_out_set)
  242. if not latest_dir:
  243. self.print('No bootstrap file for %s found in %s, stderr:\n %s' %
  244. (self.mirror_path, self.bootstrap_bucket,
  245. ' '.join((ls_err or '').splitlines(True))))
  246. return False
  247. try:
  248. # create new temporary directory locally
  249. tempdir = tempfile.mkdtemp(prefix='_cache_tmp', dir=self.GetCachePath())
  250. self.RunGit(['init', '--bare'], cwd=tempdir)
  251. self.print('Downloading files in %s/* into %s.' %
  252. (latest_dir, tempdir))
  253. with self.print_duration_of('download'):
  254. code = gsutil.call('-m', 'cp', '-r', latest_dir + "/*",
  255. tempdir)
  256. if code:
  257. return False
  258. # A quick validation that all references are valid.
  259. self.RunGit(['for-each-ref'], cwd=tempdir)
  260. except Exception as e:
  261. self.print('Encountered error: %s' % str(e), file=sys.stderr)
  262. gclient_utils.rmtree(tempdir)
  263. return False
  264. # delete the old directory
  265. if os.path.exists(directory):
  266. gclient_utils.rmtree(directory)
  267. self.Rename(tempdir, directory)
  268. return True
  269. def contains_revision(self, revision):
  270. if not self.exists():
  271. return False
  272. if sys.platform.startswith('win'):
  273. # Windows .bat scripts use ^ as escape sequence, which means we have to
  274. # escape it with itself for every .bat invocation.
  275. needle = '%s^^^^{commit}' % revision
  276. else:
  277. needle = '%s^{commit}' % revision
  278. try:
  279. # cat-file exits with 0 on success, that is git object of given hash was
  280. # found.
  281. self.RunGit(['cat-file', '-e', needle])
  282. return True
  283. except subprocess.CalledProcessError:
  284. return False
  285. def exists(self):
  286. return os.path.isfile(os.path.join(self.mirror_path, 'config'))
  287. def supported_project(self):
  288. """Returns true if this repo is known to have a bootstrap zip file."""
  289. u = urlparse.urlparse(self.url)
  290. return u.netloc in [
  291. 'chromium.googlesource.com',
  292. 'chrome-internal.googlesource.com']
  293. def _preserve_fetchspec(self):
  294. """Read and preserve remote.origin.fetch from an existing mirror.
  295. This modifies self.fetch_specs.
  296. """
  297. if not self.exists():
  298. return
  299. try:
  300. config_fetchspecs = subprocess.check_output(
  301. [self.git_exe, 'config', '--get-all', 'remote.origin.fetch'],
  302. cwd=self.mirror_path).decode('utf-8', 'ignore')
  303. for fetchspec in config_fetchspecs.splitlines():
  304. self.fetch_specs.add(self.parse_fetch_spec(fetchspec))
  305. except subprocess.CalledProcessError:
  306. logging.warning(
  307. 'Tried and failed to preserve remote.origin.fetch from the '
  308. 'existing cache directory. You may need to manually edit '
  309. '%s and "git cache fetch" again.' %
  310. os.path.join(self.mirror_path, 'config'))
  311. def _ensure_bootstrapped(
  312. self, depth, bootstrap, reset_fetch_config, force=False):
  313. pack_dir = os.path.join(self.mirror_path, 'objects', 'pack')
  314. pack_files = []
  315. if os.path.isdir(pack_dir):
  316. pack_files = [f for f in os.listdir(pack_dir) if f.endswith('.pack')]
  317. self.print('%s has %d .pack files, re-bootstrapping if >%d or ==0' %
  318. (self.mirror_path, len(pack_files), GC_AUTOPACKLIMIT))
  319. should_bootstrap = (force or
  320. not self.exists() or
  321. len(pack_files) > GC_AUTOPACKLIMIT or
  322. len(pack_files) == 0)
  323. if not should_bootstrap:
  324. if depth and os.path.exists(os.path.join(self.mirror_path, 'shallow')):
  325. logging.warning(
  326. 'Shallow fetch requested, but repo cache already exists.')
  327. return
  328. if not self.exists():
  329. if os.path.exists(self.mirror_path):
  330. # If the mirror path exists but self.exists() returns false, we're
  331. # in an unexpected state. Nuke the previous mirror directory and
  332. # start fresh.
  333. gclient_utils.rmtree(self.mirror_path)
  334. os.mkdir(self.mirror_path)
  335. elif not reset_fetch_config:
  336. # Re-bootstrapping an existing mirror; preserve existing fetch spec.
  337. self._preserve_fetchspec()
  338. bootstrapped = (not depth and bootstrap and
  339. self.bootstrap_repo(self.mirror_path))
  340. if not bootstrapped:
  341. if not self.exists() or not self.supported_project():
  342. # Bootstrap failed due to:
  343. # 1. No previous cache.
  344. # 2. Project doesn't have a bootstrap folder.
  345. # Start with a bare git dir.
  346. self.RunGit(['init', '--bare'], cwd=self.mirror_path)
  347. else:
  348. # Bootstrap failed, previous cache exists; warn and continue.
  349. logging.warning(
  350. 'Git cache has a lot of pack files (%d). Tried to re-bootstrap '
  351. 'but failed. Continuing with non-optimized repository.' %
  352. len(pack_files))
  353. def _fetch(self,
  354. rundir,
  355. verbose,
  356. depth,
  357. no_fetch_tags,
  358. reset_fetch_config,
  359. prune=True):
  360. self.config(rundir, reset_fetch_config)
  361. fetch_cmd = ['fetch']
  362. if verbose:
  363. fetch_cmd.extend(['-v', '--progress'])
  364. if depth:
  365. fetch_cmd.extend(['--depth', str(depth)])
  366. if no_fetch_tags:
  367. fetch_cmd.append('--no-tags')
  368. if prune:
  369. fetch_cmd.append('--prune')
  370. fetch_cmd.append('origin')
  371. fetch_specs = subprocess.check_output(
  372. [self.git_exe, 'config', '--get-all', 'remote.origin.fetch'],
  373. cwd=rundir).decode('utf-8', 'ignore').strip().splitlines()
  374. for spec in fetch_specs:
  375. try:
  376. self.print('Fetching %s' % spec)
  377. with self.print_duration_of('fetch %s' % spec):
  378. self.RunGit(fetch_cmd + [spec], cwd=rundir, retry=True)
  379. except subprocess.CalledProcessError:
  380. if spec == '+refs/heads/*:refs/heads/*':
  381. raise ClobberNeeded() # Corrupted cache.
  382. logging.warning('Fetch of %s failed' % spec)
  383. def populate(self,
  384. depth=None,
  385. no_fetch_tags=False,
  386. shallow=False,
  387. bootstrap=False,
  388. verbose=False,
  389. lock_timeout=0,
  390. reset_fetch_config=False):
  391. assert self.GetCachePath()
  392. if shallow and not depth:
  393. depth = 10000
  394. gclient_utils.safe_makedirs(self.GetCachePath())
  395. with lockfile.lock(self.mirror_path, lock_timeout):
  396. try:
  397. self._ensure_bootstrapped(depth, bootstrap, reset_fetch_config)
  398. self._fetch(self.mirror_path, verbose, depth, no_fetch_tags,
  399. reset_fetch_config)
  400. except ClobberNeeded:
  401. # This is a major failure, we need to clean and force a bootstrap.
  402. gclient_utils.rmtree(self.mirror_path)
  403. self.print(GIT_CACHE_CORRUPT_MESSAGE)
  404. self._ensure_bootstrapped(depth,
  405. bootstrap,
  406. reset_fetch_config,
  407. force=True)
  408. self._fetch(self.mirror_path, verbose, depth, no_fetch_tags,
  409. reset_fetch_config)
  410. def update_bootstrap(self, prune=False, gc_aggressive=False, branch='master'):
  411. # The folder is <git number>
  412. gen_number = subprocess.check_output(
  413. [self.git_exe, 'number', branch],
  414. cwd=self.mirror_path).decode('utf-8', 'ignore').strip()
  415. gsutil = Gsutil(path=self.gsutil_exe, boto_path=None)
  416. src_name = self.mirror_path
  417. dest_prefix = '%s/%s' % (self._gs_path, gen_number)
  418. # ls_out lists contents in the format: gs://blah/blah/123...
  419. _, ls_out, _ = gsutil.check_call('ls', self._gs_path)
  420. # Check to see if folder already exists in gs
  421. ls_out_set = set(ls_out.strip().splitlines())
  422. if (dest_prefix + '/' in ls_out_set and
  423. dest_prefix + '.ready' in ls_out_set):
  424. print('Cache %s already exists.' % dest_prefix)
  425. return
  426. # Reduce the number of individual files to download & write on disk.
  427. self.RunGit(['pack-refs', '--all'])
  428. # Run Garbage Collect to compress packfile.
  429. gc_args = ['gc', '--prune=all']
  430. if gc_aggressive:
  431. # The default "gc --aggressive" is often too aggressive for some machines,
  432. # since it attempts to create as many threads as there are CPU cores,
  433. # while not limiting per-thread memory usage, which puts too much pressure
  434. # on RAM on high-core machines, causing them to thrash. Using lower-level
  435. # commands gives more control over those settings.
  436. # This might not be strictly necessary, but it's fast and is normally run
  437. # by 'gc --aggressive', so it shouldn't hurt.
  438. self.RunGit(['reflog', 'expire', '--all'])
  439. # These are the default repack settings for 'gc --aggressive'.
  440. gc_args = ['repack', '-d', '-l', '-f', '--depth=50', '--window=250', '-A',
  441. '--unpack-unreachable=all']
  442. # A 1G memory limit seems to provide comparable pack results as the
  443. # default, even for our largest repos, while preventing runaway memory (at
  444. # least on current Chromium builders which have about 4G RAM per core).
  445. gc_args.append('--window-memory=1g')
  446. # NOTE: It might also be possible to avoid thrashing with a larger window
  447. # (e.g. "--window-memory=2g") by limiting the number of threads created
  448. # (e.g. "--threads=[cores/2]"). Some limited testing didn't show much
  449. # difference in outcomes on our current repos, but it might be worth
  450. # trying if the repos grow much larger and the packs don't seem to be
  451. # getting compressed enough.
  452. self.RunGit(gc_args)
  453. gsutil.call('-m', 'cp', '-r', src_name, dest_prefix)
  454. # Create .ready file and upload
  455. _, ready_file_name = tempfile.mkstemp(suffix='.ready')
  456. try:
  457. gsutil.call('cp', ready_file_name, '%s.ready' % (dest_prefix))
  458. finally:
  459. os.remove(ready_file_name)
  460. # remove all other directory/.ready files in the same gs_path
  461. # except for the directory/.ready file previously created
  462. # which can be used for bootstrapping while the current one is
  463. # being uploaded
  464. if not prune:
  465. return
  466. prev_dest_prefix = self._GetMostRecentCacheDirectory(ls_out_set)
  467. if not prev_dest_prefix:
  468. return
  469. for path in ls_out_set:
  470. if (path == prev_dest_prefix + '/' or
  471. path == prev_dest_prefix + '.ready'):
  472. continue
  473. if path.endswith('.ready'):
  474. gsutil.call('rm', path)
  475. continue
  476. gsutil.call('-m', 'rm', '-r', path)
  477. @staticmethod
  478. def DeleteTmpPackFiles(path):
  479. pack_dir = os.path.join(path, 'objects', 'pack')
  480. if not os.path.isdir(pack_dir):
  481. return
  482. pack_files = [f for f in os.listdir(pack_dir) if
  483. f.startswith('.tmp-') or f.startswith('tmp_pack_')]
  484. for f in pack_files:
  485. f = os.path.join(pack_dir, f)
  486. try:
  487. os.remove(f)
  488. logging.warning('Deleted stale temporary pack file %s' % f)
  489. except OSError:
  490. logging.warning('Unable to delete temporary pack file %s' % f)
  491. @subcommand.usage('[url of repo to check for caching]')
  492. def CMDexists(parser, args):
  493. """Check to see if there already is a cache of the given repo."""
  494. _, args = parser.parse_args(args)
  495. if not len(args) == 1:
  496. parser.error('git cache exists only takes exactly one repo url.')
  497. url = args[0]
  498. mirror = Mirror(url)
  499. if mirror.exists():
  500. print(mirror.mirror_path)
  501. return 0
  502. return 1
  503. @subcommand.usage('[url of repo to create a bootstrap zip file]')
  504. def CMDupdate_bootstrap(parser, args):
  505. """Create and uploads a bootstrap tarball."""
  506. # Lets just assert we can't do this on Windows.
  507. if sys.platform.startswith('win'):
  508. print('Sorry, update bootstrap will not work on Windows.', file=sys.stderr)
  509. return 1
  510. parser.add_option('--skip-populate', action='store_true',
  511. help='Skips "populate" step if mirror already exists.')
  512. parser.add_option('--gc-aggressive', action='store_true',
  513. help='Run aggressive repacking of the repo.')
  514. parser.add_option('--prune', action='store_true',
  515. help='Prune all other cached bundles of the same repo.')
  516. parser.add_option('--branch', default='master',
  517. help='Branch to use for bootstrap. (Default \'master\')')
  518. populate_args = args[:]
  519. options, args = parser.parse_args(args)
  520. url = args[0]
  521. mirror = Mirror(url)
  522. if not options.skip_populate or not mirror.exists():
  523. CMDpopulate(parser, populate_args)
  524. else:
  525. print('Skipped populate step.')
  526. # Get the repo directory.
  527. _, args2 = parser.parse_args(args)
  528. url = args2[0]
  529. mirror = Mirror(url)
  530. mirror.update_bootstrap(options.prune, options.gc_aggressive, options.branch)
  531. return 0
  532. @subcommand.usage('[url of repo to add to or update in cache]')
  533. def CMDpopulate(parser, args):
  534. """Ensure that the cache has all up-to-date objects for the given repo."""
  535. parser.add_option('--depth', type='int',
  536. help='Only cache DEPTH commits of history')
  537. parser.add_option(
  538. '--no-fetch-tags',
  539. action='store_true',
  540. help=('Don\'t fetch tags from the server. This can speed up '
  541. 'fetch considerably when there are many tags.'))
  542. parser.add_option('--shallow', '-s', action='store_true',
  543. help='Only cache 10000 commits of history')
  544. parser.add_option('--ref', action='append',
  545. help='Specify additional refs to be fetched')
  546. parser.add_option('--no_bootstrap', '--no-bootstrap',
  547. action='store_true',
  548. help='Don\'t bootstrap from Google Storage')
  549. parser.add_option('--ignore_locks',
  550. '--ignore-locks',
  551. action='store_true',
  552. help='NOOP. This flag will be removed in the future.')
  553. parser.add_option('--break-locks',
  554. action='store_true',
  555. help='Break any existing lock instead of just ignoring it')
  556. parser.add_option('--reset-fetch-config', action='store_true', default=False,
  557. help='Reset the fetch config before populating the cache.')
  558. options, args = parser.parse_args(args)
  559. if not len(args) == 1:
  560. parser.error('git cache populate only takes exactly one repo url.')
  561. if options.ignore_locks:
  562. print('ignore_locks is no longer used. Please remove its usage.')
  563. if options.break_locks:
  564. print('break_locks is no longer used. Please remove its usage.')
  565. url = args[0]
  566. mirror = Mirror(url, refs=options.ref)
  567. kwargs = {
  568. 'no_fetch_tags': options.no_fetch_tags,
  569. 'verbose': options.verbose,
  570. 'shallow': options.shallow,
  571. 'bootstrap': not options.no_bootstrap,
  572. 'lock_timeout': options.timeout,
  573. 'reset_fetch_config': options.reset_fetch_config,
  574. }
  575. if options.depth:
  576. kwargs['depth'] = options.depth
  577. mirror.populate(**kwargs)
  578. @subcommand.usage('Fetch new commits into cache and current checkout')
  579. def CMDfetch(parser, args):
  580. """Update mirror, and fetch in cwd."""
  581. parser.add_option('--all', action='store_true', help='Fetch all remotes')
  582. parser.add_option('--no_bootstrap', '--no-bootstrap',
  583. action='store_true',
  584. help='Don\'t (re)bootstrap from Google Storage')
  585. parser.add_option(
  586. '--no-fetch-tags',
  587. action='store_true',
  588. help=('Don\'t fetch tags from the server. This can speed up '
  589. 'fetch considerably when there are many tags.'))
  590. options, args = parser.parse_args(args)
  591. # Figure out which remotes to fetch. This mimics the behavior of regular
  592. # 'git fetch'. Note that in the case of "stacked" or "pipelined" branches,
  593. # this will NOT try to traverse up the branching structure to find the
  594. # ultimate remote to update.
  595. remotes = []
  596. if options.all:
  597. assert not args, 'fatal: fetch --all does not take a repository argument'
  598. remotes = subprocess.check_output([Mirror.git_exe, 'remote'])
  599. remotes = remotes.decode('utf-8', 'ignore').splitlines()
  600. elif args:
  601. remotes = args
  602. else:
  603. current_branch = subprocess.check_output(
  604. [Mirror.git_exe, 'rev-parse', '--abbrev-ref', 'HEAD'])
  605. current_branch = current_branch.decode('utf-8', 'ignore').strip()
  606. if current_branch != 'HEAD':
  607. upstream = subprocess.check_output(
  608. [Mirror.git_exe, 'config', 'branch.%s.remote' % current_branch])
  609. upstream = upstream.decode('utf-8', 'ignore').strip()
  610. if upstream and upstream != '.':
  611. remotes = [upstream]
  612. if not remotes:
  613. remotes = ['origin']
  614. cachepath = Mirror.GetCachePath()
  615. git_dir = os.path.abspath(subprocess.check_output(
  616. [Mirror.git_exe, 'rev-parse', '--git-dir']).decode('utf-8', 'ignore'))
  617. git_dir = os.path.abspath(git_dir)
  618. if git_dir.startswith(cachepath):
  619. mirror = Mirror.FromPath(git_dir)
  620. mirror.populate(
  621. bootstrap=not options.no_bootstrap,
  622. no_fetch_tags=options.no_fetch_tags,
  623. lock_timeout=options.timeout)
  624. return 0
  625. for remote in remotes:
  626. remote_url = subprocess.check_output(
  627. [Mirror.git_exe, 'config', 'remote.%s.url' % remote])
  628. remote_url = remote_url.decode('utf-8', 'ignore').strip()
  629. if remote_url.startswith(cachepath):
  630. mirror = Mirror.FromPath(remote_url)
  631. mirror.print = lambda *args: None
  632. print('Updating git cache...')
  633. mirror.populate(
  634. bootstrap=not options.no_bootstrap,
  635. no_fetch_tags=options.no_fetch_tags,
  636. lock_timeout=options.timeout)
  637. subprocess.check_call([Mirror.git_exe, 'fetch', remote])
  638. return 0
  639. @subcommand.usage('do not use - it is a noop.')
  640. def CMDunlock(parser, args):
  641. """This command does nothing."""
  642. print('This command does nothing and will be removed in the future.')
  643. class OptionParser(optparse.OptionParser):
  644. """Wrapper class for OptionParser to handle global options."""
  645. def __init__(self, *args, **kwargs):
  646. optparse.OptionParser.__init__(self, *args, prog='git cache', **kwargs)
  647. self.add_option('-c', '--cache-dir',
  648. help=(
  649. 'Path to the directory containing the caches. Normally '
  650. 'deduced from git config cache.cachepath or '
  651. '$GIT_CACHE_PATH.'))
  652. self.add_option('-v', '--verbose', action='count', default=1,
  653. help='Increase verbosity (can be passed multiple times)')
  654. self.add_option('-q', '--quiet', action='store_true',
  655. help='Suppress all extraneous output')
  656. self.add_option('--timeout', type='int', default=0,
  657. help='Timeout for acquiring cache lock, in seconds')
  658. def parse_args(self, args=None, values=None):
  659. options, args = optparse.OptionParser.parse_args(self, args, values)
  660. if options.quiet:
  661. options.verbose = 0
  662. levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
  663. logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)])
  664. try:
  665. global_cache_dir = Mirror.GetCachePath()
  666. except RuntimeError:
  667. global_cache_dir = None
  668. if options.cache_dir:
  669. if global_cache_dir and (
  670. os.path.abspath(options.cache_dir) !=
  671. os.path.abspath(global_cache_dir)):
  672. logging.warning('Overriding globally-configured cache directory.')
  673. Mirror.SetCachePath(options.cache_dir)
  674. return options, args
  675. def main(argv):
  676. dispatcher = subcommand.CommandDispatcher(__name__)
  677. return dispatcher.execute(OptionParser(), argv)
  678. if __name__ == '__main__':
  679. try:
  680. sys.exit(main(sys.argv[1:]))
  681. except KeyboardInterrupt:
  682. sys.stderr.write('interrupted\n')
  683. sys.exit(1)