blob: 89f7f6d79162a725a06165b30ecde8800c062f4d [file] [log] [blame]
Edward Lesmes98eda3f2019-08-12 21:09:53 +00001#!/usr/bin/env python
agable@chromium.org5a306a22014-02-24 22:13:59 +00002# 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
6"""A git command for managing a local cache of git repositories."""
7
szager@chromium.org848fd492014-04-09 19:06:44 +00008from __future__ import print_function
Raul Tambreb946b232019-03-26 14:48:46 +00009
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -080010import contextlib
agable@chromium.org5a306a22014-02-24 22:13:59 +000011import errno
12import logging
13import optparse
14import os
szager@chromium.org174766f2014-05-13 21:27:46 +000015import re
John Budorick47ec0692019-05-01 15:04:28 +000016import subprocess
17import sys
agable@chromium.org5a306a22014-02-24 22:13:59 +000018import tempfile
szager@chromium.org1132f5f2014-08-23 01:57:59 +000019import threading
pgervais@chromium.orgf3726102014-04-17 17:24:15 +000020import time
Raul Tambreb946b232019-03-26 14:48:46 +000021
22try:
23 import urlparse
24except ImportError: # For Py3 compatibility
25 import urllib.parse as urlparse
26
hinoka@google.com563559c2014-04-02 00:36:24 +000027from download_from_google_storage import Gsutil
agable@chromium.org5a306a22014-02-24 22:13:59 +000028import gclient_utils
Josip Sokcevic14a83ae2020-05-21 01:36:34 +000029import lockfile
agable@chromium.org5a306a22014-02-24 22:13:59 +000030import subcommand
31
szager@chromium.org301a7c32014-06-16 17:13:50 +000032# Analogous to gc.autopacklimit git config.
33GC_AUTOPACKLIMIT = 50
Takuto Ikuta9fce2132017-12-14 10:44:28 +090034
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +000035GIT_CACHE_CORRUPT_MESSAGE = 'WARNING: The Git cache is corrupt.'
36
szager@chromium.org848fd492014-04-09 19:06:44 +000037try:
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -080038 # pylint: disable=undefined-variable
szager@chromium.org848fd492014-04-09 19:06:44 +000039 WinErr = WindowsError
40except NameError:
41 class WinErr(Exception):
42 pass
agable@chromium.org5a306a22014-02-24 22:13:59 +000043
hinokadcd84042016-06-09 14:26:17 -070044class ClobberNeeded(Exception):
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +000045 pass
agable@chromium.org5a306a22014-02-24 22:13:59 +000046
dnj4625b5a2016-11-10 18:23:26 -080047
48def exponential_backoff_retry(fn, excs=(Exception,), name=None, count=10,
49 sleep_time=0.25, printerr=None):
50 """Executes |fn| up to |count| times, backing off exponentially.
51
52 Args:
53 fn (callable): The function to execute. If this raises a handled
54 exception, the function will retry with exponential backoff.
55 excs (tuple): A tuple of Exception types to handle. If one of these is
56 raised by |fn|, a retry will be attempted. If |fn| raises an Exception
57 that is not in this list, it will immediately pass through. If |excs|
58 is empty, the Exception base class will be used.
59 name (str): Optional operation name to print in the retry string.
60 count (int): The number of times to try before allowing the exception to
61 pass through.
62 sleep_time (float): The initial number of seconds to sleep in between
63 retries. This will be doubled each retry.
64 printerr (callable): Function that will be called with the error string upon
65 failures. If None, |logging.warning| will be used.
66
67 Returns: The return value of the successful fn.
68 """
69 printerr = printerr or logging.warning
Edward Lesmes451e8ba2019-10-01 22:15:33 +000070 for i in range(count):
dnj4625b5a2016-11-10 18:23:26 -080071 try:
72 return fn()
73 except excs as e:
74 if (i+1) >= count:
75 raise
76
77 printerr('Retrying %s in %.2f second(s) (%d / %d attempts): %s' % (
78 (name or 'operation'), sleep_time, (i+1), count, e))
79 time.sleep(sleep_time)
80 sleep_time *= 2
81
82
szager@chromium.org848fd492014-04-09 19:06:44 +000083class Mirror(object):
84
85 git_exe = 'git.bat' if sys.platform.startswith('win') else 'git'
86 gsutil_exe = os.path.join(
hinoka@chromium.orgb091aa52014-12-20 01:47:31 +000087 os.path.dirname(os.path.abspath(__file__)), 'gsutil.py')
Vadim Shtayura08049e22017-10-11 00:14:52 +000088 cachepath_lock = threading.Lock()
szager@chromium.org848fd492014-04-09 19:06:44 +000089
Robert Iannuccia19649b2018-06-29 16:31:45 +000090 UNSET_CACHEPATH = object()
91
92 # Used for tests
93 _GIT_CONFIG_LOCATION = []
94
szager@chromium.org66c8b852015-09-22 23:19:07 +000095 @staticmethod
96 def parse_fetch_spec(spec):
97 """Parses and canonicalizes a fetch spec.
98
99 Returns (fetchspec, value_regex), where value_regex can be used
100 with 'git config --replace-all'.
101 """
102 parts = spec.split(':', 1)
103 src = parts[0].lstrip('+').rstrip('/')
104 if not src.startswith('refs/'):
105 src = 'refs/heads/%s' % src
106 dest = parts[1].rstrip('/') if len(parts) > 1 else src
107 regex = r'\+%s:.*' % src.replace('*', r'\*')
108 return ('+%s:%s' % (src, dest), regex)
109
Edward Lesmes93d80d82021-04-20 02:55:11 +0000110 def __init__(self, url, refs=None, print_func=None):
szager@chromium.org848fd492014-04-09 19:06:44 +0000111 self.url = url
szager@chromium.org66c8b852015-09-22 23:19:07 +0000112 self.fetch_specs = set([self.parse_fetch_spec(ref) for ref in (refs or [])])
szager@chromium.org848fd492014-04-09 19:06:44 +0000113 self.basedir = self.UrlToCacheDir(url)
114 self.mirror_path = os.path.join(self.GetCachePath(), self.basedir)
loislo@chromium.org0fb693f2014-12-25 15:28:22 +0000115 if print_func:
116 self.print = self.print_without_file
117 self.print_func = print_func
118 else:
119 self.print = print
120
dnj4625b5a2016-11-10 18:23:26 -0800121 def print_without_file(self, message, **_kwargs):
loislo@chromium.org0fb693f2014-12-25 15:28:22 +0000122 self.print_func(message)
szager@chromium.org848fd492014-04-09 19:06:44 +0000123
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800124 @contextlib.contextmanager
125 def print_duration_of(self, what):
126 start = time.time()
127 try:
128 yield
129 finally:
130 self.print('%s took %.1f minutes' % (what, (time.time() - start) / 60.0))
131
hinoka@chromium.orgf8fa23d2014-06-05 01:00:04 +0000132 @property
133 def bootstrap_bucket(self):
Andrii Shyshkalov4b79c382019-04-15 23:48:35 +0000134 b = os.getenv('OVERRIDE_BOOTSTRAP_BUCKET')
135 if b:
136 return b
Ryan Tseng3beabd02017-03-15 13:57:58 -0700137 u = urlparse.urlparse(self.url)
138 if u.netloc == 'chromium.googlesource.com':
hinoka@chromium.orgf8fa23d2014-06-05 01:00:04 +0000139 return 'chromium-git-cache'
Ryan Tseng3beabd02017-03-15 13:57:58 -0700140 # Not recognized.
141 return None
hinoka@chromium.orgf8fa23d2014-06-05 01:00:04 +0000142
Karen Qiandcad7492019-04-26 03:11:16 +0000143 @property
144 def _gs_path(self):
145 return 'gs://%s/v2/%s' % (self.bootstrap_bucket, self.basedir)
146
szager@chromium.org174766f2014-05-13 21:27:46 +0000147 @classmethod
148 def FromPath(cls, path):
149 return cls(cls.CacheDirToUrl(path))
150
szager@chromium.org848fd492014-04-09 19:06:44 +0000151 @staticmethod
152 def UrlToCacheDir(url):
153 """Convert a git url to a normalized form for the cache dir path."""
Edward Lemure9024d02019-11-19 18:47:46 +0000154 if os.path.isdir(url):
155 # Ignore the drive letter in Windows
156 url = os.path.splitdrive(url)[1]
157 return url.replace('-', '--').replace(os.sep, '-')
158
szager@chromium.org848fd492014-04-09 19:06:44 +0000159 parsed = urlparse.urlparse(url)
Edward Lemure9024d02019-11-19 18:47:46 +0000160 norm_url = parsed.netloc + parsed.path
szager@chromium.org848fd492014-04-09 19:06:44 +0000161 if norm_url.endswith('.git'):
162 norm_url = norm_url[:-len('.git')]
Dirk Prankedb589542019-04-12 21:07:01 +0000163
164 # Use the same dir for authenticated URLs and unauthenticated URLs.
165 norm_url = norm_url.replace('googlesource.com/a/', 'googlesource.com/')
166
szager@chromium.org848fd492014-04-09 19:06:44 +0000167 return norm_url.replace('-', '--').replace('/', '-').lower()
168
169 @staticmethod
szager@chromium.org174766f2014-05-13 21:27:46 +0000170 def CacheDirToUrl(path):
171 """Convert a cache dir path to its corresponding url."""
172 netpath = re.sub(r'\b-\b', '/', os.path.basename(path)).replace('--', '-')
173 return 'https://%s' % netpath
174
szager@chromium.org848fd492014-04-09 19:06:44 +0000175 @classmethod
176 def SetCachePath(cls, cachepath):
Vadim Shtayura08049e22017-10-11 00:14:52 +0000177 with cls.cachepath_lock:
178 setattr(cls, 'cachepath', cachepath)
szager@chromium.org848fd492014-04-09 19:06:44 +0000179
180 @classmethod
181 def GetCachePath(cls):
Vadim Shtayura08049e22017-10-11 00:14:52 +0000182 with cls.cachepath_lock:
183 if not hasattr(cls, 'cachepath'):
184 try:
185 cachepath = subprocess.check_output(
Robert Iannuccia19649b2018-06-29 16:31:45 +0000186 [cls.git_exe, 'config'] +
187 cls._GIT_CONFIG_LOCATION +
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000188 ['cache.cachepath']).decode('utf-8', 'ignore').strip()
Vadim Shtayura08049e22017-10-11 00:14:52 +0000189 except subprocess.CalledProcessError:
Robert Iannuccia19649b2018-06-29 16:31:45 +0000190 cachepath = os.environ.get('GIT_CACHE_PATH', cls.UNSET_CACHEPATH)
Vadim Shtayura08049e22017-10-11 00:14:52 +0000191 setattr(cls, 'cachepath', cachepath)
Robert Iannuccia19649b2018-06-29 16:31:45 +0000192
193 ret = getattr(cls, 'cachepath')
194 if ret is cls.UNSET_CACHEPATH:
195 raise RuntimeError('No cache.cachepath git configuration or '
196 '$GIT_CACHE_PATH is set.')
197 return ret
szager@chromium.org848fd492014-04-09 19:06:44 +0000198
Karen Qianccd2b4d2019-05-03 22:25:59 +0000199 @staticmethod
200 def _GetMostRecentCacheDirectory(ls_out_set):
201 ready_file_pattern = re.compile(r'.*/(\d+).ready$')
202 ready_dirs = []
203
204 for name in ls_out_set:
205 m = ready_file_pattern.match(name)
206 # Given <path>/<number>.ready,
207 # we are interested in <path>/<number> directory
208 if m and (name[:-len('.ready')] + '/') in ls_out_set:
209 ready_dirs.append((int(m.group(1)), name[:-len('.ready')]))
210
211 if not ready_dirs:
212 return None
213
214 return max(ready_dirs)[1]
215
dnj4625b5a2016-11-10 18:23:26 -0800216 def Rename(self, src, dst):
217 # This is somehow racy on Windows.
218 # Catching OSError because WindowsError isn't portable and
219 # pylint complains.
220 exponential_backoff_retry(
221 lambda: os.rename(src, dst),
222 excs=(OSError,),
223 name='rename [%s] => [%s]' % (src, dst),
224 printerr=self.print)
225
szager@chromium.org848fd492014-04-09 19:06:44 +0000226 def RunGit(self, cmd, **kwargs):
227 """Run git in a subprocess."""
228 cwd = kwargs.setdefault('cwd', self.mirror_path)
229 kwargs.setdefault('print_stdout', False)
230 kwargs.setdefault('filter_fn', self.print)
231 env = kwargs.get('env') or kwargs.setdefault('env', os.environ.copy())
232 env.setdefault('GIT_ASKPASS', 'true')
233 env.setdefault('SSH_ASKPASS', 'true')
234 self.print('running "git %s" in "%s"' % (' '.join(cmd), cwd))
235 gclient_utils.CheckCallAndFilter([self.git_exe] + cmd, **kwargs)
236
Edward Lemur579c9862018-07-13 23:17:51 +0000237 def config(self, cwd=None, reset_fetch_config=False):
szager@chromium.org848fd492014-04-09 19:06:44 +0000238 if cwd is None:
239 cwd = self.mirror_path
szager@chromium.org301a7c32014-06-16 17:13:50 +0000240
Edward Lemur579c9862018-07-13 23:17:51 +0000241 if reset_fetch_config:
Edward Lemur2f38df62018-07-14 02:13:21 +0000242 try:
243 self.RunGit(['config', '--unset-all', 'remote.origin.fetch'], cwd=cwd)
244 except subprocess.CalledProcessError as e:
245 # If exit code was 5, it means we attempted to unset a config that
246 # didn't exist. Ignore it.
247 if e.returncode != 5:
248 raise
Edward Lemur579c9862018-07-13 23:17:51 +0000249
szager@chromium.org301a7c32014-06-16 17:13:50 +0000250 # Don't run git-gc in a daemon. Bad things can happen if it gets killed.
hinokadcd84042016-06-09 14:26:17 -0700251 try:
252 self.RunGit(['config', 'gc.autodetach', '0'], cwd=cwd)
253 except subprocess.CalledProcessError:
254 # Hard error, need to clobber.
255 raise ClobberNeeded()
szager@chromium.org301a7c32014-06-16 17:13:50 +0000256
257 # Don't combine pack files into one big pack file. It's really slow for
258 # repositories, and there's no way to track progress and make sure it's
259 # not stuck.
Ryan Tseng3beabd02017-03-15 13:57:58 -0700260 if self.supported_project():
261 self.RunGit(['config', 'gc.autopacklimit', '0'], cwd=cwd)
szager@chromium.org301a7c32014-06-16 17:13:50 +0000262
263 # Allocate more RAM for cache-ing delta chains, for better performance
264 # of "Resolving deltas".
szager@chromium.org848fd492014-04-09 19:06:44 +0000265 self.RunGit(['config', 'core.deltaBaseCacheLimit',
hinoka@chromium.org8e095af2015-06-10 19:19:07 +0000266 gclient_utils.DefaultDeltaBaseCacheLimit()], cwd=cwd)
szager@chromium.org301a7c32014-06-16 17:13:50 +0000267
hinoka@chromium.org8e095af2015-06-10 19:19:07 +0000268 self.RunGit(['config', 'remote.origin.url', self.url], cwd=cwd)
szager@chromium.org848fd492014-04-09 19:06:44 +0000269 self.RunGit(['config', '--replace-all', 'remote.origin.fetch',
hinoka@chromium.org8e095af2015-06-10 19:19:07 +0000270 '+refs/heads/*:refs/heads/*', r'\+refs/heads/\*:.*'], cwd=cwd)
szager@chromium.org66c8b852015-09-22 23:19:07 +0000271 for spec, value_regex in self.fetch_specs:
szager@chromium.org965c44f2014-08-19 21:19:19 +0000272 self.RunGit(
szager@chromium.org66c8b852015-09-22 23:19:07 +0000273 ['config', '--replace-all', 'remote.origin.fetch', spec, value_regex],
hinoka@chromium.org8e095af2015-06-10 19:19:07 +0000274 cwd=cwd)
szager@chromium.org848fd492014-04-09 19:06:44 +0000275
276 def bootstrap_repo(self, directory):
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800277 """Bootstrap the repo from Google Storage if possible.
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000278
279 More apt-ly named bootstrap_repo_from_cloud_if_possible_else_do_nothing().
280 """
Ryan Tseng3beabd02017-03-15 13:57:58 -0700281 if not self.bootstrap_bucket:
282 return False
szager@chromium.org848fd492014-04-09 19:06:44 +0000283
hinoka@chromium.org199bc5f2014-12-17 02:17:14 +0000284 gsutil = Gsutil(self.gsutil_exe, boto_path=None)
Yuwei Huanga1fbdff2019-02-01 21:51:15 +0000285
Karen Qian0cbd5a52019-04-29 20:14:50 +0000286 # Get the most recent version of the directory.
287 # This is determined from the most recent version of a .ready file.
288 # The .ready file is only uploaded when an entire directory has been
289 # uploaded to GS.
290 _, ls_out, ls_err = gsutil.check_call('ls', self._gs_path)
Karen Qianccd2b4d2019-05-03 22:25:59 +0000291 ls_out_set = set(ls_out.strip().splitlines())
292 latest_dir = self._GetMostRecentCacheDirectory(ls_out_set)
Yuwei Huanga1fbdff2019-02-01 21:51:15 +0000293
Karen Qianccd2b4d2019-05-03 22:25:59 +0000294 if not latest_dir:
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800295 self.print('No bootstrap file for %s found in %s, stderr:\n %s' %
296 (self.mirror_path, self.bootstrap_bucket,
Karen Qian0cbd5a52019-04-29 20:14:50 +0000297 ' '.join((ls_err or '').splitlines(True))))
szager@chromium.org848fd492014-04-09 19:06:44 +0000298 return False
szager@chromium.org848fd492014-04-09 19:06:44 +0000299
szager@chromium.org848fd492014-04-09 19:06:44 +0000300 try:
Karen Qian0cbd5a52019-04-29 20:14:50 +0000301 # create new temporary directory locally
szager@chromium.org1cbf1042014-06-17 18:26:24 +0000302 tempdir = tempfile.mkdtemp(prefix='_cache_tmp', dir=self.GetCachePath())
Karen Qian0cbd5a52019-04-29 20:14:50 +0000303 self.RunGit(['init', '--bare'], cwd=tempdir)
304 self.print('Downloading files in %s/* into %s.' %
305 (latest_dir, tempdir))
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800306 with self.print_duration_of('download'):
Karen Qian0cbd5a52019-04-29 20:14:50 +0000307 code = gsutil.call('-m', 'cp', '-r', latest_dir + "/*",
308 tempdir)
szager@chromium.org848fd492014-04-09 19:06:44 +0000309 if code:
szager@chromium.org848fd492014-04-09 19:06:44 +0000310 return False
Josip Sokcevic67e12282020-12-16 17:12:45 +0000311 # A quick validation that all references are valid.
312 self.RunGit(['for-each-ref'], cwd=tempdir)
Karen Qian0cbd5a52019-04-29 20:14:50 +0000313 except Exception as e:
314 self.print('Encountered error: %s' % str(e), file=sys.stderr)
315 gclient_utils.rmtree(tempdir)
szager@chromium.org848fd492014-04-09 19:06:44 +0000316 return False
Karen Qian0cbd5a52019-04-29 20:14:50 +0000317 # delete the old directory
318 if os.path.exists(directory):
319 gclient_utils.rmtree(directory)
320 self.Rename(tempdir, directory)
szager@chromium.org848fd492014-04-09 19:06:44 +0000321 return True
322
Andrii Shyshkalov46a672b2017-11-24 18:04:43 -0800323 def contains_revision(self, revision):
324 if not self.exists():
325 return False
326
327 if sys.platform.startswith('win'):
328 # Windows .bat scripts use ^ as escape sequence, which means we have to
329 # escape it with itself for every .bat invocation.
330 needle = '%s^^^^{commit}' % revision
331 else:
332 needle = '%s^{commit}' % revision
333 try:
334 # cat-file exits with 0 on success, that is git object of given hash was
335 # found.
336 self.RunGit(['cat-file', '-e', needle])
337 return True
338 except subprocess.CalledProcessError:
339 return False
340
szager@chromium.org848fd492014-04-09 19:06:44 +0000341 def exists(self):
342 return os.path.isfile(os.path.join(self.mirror_path, 'config'))
343
Ryan Tseng3beabd02017-03-15 13:57:58 -0700344 def supported_project(self):
345 """Returns true if this repo is known to have a bootstrap zip file."""
346 u = urlparse.urlparse(self.url)
347 return u.netloc in [
348 'chromium.googlesource.com',
349 'chrome-internal.googlesource.com']
350
szager@chromium.org66c8b852015-09-22 23:19:07 +0000351 def _preserve_fetchspec(self):
352 """Read and preserve remote.origin.fetch from an existing mirror.
353
354 This modifies self.fetch_specs.
355 """
356 if not self.exists():
357 return
358 try:
359 config_fetchspecs = subprocess.check_output(
360 [self.git_exe, 'config', '--get-all', 'remote.origin.fetch'],
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000361 cwd=self.mirror_path).decode('utf-8', 'ignore')
szager@chromium.org66c8b852015-09-22 23:19:07 +0000362 for fetchspec in config_fetchspecs.splitlines():
363 self.fetch_specs.add(self.parse_fetch_spec(fetchspec))
364 except subprocess.CalledProcessError:
Gavin Make6a62332020-12-04 21:57:10 +0000365 logging.warning(
366 'Tried and failed to preserve remote.origin.fetch from the '
367 'existing cache directory. You may need to manually edit '
368 '%s and "git cache fetch" again.' %
369 os.path.join(self.mirror_path, 'config'))
szager@chromium.org66c8b852015-09-22 23:19:07 +0000370
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000371 def _ensure_bootstrapped(
372 self, depth, bootstrap, reset_fetch_config, force=False):
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000373 pack_dir = os.path.join(self.mirror_path, 'objects', 'pack')
374 pack_files = []
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000375 if os.path.isdir(pack_dir):
376 pack_files = [f for f in os.listdir(pack_dir) if f.endswith('.pack')]
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000377 self.print('%s has %d .pack files, re-bootstrapping if >%d or ==0' %
Karen Qian0cbd5a52019-04-29 20:14:50 +0000378 (self.mirror_path, len(pack_files), GC_AUTOPACKLIMIT))
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000379
380 should_bootstrap = (force or
szager@chromium.org66c8b852015-09-22 23:19:07 +0000381 not self.exists() or
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000382 len(pack_files) > GC_AUTOPACKLIMIT or
383 len(pack_files) == 0)
Karen Qian0cbd5a52019-04-29 20:14:50 +0000384
385 if not should_bootstrap:
386 if depth and os.path.exists(os.path.join(self.mirror_path, 'shallow')):
Gavin Make6a62332020-12-04 21:57:10 +0000387 logging.warning(
Karen Qian0cbd5a52019-04-29 20:14:50 +0000388 'Shallow fetch requested, but repo cache already exists.')
389 return
390
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000391 if not self.exists():
John Budorick47ec0692019-05-01 15:04:28 +0000392 if os.path.exists(self.mirror_path):
393 # If the mirror path exists but self.exists() returns false, we're
394 # in an unexpected state. Nuke the previous mirror directory and
395 # start fresh.
396 gclient_utils.rmtree(self.mirror_path)
Karen Qian0cbd5a52019-04-29 20:14:50 +0000397 os.mkdir(self.mirror_path)
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000398 elif not reset_fetch_config:
399 # Re-bootstrapping an existing mirror; preserve existing fetch spec.
400 self._preserve_fetchspec()
Karen Qian0cbd5a52019-04-29 20:14:50 +0000401
402 bootstrapped = (not depth and bootstrap and
403 self.bootstrap_repo(self.mirror_path))
404
405 if not bootstrapped:
406 if not self.exists() or not self.supported_project():
407 # Bootstrap failed due to:
408 # 1. No previous cache.
409 # 2. Project doesn't have a bootstrap folder.
Ryan Tseng3beabd02017-03-15 13:57:58 -0700410 # Start with a bare git dir.
Karen Qian0cbd5a52019-04-29 20:14:50 +0000411 self.RunGit(['init', '--bare'], cwd=self.mirror_path)
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000412 else:
413 # Bootstrap failed, previous cache exists; warn and continue.
Gavin Make6a62332020-12-04 21:57:10 +0000414 logging.warning(
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800415 'Git cache has a lot of pack files (%d). Tried to re-bootstrap '
Gavin Make6a62332020-12-04 21:57:10 +0000416 'but failed. Continuing with non-optimized repository.' %
417 len(pack_files))
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000418
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000419 def _fetch(self,
420 rundir,
421 verbose,
422 depth,
423 no_fetch_tags,
424 reset_fetch_config,
425 prune=True):
Edward Lemur579c9862018-07-13 23:17:51 +0000426 self.config(rundir, reset_fetch_config)
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000427
428 fetch_cmd = ['fetch']
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000429 if verbose:
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000430 fetch_cmd.extend(['-v', '--progress'])
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000431 if depth:
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000432 fetch_cmd.extend(['--depth', str(depth)])
danakjc41f72c2019-11-05 17:12:01 +0000433 if no_fetch_tags:
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000434 fetch_cmd.append('--no-tags')
435 if prune:
436 fetch_cmd.append('--prune')
437 fetch_cmd.append('origin')
438
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000439 fetch_specs = subprocess.check_output(
440 [self.git_exe, 'config', '--get-all', 'remote.origin.fetch'],
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000441 cwd=rundir).decode('utf-8', 'ignore').strip().splitlines()
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000442 for spec in fetch_specs:
443 try:
444 self.print('Fetching %s' % spec)
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800445 with self.print_duration_of('fetch %s' % spec):
John Budorick3da78c42019-11-14 20:06:30 +0000446 self.RunGit(fetch_cmd + [spec], cwd=rundir, retry=True)
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000447 except subprocess.CalledProcessError:
448 if spec == '+refs/heads/*:refs/heads/*':
hinokadcd84042016-06-09 14:26:17 -0700449 raise ClobberNeeded() # Corrupted cache.
Gavin Make6a62332020-12-04 21:57:10 +0000450 logging.warning('Fetch of %s failed' % spec)
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000451
danakjc41f72c2019-11-05 17:12:01 +0000452 def populate(self,
453 depth=None,
454 no_fetch_tags=False,
455 shallow=False,
456 bootstrap=False,
457 verbose=False,
danakjc41f72c2019-11-05 17:12:01 +0000458 lock_timeout=0,
Edward Lemur579c9862018-07-13 23:17:51 +0000459 reset_fetch_config=False):
szager@chromium.orgb0a13a22014-06-18 00:52:25 +0000460 assert self.GetCachePath()
szager@chromium.org848fd492014-04-09 19:06:44 +0000461 if shallow and not depth:
462 depth = 10000
463 gclient_utils.safe_makedirs(self.GetCachePath())
464
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000465 with lockfile.lock(self.mirror_path, lock_timeout):
466 try:
467 self._ensure_bootstrapped(depth, bootstrap, reset_fetch_config)
468 self._fetch(self.mirror_path, verbose, depth, no_fetch_tags,
469 reset_fetch_config)
470 except ClobberNeeded:
471 # This is a major failure, we need to clean and force a bootstrap.
472 gclient_utils.rmtree(self.mirror_path)
473 self.print(GIT_CACHE_CORRUPT_MESSAGE)
474 self._ensure_bootstrapped(depth,
475 bootstrap,
476 reset_fetch_config,
477 force=True)
478 self._fetch(self.mirror_path, verbose, depth, no_fetch_tags,
479 reset_fetch_config)
szager@chromium.org848fd492014-04-09 19:06:44 +0000480
Anthony Polito90b4c0f2020-11-17 18:09:21 +0000481 def update_bootstrap(self, prune=False, gc_aggressive=False, branch='master'):
Karen Qiandcad7492019-04-26 03:11:16 +0000482 # The folder is <git number>
szager@chromium.org848fd492014-04-09 19:06:44 +0000483 gen_number = subprocess.check_output(
Anthony Polito90b4c0f2020-11-17 18:09:21 +0000484 [self.git_exe, 'number', branch],
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000485 cwd=self.mirror_path).decode('utf-8', 'ignore').strip()
Karen Qiandcad7492019-04-26 03:11:16 +0000486 gsutil = Gsutil(path=self.gsutil_exe, boto_path=None)
487
488 src_name = self.mirror_path
Karen Qianccd2b4d2019-05-03 22:25:59 +0000489 dest_prefix = '%s/%s' % (self._gs_path, gen_number)
Karen Qiandcad7492019-04-26 03:11:16 +0000490
Karen Qianccd2b4d2019-05-03 22:25:59 +0000491 # ls_out lists contents in the format: gs://blah/blah/123...
492 _, ls_out, _ = gsutil.check_call('ls', self._gs_path)
Karen Qiandcad7492019-04-26 03:11:16 +0000493
Karen Qianccd2b4d2019-05-03 22:25:59 +0000494 # Check to see if folder already exists in gs
495 ls_out_set = set(ls_out.strip().splitlines())
496 if (dest_prefix + '/' in ls_out_set and
497 dest_prefix + '.ready' in ls_out_set):
498 print('Cache %s already exists.' % dest_prefix)
Karen Qiandcad7492019-04-26 03:11:16 +0000499 return
500
Andrii Shyshkalov46b91c02020-10-27 17:25:47 +0000501 # Reduce the number of individual files to download & write on disk.
502 self.RunGit(['pack-refs', '--all'])
503
Andrii Shyshkalov199182f2019-04-26 16:01:20 +0000504 # Run Garbage Collect to compress packfile.
Andrii Shyshkalovdcfe55f2019-09-21 03:35:39 +0000505 gc_args = ['gc', '--prune=all']
506 if gc_aggressive:
Michael Moss77480942020-06-22 18:32:37 +0000507 # The default "gc --aggressive" is often too aggressive for some machines,
508 # since it attempts to create as many threads as there are CPU cores,
509 # while not limiting per-thread memory usage, which puts too much pressure
510 # on RAM on high-core machines, causing them to thrash. Using lower-level
511 # commands gives more control over those settings.
512
513 # This might not be strictly necessary, but it's fast and is normally run
514 # by 'gc --aggressive', so it shouldn't hurt.
515 self.RunGit(['reflog', 'expire', '--all'])
516
517 # These are the default repack settings for 'gc --aggressive'.
518 gc_args = ['repack', '-d', '-l', '-f', '--depth=50', '--window=250', '-A',
519 '--unpack-unreachable=all']
520 # A 1G memory limit seems to provide comparable pack results as the
521 # default, even for our largest repos, while preventing runaway memory (at
522 # least on current Chromium builders which have about 4G RAM per core).
523 gc_args.append('--window-memory=1g')
524 # NOTE: It might also be possible to avoid thrashing with a larger window
525 # (e.g. "--window-memory=2g") by limiting the number of threads created
526 # (e.g. "--threads=[cores/2]"). Some limited testing didn't show much
527 # difference in outcomes on our current repos, but it might be worth
528 # trying if the repos grow much larger and the packs don't seem to be
529 # getting compressed enough.
Andrii Shyshkalovdcfe55f2019-09-21 03:35:39 +0000530 self.RunGit(gc_args)
Andrii Shyshkalov199182f2019-04-26 16:01:20 +0000531
Karen Qianccd2b4d2019-05-03 22:25:59 +0000532 gsutil.call('-m', 'cp', '-r', src_name, dest_prefix)
Karen Qiandcad7492019-04-26 03:11:16 +0000533
Karen Qianccd2b4d2019-05-03 22:25:59 +0000534 # Create .ready file and upload
Karen Qiandcad7492019-04-26 03:11:16 +0000535 _, ready_file_name = tempfile.mkstemp(suffix='.ready')
536 try:
Karen Qianccd2b4d2019-05-03 22:25:59 +0000537 gsutil.call('cp', ready_file_name, '%s.ready' % (dest_prefix))
Karen Qiandcad7492019-04-26 03:11:16 +0000538 finally:
539 os.remove(ready_file_name)
hinoka@chromium.orgc8444f32014-06-18 23:18:17 +0000540
Karen Qianccd2b4d2019-05-03 22:25:59 +0000541 # remove all other directory/.ready files in the same gs_path
542 # except for the directory/.ready file previously created
543 # which can be used for bootstrapping while the current one is
544 # being uploaded
545 if not prune:
546 return
547 prev_dest_prefix = self._GetMostRecentCacheDirectory(ls_out_set)
548 if not prev_dest_prefix:
549 return
550 for path in ls_out_set:
551 if (path == prev_dest_prefix + '/' or
552 path == prev_dest_prefix + '.ready'):
553 continue
554 if path.endswith('.ready'):
555 gsutil.call('rm', path)
556 continue
557 gsutil.call('-m', 'rm', '-r', path)
558
559
szager@chromium.orgcdfcd7c2014-06-10 23:40:46 +0000560 @staticmethod
561 def DeleteTmpPackFiles(path):
562 pack_dir = os.path.join(path, 'objects', 'pack')
szager@chromium.org33418492014-06-18 19:03:39 +0000563 if not os.path.isdir(pack_dir):
564 return
szager@chromium.orgcdfcd7c2014-06-10 23:40:46 +0000565 pack_files = [f for f in os.listdir(pack_dir) if
566 f.startswith('.tmp-') or f.startswith('tmp_pack_')]
567 for f in pack_files:
568 f = os.path.join(pack_dir, f)
569 try:
570 os.remove(f)
Gavin Make6a62332020-12-04 21:57:10 +0000571 logging.warning('Deleted stale temporary pack file %s' % f)
szager@chromium.orgcdfcd7c2014-06-10 23:40:46 +0000572 except OSError:
Gavin Make6a62332020-12-04 21:57:10 +0000573 logging.warning('Unable to delete temporary pack file %s' % f)
szager@chromium.org174766f2014-05-13 21:27:46 +0000574
szager@chromium.org848fd492014-04-09 19:06:44 +0000575
agable@chromium.org5a306a22014-02-24 22:13:59 +0000576@subcommand.usage('[url of repo to check for caching]')
577def CMDexists(parser, args):
578 """Check to see if there already is a cache of the given repo."""
szager@chromium.org848fd492014-04-09 19:06:44 +0000579 _, args = parser.parse_args(args)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000580 if not len(args) == 1:
581 parser.error('git cache exists only takes exactly one repo url.')
582 url = args[0]
szager@chromium.org848fd492014-04-09 19:06:44 +0000583 mirror = Mirror(url)
584 if mirror.exists():
585 print(mirror.mirror_path)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000586 return 0
587 return 1
588
589
hinoka@google.com563559c2014-04-02 00:36:24 +0000590@subcommand.usage('[url of repo to create a bootstrap zip file]')
591def CMDupdate_bootstrap(parser, args):
592 """Create and uploads a bootstrap tarball."""
593 # Lets just assert we can't do this on Windows.
594 if sys.platform.startswith('win'):
szager@chromium.org848fd492014-04-09 19:06:44 +0000595 print('Sorry, update bootstrap will not work on Windows.', file=sys.stderr)
hinoka@google.com563559c2014-04-02 00:36:24 +0000596 return 1
597
Robert Iannucci0081c0f2019-09-29 08:30:54 +0000598 parser.add_option('--skip-populate', action='store_true',
599 help='Skips "populate" step if mirror already exists.')
Andrii Shyshkalovdcfe55f2019-09-21 03:35:39 +0000600 parser.add_option('--gc-aggressive', action='store_true',
601 help='Run aggressive repacking of the repo.')
hinoka@chromium.orgc8444f32014-06-18 23:18:17 +0000602 parser.add_option('--prune', action='store_true',
Andrii Shyshkalov7a2205c2019-04-26 05:14:36 +0000603 help='Prune all other cached bundles of the same repo.')
Anthony Polito90b4c0f2020-11-17 18:09:21 +0000604 parser.add_option('--branch', default='master',
605 help='Branch to use for bootstrap. (Default \'master\')')
hinoka@chromium.orgc8444f32014-06-18 23:18:17 +0000606
hinoka@google.com563559c2014-04-02 00:36:24 +0000607 populate_args = args[:]
Robert Iannucci0081c0f2019-09-29 08:30:54 +0000608 options, args = parser.parse_args(args)
609 url = args[0]
610 mirror = Mirror(url)
611 if not options.skip_populate or not mirror.exists():
612 CMDpopulate(parser, populate_args)
613 else:
614 print('Skipped populate step.')
hinoka@google.com563559c2014-04-02 00:36:24 +0000615
616 # Get the repo directory.
Andrii Shyshkalovc50b0962019-11-21 23:03:18 +0000617 _, args2 = parser.parse_args(args)
618 url = args2[0]
szager@chromium.org848fd492014-04-09 19:06:44 +0000619 mirror = Mirror(url)
Anthony Polito90b4c0f2020-11-17 18:09:21 +0000620 mirror.update_bootstrap(options.prune, options.gc_aggressive, options.branch)
szager@chromium.org848fd492014-04-09 19:06:44 +0000621 return 0
hinoka@google.com563559c2014-04-02 00:36:24 +0000622
623
agable@chromium.org5a306a22014-02-24 22:13:59 +0000624@subcommand.usage('[url of repo to add to or update in cache]')
625def CMDpopulate(parser, args):
626 """Ensure that the cache has all up-to-date objects for the given repo."""
627 parser.add_option('--depth', type='int',
628 help='Only cache DEPTH commits of history')
danakjc41f72c2019-11-05 17:12:01 +0000629 parser.add_option(
630 '--no-fetch-tags',
631 action='store_true',
632 help=('Don\'t fetch tags from the server. This can speed up '
633 'fetch considerably when there are many tags.'))
agable@chromium.org5a306a22014-02-24 22:13:59 +0000634 parser.add_option('--shallow', '-s', action='store_true',
635 help='Only cache 10000 commits of history')
636 parser.add_option('--ref', action='append',
637 help='Specify additional refs to be fetched')
pgervais@chromium.orgb9f27512014-08-08 15:52:33 +0000638 parser.add_option('--no_bootstrap', '--no-bootstrap',
639 action='store_true',
hinoka@google.com563559c2014-04-02 00:36:24 +0000640 help='Don\'t bootstrap from Google Storage')
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000641 parser.add_option('--ignore_locks',
642 '--ignore-locks',
Vadim Shtayura08049e22017-10-11 00:14:52 +0000643 action='store_true',
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000644 help='NOOP. This flag will be removed in the future.')
Robert Iannucci09315982019-10-05 08:12:03 +0000645 parser.add_option('--break-locks',
646 action='store_true',
647 help='Break any existing lock instead of just ignoring it')
Edward Lemur579c9862018-07-13 23:17:51 +0000648 parser.add_option('--reset-fetch-config', action='store_true', default=False,
649 help='Reset the fetch config before populating the cache.')
hinoka@google.com563559c2014-04-02 00:36:24 +0000650
agable@chromium.org5a306a22014-02-24 22:13:59 +0000651 options, args = parser.parse_args(args)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000652 if not len(args) == 1:
653 parser.error('git cache populate only takes exactly one repo url.')
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000654 if options.ignore_locks:
655 print('ignore_locks is no longer used. Please remove its usage.')
656 if options.break_locks:
657 print('break_locks is no longer used. Please remove its usage.')
agable@chromium.org5a306a22014-02-24 22:13:59 +0000658 url = args[0]
659
Edward Lesmes93d80d82021-04-20 02:55:11 +0000660 mirror = Mirror(url, refs=options.ref)
szager@chromium.org848fd492014-04-09 19:06:44 +0000661 kwargs = {
danakjc41f72c2019-11-05 17:12:01 +0000662 'no_fetch_tags': options.no_fetch_tags,
szager@chromium.org848fd492014-04-09 19:06:44 +0000663 'verbose': options.verbose,
664 'shallow': options.shallow,
665 'bootstrap': not options.no_bootstrap,
Vadim Shtayura08049e22017-10-11 00:14:52 +0000666 'lock_timeout': options.timeout,
Edward Lemur579c9862018-07-13 23:17:51 +0000667 'reset_fetch_config': options.reset_fetch_config,
szager@chromium.org848fd492014-04-09 19:06:44 +0000668 }
agable@chromium.org5a306a22014-02-24 22:13:59 +0000669 if options.depth:
szager@chromium.org848fd492014-04-09 19:06:44 +0000670 kwargs['depth'] = options.depth
671 mirror.populate(**kwargs)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000672
673
szager@chromium.orgf3145112014-08-07 21:02:36 +0000674@subcommand.usage('Fetch new commits into cache and current checkout')
675def CMDfetch(parser, args):
676 """Update mirror, and fetch in cwd."""
677 parser.add_option('--all', action='store_true', help='Fetch all remotes')
szager@chromium.org66c8b852015-09-22 23:19:07 +0000678 parser.add_option('--no_bootstrap', '--no-bootstrap',
679 action='store_true',
680 help='Don\'t (re)bootstrap from Google Storage')
danakjc41f72c2019-11-05 17:12:01 +0000681 parser.add_option(
682 '--no-fetch-tags',
683 action='store_true',
684 help=('Don\'t fetch tags from the server. This can speed up '
685 'fetch considerably when there are many tags.'))
szager@chromium.orgf3145112014-08-07 21:02:36 +0000686 options, args = parser.parse_args(args)
687
688 # Figure out which remotes to fetch. This mimics the behavior of regular
689 # 'git fetch'. Note that in the case of "stacked" or "pipelined" branches,
690 # this will NOT try to traverse up the branching structure to find the
691 # ultimate remote to update.
692 remotes = []
693 if options.all:
694 assert not args, 'fatal: fetch --all does not take a repository argument'
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000695 remotes = subprocess.check_output([Mirror.git_exe, 'remote'])
696 remotes = remotes.decode('utf-8', 'ignore').splitlines()
szager@chromium.orgf3145112014-08-07 21:02:36 +0000697 elif args:
698 remotes = args
699 else:
700 current_branch = subprocess.check_output(
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000701 [Mirror.git_exe, 'rev-parse', '--abbrev-ref', 'HEAD'])
702 current_branch = current_branch.decode('utf-8', 'ignore').strip()
szager@chromium.orgf3145112014-08-07 21:02:36 +0000703 if current_branch != 'HEAD':
704 upstream = subprocess.check_output(
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000705 [Mirror.git_exe, 'config', 'branch.%s.remote' % current_branch])
706 upstream = upstream.decode('utf-8', 'ignore').strip()
szager@chromium.orgf3145112014-08-07 21:02:36 +0000707 if upstream and upstream != '.':
708 remotes = [upstream]
709 if not remotes:
710 remotes = ['origin']
711
712 cachepath = Mirror.GetCachePath()
713 git_dir = os.path.abspath(subprocess.check_output(
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000714 [Mirror.git_exe, 'rev-parse', '--git-dir']).decode('utf-8', 'ignore'))
szager@chromium.orgf3145112014-08-07 21:02:36 +0000715 git_dir = os.path.abspath(git_dir)
716 if git_dir.startswith(cachepath):
717 mirror = Mirror.FromPath(git_dir)
szager@chromium.orgdbb6f822016-02-02 22:59:30 +0000718 mirror.populate(
danakjc41f72c2019-11-05 17:12:01 +0000719 bootstrap=not options.no_bootstrap,
720 no_fetch_tags=options.no_fetch_tags,
721 lock_timeout=options.timeout)
szager@chromium.orgf3145112014-08-07 21:02:36 +0000722 return 0
723 for remote in remotes:
724 remote_url = subprocess.check_output(
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000725 [Mirror.git_exe, 'config', 'remote.%s.url' % remote])
726 remote_url = remote_url.decode('utf-8', 'ignore').strip()
szager@chromium.orgf3145112014-08-07 21:02:36 +0000727 if remote_url.startswith(cachepath):
728 mirror = Mirror.FromPath(remote_url)
729 mirror.print = lambda *args: None
730 print('Updating git cache...')
szager@chromium.orgdbb6f822016-02-02 22:59:30 +0000731 mirror.populate(
danakjc41f72c2019-11-05 17:12:01 +0000732 bootstrap=not options.no_bootstrap,
733 no_fetch_tags=options.no_fetch_tags,
734 lock_timeout=options.timeout)
szager@chromium.orgf3145112014-08-07 21:02:36 +0000735 subprocess.check_call([Mirror.git_exe, 'fetch', remote])
736 return 0
737
738
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000739@subcommand.usage('do not use - it is a noop.')
Vadim Shtayura08049e22017-10-11 00:14:52 +0000740def CMDunlock(parser, args):
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000741 """This command does nothing."""
742 print('This command does nothing and will be removed in the future.')
Vadim Shtayura08049e22017-10-11 00:14:52 +0000743
744
agable@chromium.org5a306a22014-02-24 22:13:59 +0000745class OptionParser(optparse.OptionParser):
746 """Wrapper class for OptionParser to handle global options."""
747
748 def __init__(self, *args, **kwargs):
749 optparse.OptionParser.__init__(self, *args, prog='git cache', **kwargs)
750 self.add_option('-c', '--cache-dir',
Robert Iannuccia19649b2018-06-29 16:31:45 +0000751 help=(
752 'Path to the directory containing the caches. Normally '
753 'deduced from git config cache.cachepath or '
754 '$GIT_CACHE_PATH.'))
szager@chromium.org2c391af2014-05-23 09:07:15 +0000755 self.add_option('-v', '--verbose', action='count', default=1,
agable@chromium.org5a306a22014-02-24 22:13:59 +0000756 help='Increase verbosity (can be passed multiple times)')
szager@chromium.org2c391af2014-05-23 09:07:15 +0000757 self.add_option('-q', '--quiet', action='store_true',
758 help='Suppress all extraneous output')
Vadim Shtayura08049e22017-10-11 00:14:52 +0000759 self.add_option('--timeout', type='int', default=0,
760 help='Timeout for acquiring cache lock, in seconds')
agable@chromium.org5a306a22014-02-24 22:13:59 +0000761
762 def parse_args(self, args=None, values=None):
763 options, args = optparse.OptionParser.parse_args(self, args, values)
szager@chromium.org2c391af2014-05-23 09:07:15 +0000764 if options.quiet:
765 options.verbose = 0
766
767 levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
768 logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)])
agable@chromium.org5a306a22014-02-24 22:13:59 +0000769
770 try:
szager@chromium.org848fd492014-04-09 19:06:44 +0000771 global_cache_dir = Mirror.GetCachePath()
772 except RuntimeError:
773 global_cache_dir = None
774 if options.cache_dir:
775 if global_cache_dir and (
776 os.path.abspath(options.cache_dir) !=
777 os.path.abspath(global_cache_dir)):
Gavin Make6a62332020-12-04 21:57:10 +0000778 logging.warning('Overriding globally-configured cache directory.')
szager@chromium.org848fd492014-04-09 19:06:44 +0000779 Mirror.SetCachePath(options.cache_dir)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000780
agable@chromium.org5a306a22014-02-24 22:13:59 +0000781 return options, args
782
783
784def main(argv):
785 dispatcher = subcommand.CommandDispatcher(__name__)
786 return dispatcher.execute(OptionParser(), argv)
787
788
789if __name__ == '__main__':
sbc@chromium.org013731e2015-02-26 18:28:43 +0000790 try:
791 sys.exit(main(sys.argv[1:]))
792 except KeyboardInterrupt:
793 sys.stderr.write('interrupted\n')
Edward Lemurdf746d02019-07-27 00:42:46 +0000794 sys.exit(1)