Edward Lesmes | 98eda3f | 2019-08-12 21:09:53 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 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 | |
| 6 | """A git command for managing a local cache of git repositories.""" |
| 7 | |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 8 | from __future__ import print_function |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 9 | |
Andrii Shyshkalov | 4f56f23 | 2017-11-23 02:19:25 -0800 | [diff] [blame] | 10 | import contextlib |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 11 | import errno |
| 12 | import logging |
| 13 | import optparse |
| 14 | import os |
szager@chromium.org | 174766f | 2014-05-13 21:27:46 +0000 | [diff] [blame] | 15 | import re |
John Budorick | 47ec069 | 2019-05-01 15:04:28 +0000 | [diff] [blame] | 16 | import subprocess |
| 17 | import sys |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 18 | import tempfile |
szager@chromium.org | 1132f5f | 2014-08-23 01:57:59 +0000 | [diff] [blame] | 19 | import threading |
pgervais@chromium.org | f372610 | 2014-04-17 17:24:15 +0000 | [diff] [blame] | 20 | import time |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 21 | |
| 22 | try: |
| 23 | import urlparse |
| 24 | except ImportError: # For Py3 compatibility |
| 25 | import urllib.parse as urlparse |
| 26 | |
hinoka@google.com | 563559c | 2014-04-02 00:36:24 +0000 | [diff] [blame] | 27 | from download_from_google_storage import Gsutil |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 28 | import gclient_utils |
Josip Sokcevic | 14a83ae | 2020-05-21 01:36:34 +0000 | [diff] [blame^] | 29 | import lockfile |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 30 | import subcommand |
| 31 | |
szager@chromium.org | 301a7c3 | 2014-06-16 17:13:50 +0000 | [diff] [blame] | 32 | # Analogous to gc.autopacklimit git config. |
| 33 | GC_AUTOPACKLIMIT = 50 |
Takuto Ikuta | 9fce213 | 2017-12-14 10:44:28 +0900 | [diff] [blame] | 34 | |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 35 | GIT_CACHE_CORRUPT_MESSAGE = 'WARNING: The Git cache is corrupt.' |
| 36 | |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 37 | try: |
Quinten Yearsley | b2cc4a9 | 2016-12-15 13:53:26 -0800 | [diff] [blame] | 38 | # pylint: disable=undefined-variable |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 39 | WinErr = WindowsError |
| 40 | except NameError: |
| 41 | class WinErr(Exception): |
| 42 | pass |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 43 | |
hinoka | dcd8404 | 2016-06-09 14:26:17 -0700 | [diff] [blame] | 44 | class ClobberNeeded(Exception): |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 45 | pass |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 46 | |
dnj | 4625b5a | 2016-11-10 18:23:26 -0800 | [diff] [blame] | 47 | |
| 48 | def 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 Lesmes | 451e8ba | 2019-10-01 22:15:33 +0000 | [diff] [blame] | 70 | for i in range(count): |
dnj | 4625b5a | 2016-11-10 18:23:26 -0800 | [diff] [blame] | 71 | 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.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 83 | class Mirror(object): |
| 84 | |
| 85 | git_exe = 'git.bat' if sys.platform.startswith('win') else 'git' |
| 86 | gsutil_exe = os.path.join( |
hinoka@chromium.org | b091aa5 | 2014-12-20 01:47:31 +0000 | [diff] [blame] | 87 | os.path.dirname(os.path.abspath(__file__)), 'gsutil.py') |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 88 | cachepath_lock = threading.Lock() |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 89 | |
Robert Iannucci | a19649b | 2018-06-29 16:31:45 +0000 | [diff] [blame] | 90 | UNSET_CACHEPATH = object() |
| 91 | |
| 92 | # Used for tests |
| 93 | _GIT_CONFIG_LOCATION = [] |
| 94 | |
szager@chromium.org | 66c8b85 | 2015-09-22 23:19:07 +0000 | [diff] [blame] | 95 | @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 | |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 110 | def __init__(self, url, refs=None, print_func=None): |
| 111 | self.url = url |
szager@chromium.org | 66c8b85 | 2015-09-22 23:19:07 +0000 | [diff] [blame] | 112 | self.fetch_specs = set([self.parse_fetch_spec(ref) for ref in (refs or [])]) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 113 | self.basedir = self.UrlToCacheDir(url) |
| 114 | self.mirror_path = os.path.join(self.GetCachePath(), self.basedir) |
loislo@chromium.org | 0fb693f | 2014-12-25 15:28:22 +0000 | [diff] [blame] | 115 | if print_func: |
| 116 | self.print = self.print_without_file |
| 117 | self.print_func = print_func |
| 118 | else: |
| 119 | self.print = print |
| 120 | |
dnj | 4625b5a | 2016-11-10 18:23:26 -0800 | [diff] [blame] | 121 | def print_without_file(self, message, **_kwargs): |
loislo@chromium.org | 0fb693f | 2014-12-25 15:28:22 +0000 | [diff] [blame] | 122 | self.print_func(message) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 123 | |
Andrii Shyshkalov | 4f56f23 | 2017-11-23 02:19:25 -0800 | [diff] [blame] | 124 | @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.org | f8fa23d | 2014-06-05 01:00:04 +0000 | [diff] [blame] | 132 | @property |
| 133 | def bootstrap_bucket(self): |
Andrii Shyshkalov | 4b79c38 | 2019-04-15 23:48:35 +0000 | [diff] [blame] | 134 | b = os.getenv('OVERRIDE_BOOTSTRAP_BUCKET') |
| 135 | if b: |
| 136 | return b |
Ryan Tseng | 3beabd0 | 2017-03-15 13:57:58 -0700 | [diff] [blame] | 137 | u = urlparse.urlparse(self.url) |
| 138 | if u.netloc == 'chromium.googlesource.com': |
hinoka@chromium.org | f8fa23d | 2014-06-05 01:00:04 +0000 | [diff] [blame] | 139 | return 'chromium-git-cache' |
Andrii Shyshkalov | 4b79c38 | 2019-04-15 23:48:35 +0000 | [diff] [blame] | 140 | # TODO(tandrii): delete once LUCI migration is completed. |
| 141 | # Only public hosts will be supported going forward. |
Ryan Tseng | 3beabd0 | 2017-03-15 13:57:58 -0700 | [diff] [blame] | 142 | elif u.netloc == 'chrome-internal.googlesource.com': |
| 143 | return 'chrome-git-cache' |
| 144 | # Not recognized. |
| 145 | return None |
hinoka@chromium.org | f8fa23d | 2014-06-05 01:00:04 +0000 | [diff] [blame] | 146 | |
Karen Qian | dcad749 | 2019-04-26 03:11:16 +0000 | [diff] [blame] | 147 | @property |
| 148 | def _gs_path(self): |
| 149 | return 'gs://%s/v2/%s' % (self.bootstrap_bucket, self.basedir) |
| 150 | |
szager@chromium.org | 174766f | 2014-05-13 21:27:46 +0000 | [diff] [blame] | 151 | @classmethod |
| 152 | def FromPath(cls, path): |
| 153 | return cls(cls.CacheDirToUrl(path)) |
| 154 | |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 155 | @staticmethod |
| 156 | def UrlToCacheDir(url): |
| 157 | """Convert a git url to a normalized form for the cache dir path.""" |
Edward Lemur | e9024d0 | 2019-11-19 18:47:46 +0000 | [diff] [blame] | 158 | if os.path.isdir(url): |
| 159 | # Ignore the drive letter in Windows |
| 160 | url = os.path.splitdrive(url)[1] |
| 161 | return url.replace('-', '--').replace(os.sep, '-') |
| 162 | |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 163 | parsed = urlparse.urlparse(url) |
Edward Lemur | e9024d0 | 2019-11-19 18:47:46 +0000 | [diff] [blame] | 164 | norm_url = parsed.netloc + parsed.path |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 165 | if norm_url.endswith('.git'): |
| 166 | norm_url = norm_url[:-len('.git')] |
Dirk Pranke | db58954 | 2019-04-12 21:07:01 +0000 | [diff] [blame] | 167 | |
| 168 | # Use the same dir for authenticated URLs and unauthenticated URLs. |
| 169 | norm_url = norm_url.replace('googlesource.com/a/', 'googlesource.com/') |
| 170 | |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 171 | return norm_url.replace('-', '--').replace('/', '-').lower() |
| 172 | |
| 173 | @staticmethod |
szager@chromium.org | 174766f | 2014-05-13 21:27:46 +0000 | [diff] [blame] | 174 | def CacheDirToUrl(path): |
| 175 | """Convert a cache dir path to its corresponding url.""" |
| 176 | netpath = re.sub(r'\b-\b', '/', os.path.basename(path)).replace('--', '-') |
| 177 | return 'https://%s' % netpath |
| 178 | |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 179 | @classmethod |
| 180 | def SetCachePath(cls, cachepath): |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 181 | with cls.cachepath_lock: |
| 182 | setattr(cls, 'cachepath', cachepath) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 183 | |
| 184 | @classmethod |
| 185 | def GetCachePath(cls): |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 186 | with cls.cachepath_lock: |
| 187 | if not hasattr(cls, 'cachepath'): |
| 188 | try: |
| 189 | cachepath = subprocess.check_output( |
Robert Iannucci | a19649b | 2018-06-29 16:31:45 +0000 | [diff] [blame] | 190 | [cls.git_exe, 'config'] + |
| 191 | cls._GIT_CONFIG_LOCATION + |
Edward Lesmes | 4c3eb70 | 2020-03-25 21:09:30 +0000 | [diff] [blame] | 192 | ['cache.cachepath']).decode('utf-8', 'ignore').strip() |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 193 | except subprocess.CalledProcessError: |
Robert Iannucci | a19649b | 2018-06-29 16:31:45 +0000 | [diff] [blame] | 194 | cachepath = os.environ.get('GIT_CACHE_PATH', cls.UNSET_CACHEPATH) |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 195 | setattr(cls, 'cachepath', cachepath) |
Robert Iannucci | a19649b | 2018-06-29 16:31:45 +0000 | [diff] [blame] | 196 | |
| 197 | ret = getattr(cls, 'cachepath') |
| 198 | if ret is cls.UNSET_CACHEPATH: |
| 199 | raise RuntimeError('No cache.cachepath git configuration or ' |
| 200 | '$GIT_CACHE_PATH is set.') |
| 201 | return ret |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 202 | |
Karen Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 203 | @staticmethod |
| 204 | def _GetMostRecentCacheDirectory(ls_out_set): |
| 205 | ready_file_pattern = re.compile(r'.*/(\d+).ready$') |
| 206 | ready_dirs = [] |
| 207 | |
| 208 | for name in ls_out_set: |
| 209 | m = ready_file_pattern.match(name) |
| 210 | # Given <path>/<number>.ready, |
| 211 | # we are interested in <path>/<number> directory |
| 212 | if m and (name[:-len('.ready')] + '/') in ls_out_set: |
| 213 | ready_dirs.append((int(m.group(1)), name[:-len('.ready')])) |
| 214 | |
| 215 | if not ready_dirs: |
| 216 | return None |
| 217 | |
| 218 | return max(ready_dirs)[1] |
| 219 | |
dnj | 4625b5a | 2016-11-10 18:23:26 -0800 | [diff] [blame] | 220 | def Rename(self, src, dst): |
| 221 | # This is somehow racy on Windows. |
| 222 | # Catching OSError because WindowsError isn't portable and |
| 223 | # pylint complains. |
| 224 | exponential_backoff_retry( |
| 225 | lambda: os.rename(src, dst), |
| 226 | excs=(OSError,), |
| 227 | name='rename [%s] => [%s]' % (src, dst), |
| 228 | printerr=self.print) |
| 229 | |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 230 | def RunGit(self, cmd, **kwargs): |
| 231 | """Run git in a subprocess.""" |
| 232 | cwd = kwargs.setdefault('cwd', self.mirror_path) |
| 233 | kwargs.setdefault('print_stdout', False) |
| 234 | kwargs.setdefault('filter_fn', self.print) |
| 235 | env = kwargs.get('env') or kwargs.setdefault('env', os.environ.copy()) |
| 236 | env.setdefault('GIT_ASKPASS', 'true') |
| 237 | env.setdefault('SSH_ASKPASS', 'true') |
| 238 | self.print('running "git %s" in "%s"' % (' '.join(cmd), cwd)) |
| 239 | gclient_utils.CheckCallAndFilter([self.git_exe] + cmd, **kwargs) |
| 240 | |
Edward Lemur | 579c986 | 2018-07-13 23:17:51 +0000 | [diff] [blame] | 241 | def config(self, cwd=None, reset_fetch_config=False): |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 242 | if cwd is None: |
| 243 | cwd = self.mirror_path |
szager@chromium.org | 301a7c3 | 2014-06-16 17:13:50 +0000 | [diff] [blame] | 244 | |
Edward Lemur | 579c986 | 2018-07-13 23:17:51 +0000 | [diff] [blame] | 245 | if reset_fetch_config: |
Edward Lemur | 2f38df6 | 2018-07-14 02:13:21 +0000 | [diff] [blame] | 246 | try: |
| 247 | self.RunGit(['config', '--unset-all', 'remote.origin.fetch'], cwd=cwd) |
| 248 | except subprocess.CalledProcessError as e: |
| 249 | # If exit code was 5, it means we attempted to unset a config that |
| 250 | # didn't exist. Ignore it. |
| 251 | if e.returncode != 5: |
| 252 | raise |
Edward Lemur | 579c986 | 2018-07-13 23:17:51 +0000 | [diff] [blame] | 253 | |
szager@chromium.org | 301a7c3 | 2014-06-16 17:13:50 +0000 | [diff] [blame] | 254 | # Don't run git-gc in a daemon. Bad things can happen if it gets killed. |
hinoka | dcd8404 | 2016-06-09 14:26:17 -0700 | [diff] [blame] | 255 | try: |
| 256 | self.RunGit(['config', 'gc.autodetach', '0'], cwd=cwd) |
| 257 | except subprocess.CalledProcessError: |
| 258 | # Hard error, need to clobber. |
| 259 | raise ClobberNeeded() |
szager@chromium.org | 301a7c3 | 2014-06-16 17:13:50 +0000 | [diff] [blame] | 260 | |
| 261 | # Don't combine pack files into one big pack file. It's really slow for |
| 262 | # repositories, and there's no way to track progress and make sure it's |
| 263 | # not stuck. |
Ryan Tseng | 3beabd0 | 2017-03-15 13:57:58 -0700 | [diff] [blame] | 264 | if self.supported_project(): |
| 265 | self.RunGit(['config', 'gc.autopacklimit', '0'], cwd=cwd) |
szager@chromium.org | 301a7c3 | 2014-06-16 17:13:50 +0000 | [diff] [blame] | 266 | |
| 267 | # Allocate more RAM for cache-ing delta chains, for better performance |
| 268 | # of "Resolving deltas". |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 269 | self.RunGit(['config', 'core.deltaBaseCacheLimit', |
hinoka@chromium.org | 8e095af | 2015-06-10 19:19:07 +0000 | [diff] [blame] | 270 | gclient_utils.DefaultDeltaBaseCacheLimit()], cwd=cwd) |
szager@chromium.org | 301a7c3 | 2014-06-16 17:13:50 +0000 | [diff] [blame] | 271 | |
hinoka@chromium.org | 8e095af | 2015-06-10 19:19:07 +0000 | [diff] [blame] | 272 | self.RunGit(['config', 'remote.origin.url', self.url], cwd=cwd) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 273 | self.RunGit(['config', '--replace-all', 'remote.origin.fetch', |
hinoka@chromium.org | 8e095af | 2015-06-10 19:19:07 +0000 | [diff] [blame] | 274 | '+refs/heads/*:refs/heads/*', r'\+refs/heads/\*:.*'], cwd=cwd) |
szager@chromium.org | 66c8b85 | 2015-09-22 23:19:07 +0000 | [diff] [blame] | 275 | for spec, value_regex in self.fetch_specs: |
szager@chromium.org | 965c44f | 2014-08-19 21:19:19 +0000 | [diff] [blame] | 276 | self.RunGit( |
szager@chromium.org | 66c8b85 | 2015-09-22 23:19:07 +0000 | [diff] [blame] | 277 | ['config', '--replace-all', 'remote.origin.fetch', spec, value_regex], |
hinoka@chromium.org | 8e095af | 2015-06-10 19:19:07 +0000 | [diff] [blame] | 278 | cwd=cwd) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 279 | |
| 280 | def bootstrap_repo(self, directory): |
Andrii Shyshkalov | 4f56f23 | 2017-11-23 02:19:25 -0800 | [diff] [blame] | 281 | """Bootstrap the repo from Google Storage if possible. |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 282 | |
| 283 | More apt-ly named bootstrap_repo_from_cloud_if_possible_else_do_nothing(). |
| 284 | """ |
Ryan Tseng | 3beabd0 | 2017-03-15 13:57:58 -0700 | [diff] [blame] | 285 | if not self.bootstrap_bucket: |
| 286 | return False |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 287 | |
hinoka@chromium.org | 199bc5f | 2014-12-17 02:17:14 +0000 | [diff] [blame] | 288 | gsutil = Gsutil(self.gsutil_exe, boto_path=None) |
Yuwei Huang | a1fbdff | 2019-02-01 21:51:15 +0000 | [diff] [blame] | 289 | |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 290 | # Get the most recent version of the directory. |
| 291 | # This is determined from the most recent version of a .ready file. |
| 292 | # The .ready file is only uploaded when an entire directory has been |
| 293 | # uploaded to GS. |
| 294 | _, ls_out, ls_err = gsutil.check_call('ls', self._gs_path) |
Karen Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 295 | ls_out_set = set(ls_out.strip().splitlines()) |
| 296 | latest_dir = self._GetMostRecentCacheDirectory(ls_out_set) |
Yuwei Huang | a1fbdff | 2019-02-01 21:51:15 +0000 | [diff] [blame] | 297 | |
Karen Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 298 | if not latest_dir: |
Andrii Shyshkalov | 4f56f23 | 2017-11-23 02:19:25 -0800 | [diff] [blame] | 299 | self.print('No bootstrap file for %s found in %s, stderr:\n %s' % |
| 300 | (self.mirror_path, self.bootstrap_bucket, |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 301 | ' '.join((ls_err or '').splitlines(True)))) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 302 | return False |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 303 | |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 304 | try: |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 305 | # create new temporary directory locally |
szager@chromium.org | 1cbf104 | 2014-06-17 18:26:24 +0000 | [diff] [blame] | 306 | tempdir = tempfile.mkdtemp(prefix='_cache_tmp', dir=self.GetCachePath()) |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 307 | self.RunGit(['init', '--bare'], cwd=tempdir) |
| 308 | self.print('Downloading files in %s/* into %s.' % |
| 309 | (latest_dir, tempdir)) |
Andrii Shyshkalov | 4f56f23 | 2017-11-23 02:19:25 -0800 | [diff] [blame] | 310 | with self.print_duration_of('download'): |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 311 | code = gsutil.call('-m', 'cp', '-r', latest_dir + "/*", |
| 312 | tempdir) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 313 | if code: |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 314 | return False |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 315 | except Exception as e: |
| 316 | self.print('Encountered error: %s' % str(e), file=sys.stderr) |
| 317 | gclient_utils.rmtree(tempdir) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 318 | return False |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 319 | # delete the old directory |
| 320 | if os.path.exists(directory): |
| 321 | gclient_utils.rmtree(directory) |
| 322 | self.Rename(tempdir, directory) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 323 | return True |
| 324 | |
Andrii Shyshkalov | 46a672b | 2017-11-24 18:04:43 -0800 | [diff] [blame] | 325 | def contains_revision(self, revision): |
| 326 | if not self.exists(): |
| 327 | return False |
| 328 | |
| 329 | if sys.platform.startswith('win'): |
| 330 | # Windows .bat scripts use ^ as escape sequence, which means we have to |
| 331 | # escape it with itself for every .bat invocation. |
| 332 | needle = '%s^^^^{commit}' % revision |
| 333 | else: |
| 334 | needle = '%s^{commit}' % revision |
| 335 | try: |
| 336 | # cat-file exits with 0 on success, that is git object of given hash was |
| 337 | # found. |
| 338 | self.RunGit(['cat-file', '-e', needle]) |
| 339 | return True |
| 340 | except subprocess.CalledProcessError: |
| 341 | return False |
| 342 | |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 343 | def exists(self): |
| 344 | return os.path.isfile(os.path.join(self.mirror_path, 'config')) |
| 345 | |
Ryan Tseng | 3beabd0 | 2017-03-15 13:57:58 -0700 | [diff] [blame] | 346 | def supported_project(self): |
| 347 | """Returns true if this repo is known to have a bootstrap zip file.""" |
| 348 | u = urlparse.urlparse(self.url) |
| 349 | return u.netloc in [ |
| 350 | 'chromium.googlesource.com', |
| 351 | 'chrome-internal.googlesource.com'] |
| 352 | |
szager@chromium.org | 66c8b85 | 2015-09-22 23:19:07 +0000 | [diff] [blame] | 353 | def _preserve_fetchspec(self): |
| 354 | """Read and preserve remote.origin.fetch from an existing mirror. |
| 355 | |
| 356 | This modifies self.fetch_specs. |
| 357 | """ |
| 358 | if not self.exists(): |
| 359 | return |
| 360 | try: |
| 361 | config_fetchspecs = subprocess.check_output( |
| 362 | [self.git_exe, 'config', '--get-all', 'remote.origin.fetch'], |
Edward Lesmes | 4c3eb70 | 2020-03-25 21:09:30 +0000 | [diff] [blame] | 363 | cwd=self.mirror_path).decode('utf-8', 'ignore') |
szager@chromium.org | 66c8b85 | 2015-09-22 23:19:07 +0000 | [diff] [blame] | 364 | for fetchspec in config_fetchspecs.splitlines(): |
| 365 | self.fetch_specs.add(self.parse_fetch_spec(fetchspec)) |
| 366 | except subprocess.CalledProcessError: |
| 367 | logging.warn('Tried and failed to preserve remote.origin.fetch from the ' |
| 368 | 'existing cache directory. You may need to manually edit ' |
| 369 | '%s and "git cache fetch" again.' |
| 370 | % os.path.join(self.mirror_path, 'config')) |
| 371 | |
Edward Lesmes | 34f71ab | 2020-03-25 21:24:00 +0000 | [diff] [blame] | 372 | def _ensure_bootstrapped( |
| 373 | self, depth, bootstrap, reset_fetch_config, force=False): |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 374 | pack_dir = os.path.join(self.mirror_path, 'objects', 'pack') |
| 375 | pack_files = [] |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 376 | if os.path.isdir(pack_dir): |
| 377 | pack_files = [f for f in os.listdir(pack_dir) if f.endswith('.pack')] |
Edward Lesmes | 34f71ab | 2020-03-25 21:24:00 +0000 | [diff] [blame] | 378 | self.print('%s has %d .pack files, re-bootstrapping if >%d or ==0' % |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 379 | (self.mirror_path, len(pack_files), GC_AUTOPACKLIMIT)) |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 380 | |
| 381 | should_bootstrap = (force or |
szager@chromium.org | 66c8b85 | 2015-09-22 23:19:07 +0000 | [diff] [blame] | 382 | not self.exists() or |
Edward Lesmes | 34f71ab | 2020-03-25 21:24:00 +0000 | [diff] [blame] | 383 | len(pack_files) > GC_AUTOPACKLIMIT or |
| 384 | len(pack_files) == 0) |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 385 | |
| 386 | if not should_bootstrap: |
| 387 | if depth and os.path.exists(os.path.join(self.mirror_path, 'shallow')): |
| 388 | logging.warn( |
| 389 | 'Shallow fetch requested, but repo cache already exists.') |
| 390 | return |
| 391 | |
Edward Lesmes | 34f71ab | 2020-03-25 21:24:00 +0000 | [diff] [blame] | 392 | if not self.exists(): |
John Budorick | 47ec069 | 2019-05-01 15:04:28 +0000 | [diff] [blame] | 393 | if os.path.exists(self.mirror_path): |
| 394 | # If the mirror path exists but self.exists() returns false, we're |
| 395 | # in an unexpected state. Nuke the previous mirror directory and |
| 396 | # start fresh. |
| 397 | gclient_utils.rmtree(self.mirror_path) |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 398 | os.mkdir(self.mirror_path) |
Edward Lesmes | 34f71ab | 2020-03-25 21:24:00 +0000 | [diff] [blame] | 399 | elif not reset_fetch_config: |
| 400 | # Re-bootstrapping an existing mirror; preserve existing fetch spec. |
| 401 | self._preserve_fetchspec() |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 402 | |
| 403 | bootstrapped = (not depth and bootstrap and |
| 404 | self.bootstrap_repo(self.mirror_path)) |
| 405 | |
| 406 | if not bootstrapped: |
| 407 | if not self.exists() or not self.supported_project(): |
| 408 | # Bootstrap failed due to: |
| 409 | # 1. No previous cache. |
| 410 | # 2. Project doesn't have a bootstrap folder. |
Ryan Tseng | 3beabd0 | 2017-03-15 13:57:58 -0700 | [diff] [blame] | 411 | # Start with a bare git dir. |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 412 | self.RunGit(['init', '--bare'], cwd=self.mirror_path) |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 413 | else: |
| 414 | # Bootstrap failed, previous cache exists; warn and continue. |
| 415 | logging.warn( |
Andrii Shyshkalov | 4f56f23 | 2017-11-23 02:19:25 -0800 | [diff] [blame] | 416 | 'Git cache has a lot of pack files (%d). Tried to re-bootstrap ' |
| 417 | 'but failed. Continuing with non-optimized repository.' |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 418 | % len(pack_files)) |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 419 | |
Josip Sokcevic | 6afaa6c | 2020-05-08 18:20:17 +0000 | [diff] [blame] | 420 | def _fetch(self, |
| 421 | rundir, |
| 422 | verbose, |
| 423 | depth, |
| 424 | no_fetch_tags, |
| 425 | reset_fetch_config, |
| 426 | prune=True): |
Edward Lemur | 579c986 | 2018-07-13 23:17:51 +0000 | [diff] [blame] | 427 | self.config(rundir, reset_fetch_config) |
Josip Sokcevic | 6afaa6c | 2020-05-08 18:20:17 +0000 | [diff] [blame] | 428 | |
| 429 | fetch_cmd = ['fetch'] |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 430 | if verbose: |
Josip Sokcevic | 6afaa6c | 2020-05-08 18:20:17 +0000 | [diff] [blame] | 431 | fetch_cmd.extend(['-v', '--progress']) |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 432 | if depth: |
Josip Sokcevic | 6afaa6c | 2020-05-08 18:20:17 +0000 | [diff] [blame] | 433 | fetch_cmd.extend(['--depth', str(depth)]) |
danakj | c41f72c | 2019-11-05 17:12:01 +0000 | [diff] [blame] | 434 | if no_fetch_tags: |
Josip Sokcevic | 6afaa6c | 2020-05-08 18:20:17 +0000 | [diff] [blame] | 435 | fetch_cmd.append('--no-tags') |
| 436 | if prune: |
| 437 | fetch_cmd.append('--prune') |
| 438 | fetch_cmd.append('origin') |
| 439 | |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 440 | fetch_specs = subprocess.check_output( |
| 441 | [self.git_exe, 'config', '--get-all', 'remote.origin.fetch'], |
Edward Lesmes | 4c3eb70 | 2020-03-25 21:09:30 +0000 | [diff] [blame] | 442 | cwd=rundir).decode('utf-8', 'ignore').strip().splitlines() |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 443 | for spec in fetch_specs: |
| 444 | try: |
| 445 | self.print('Fetching %s' % spec) |
Andrii Shyshkalov | 4f56f23 | 2017-11-23 02:19:25 -0800 | [diff] [blame] | 446 | with self.print_duration_of('fetch %s' % spec): |
John Budorick | 3da78c4 | 2019-11-14 20:06:30 +0000 | [diff] [blame] | 447 | self.RunGit(fetch_cmd + [spec], cwd=rundir, retry=True) |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 448 | except subprocess.CalledProcessError: |
| 449 | if spec == '+refs/heads/*:refs/heads/*': |
hinoka | dcd8404 | 2016-06-09 14:26:17 -0700 | [diff] [blame] | 450 | raise ClobberNeeded() # Corrupted cache. |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 451 | logging.warn('Fetch of %s failed' % spec) |
| 452 | |
danakj | c41f72c | 2019-11-05 17:12:01 +0000 | [diff] [blame] | 453 | def populate(self, |
| 454 | depth=None, |
| 455 | no_fetch_tags=False, |
| 456 | shallow=False, |
| 457 | bootstrap=False, |
| 458 | verbose=False, |
danakj | c41f72c | 2019-11-05 17:12:01 +0000 | [diff] [blame] | 459 | lock_timeout=0, |
Edward Lemur | 579c986 | 2018-07-13 23:17:51 +0000 | [diff] [blame] | 460 | reset_fetch_config=False): |
szager@chromium.org | b0a13a2 | 2014-06-18 00:52:25 +0000 | [diff] [blame] | 461 | assert self.GetCachePath() |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 462 | if shallow and not depth: |
| 463 | depth = 10000 |
| 464 | gclient_utils.safe_makedirs(self.GetCachePath()) |
| 465 | |
Josip Sokcevic | 14a83ae | 2020-05-21 01:36:34 +0000 | [diff] [blame^] | 466 | with lockfile.lock(self.mirror_path, lock_timeout): |
| 467 | try: |
| 468 | self._ensure_bootstrapped(depth, bootstrap, reset_fetch_config) |
| 469 | self._fetch(self.mirror_path, verbose, depth, no_fetch_tags, |
| 470 | reset_fetch_config) |
| 471 | except ClobberNeeded: |
| 472 | # This is a major failure, we need to clean and force a bootstrap. |
| 473 | gclient_utils.rmtree(self.mirror_path) |
| 474 | self.print(GIT_CACHE_CORRUPT_MESSAGE) |
| 475 | self._ensure_bootstrapped(depth, |
| 476 | bootstrap, |
| 477 | reset_fetch_config, |
| 478 | force=True) |
| 479 | self._fetch(self.mirror_path, verbose, depth, no_fetch_tags, |
| 480 | reset_fetch_config) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 481 | |
Andrii Shyshkalov | dcfe55f | 2019-09-21 03:35:39 +0000 | [diff] [blame] | 482 | def update_bootstrap(self, prune=False, gc_aggressive=False): |
Karen Qian | dcad749 | 2019-04-26 03:11:16 +0000 | [diff] [blame] | 483 | # The folder is <git number> |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 484 | gen_number = subprocess.check_output( |
Edward Lesmes | 4c3eb70 | 2020-03-25 21:09:30 +0000 | [diff] [blame] | 485 | [self.git_exe, 'number', 'master'], |
| 486 | cwd=self.mirror_path).decode('utf-8', 'ignore').strip() |
Karen Qian | dcad749 | 2019-04-26 03:11:16 +0000 | [diff] [blame] | 487 | gsutil = Gsutil(path=self.gsutil_exe, boto_path=None) |
| 488 | |
| 489 | src_name = self.mirror_path |
Karen Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 490 | dest_prefix = '%s/%s' % (self._gs_path, gen_number) |
Karen Qian | dcad749 | 2019-04-26 03:11:16 +0000 | [diff] [blame] | 491 | |
Karen Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 492 | # ls_out lists contents in the format: gs://blah/blah/123... |
| 493 | _, ls_out, _ = gsutil.check_call('ls', self._gs_path) |
Karen Qian | dcad749 | 2019-04-26 03:11:16 +0000 | [diff] [blame] | 494 | |
Karen Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 495 | # Check to see if folder already exists in gs |
| 496 | ls_out_set = set(ls_out.strip().splitlines()) |
| 497 | if (dest_prefix + '/' in ls_out_set and |
| 498 | dest_prefix + '.ready' in ls_out_set): |
| 499 | print('Cache %s already exists.' % dest_prefix) |
Karen Qian | dcad749 | 2019-04-26 03:11:16 +0000 | [diff] [blame] | 500 | return |
| 501 | |
Andrii Shyshkalov | 199182f | 2019-04-26 16:01:20 +0000 | [diff] [blame] | 502 | # Run Garbage Collect to compress packfile. |
Andrii Shyshkalov | dcfe55f | 2019-09-21 03:35:39 +0000 | [diff] [blame] | 503 | gc_args = ['gc', '--prune=all'] |
| 504 | if gc_aggressive: |
| 505 | gc_args.append('--aggressive') |
| 506 | self.RunGit(gc_args) |
Andrii Shyshkalov | 199182f | 2019-04-26 16:01:20 +0000 | [diff] [blame] | 507 | |
Karen Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 508 | gsutil.call('-m', 'cp', '-r', src_name, dest_prefix) |
Karen Qian | dcad749 | 2019-04-26 03:11:16 +0000 | [diff] [blame] | 509 | |
Karen Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 510 | # Create .ready file and upload |
Karen Qian | dcad749 | 2019-04-26 03:11:16 +0000 | [diff] [blame] | 511 | _, ready_file_name = tempfile.mkstemp(suffix='.ready') |
| 512 | try: |
Karen Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 513 | gsutil.call('cp', ready_file_name, '%s.ready' % (dest_prefix)) |
Karen Qian | dcad749 | 2019-04-26 03:11:16 +0000 | [diff] [blame] | 514 | finally: |
| 515 | os.remove(ready_file_name) |
hinoka@chromium.org | c8444f3 | 2014-06-18 23:18:17 +0000 | [diff] [blame] | 516 | |
Karen Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 517 | # remove all other directory/.ready files in the same gs_path |
| 518 | # except for the directory/.ready file previously created |
| 519 | # which can be used for bootstrapping while the current one is |
| 520 | # being uploaded |
| 521 | if not prune: |
| 522 | return |
| 523 | prev_dest_prefix = self._GetMostRecentCacheDirectory(ls_out_set) |
| 524 | if not prev_dest_prefix: |
| 525 | return |
| 526 | for path in ls_out_set: |
| 527 | if (path == prev_dest_prefix + '/' or |
| 528 | path == prev_dest_prefix + '.ready'): |
| 529 | continue |
| 530 | if path.endswith('.ready'): |
| 531 | gsutil.call('rm', path) |
| 532 | continue |
| 533 | gsutil.call('-m', 'rm', '-r', path) |
| 534 | |
| 535 | |
szager@chromium.org | cdfcd7c | 2014-06-10 23:40:46 +0000 | [diff] [blame] | 536 | @staticmethod |
| 537 | def DeleteTmpPackFiles(path): |
| 538 | pack_dir = os.path.join(path, 'objects', 'pack') |
szager@chromium.org | 3341849 | 2014-06-18 19:03:39 +0000 | [diff] [blame] | 539 | if not os.path.isdir(pack_dir): |
| 540 | return |
szager@chromium.org | cdfcd7c | 2014-06-10 23:40:46 +0000 | [diff] [blame] | 541 | pack_files = [f for f in os.listdir(pack_dir) if |
| 542 | f.startswith('.tmp-') or f.startswith('tmp_pack_')] |
| 543 | for f in pack_files: |
| 544 | f = os.path.join(pack_dir, f) |
| 545 | try: |
| 546 | os.remove(f) |
| 547 | logging.warn('Deleted stale temporary pack file %s' % f) |
| 548 | except OSError: |
| 549 | logging.warn('Unable to delete temporary pack file %s' % f) |
szager@chromium.org | 174766f | 2014-05-13 21:27:46 +0000 | [diff] [blame] | 550 | |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 551 | |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 552 | @subcommand.usage('[url of repo to check for caching]') |
| 553 | def CMDexists(parser, args): |
| 554 | """Check to see if there already is a cache of the given repo.""" |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 555 | _, args = parser.parse_args(args) |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 556 | if not len(args) == 1: |
| 557 | parser.error('git cache exists only takes exactly one repo url.') |
| 558 | url = args[0] |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 559 | mirror = Mirror(url) |
| 560 | if mirror.exists(): |
| 561 | print(mirror.mirror_path) |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 562 | return 0 |
| 563 | return 1 |
| 564 | |
| 565 | |
hinoka@google.com | 563559c | 2014-04-02 00:36:24 +0000 | [diff] [blame] | 566 | @subcommand.usage('[url of repo to create a bootstrap zip file]') |
| 567 | def CMDupdate_bootstrap(parser, args): |
| 568 | """Create and uploads a bootstrap tarball.""" |
| 569 | # Lets just assert we can't do this on Windows. |
| 570 | if sys.platform.startswith('win'): |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 571 | print('Sorry, update bootstrap will not work on Windows.', file=sys.stderr) |
hinoka@google.com | 563559c | 2014-04-02 00:36:24 +0000 | [diff] [blame] | 572 | return 1 |
| 573 | |
Robert Iannucci | 0081c0f | 2019-09-29 08:30:54 +0000 | [diff] [blame] | 574 | parser.add_option('--skip-populate', action='store_true', |
| 575 | help='Skips "populate" step if mirror already exists.') |
Andrii Shyshkalov | dcfe55f | 2019-09-21 03:35:39 +0000 | [diff] [blame] | 576 | parser.add_option('--gc-aggressive', action='store_true', |
| 577 | help='Run aggressive repacking of the repo.') |
hinoka@chromium.org | c8444f3 | 2014-06-18 23:18:17 +0000 | [diff] [blame] | 578 | parser.add_option('--prune', action='store_true', |
Andrii Shyshkalov | 7a2205c | 2019-04-26 05:14:36 +0000 | [diff] [blame] | 579 | help='Prune all other cached bundles of the same repo.') |
hinoka@chromium.org | c8444f3 | 2014-06-18 23:18:17 +0000 | [diff] [blame] | 580 | |
hinoka@google.com | 563559c | 2014-04-02 00:36:24 +0000 | [diff] [blame] | 581 | populate_args = args[:] |
Robert Iannucci | 0081c0f | 2019-09-29 08:30:54 +0000 | [diff] [blame] | 582 | options, args = parser.parse_args(args) |
| 583 | url = args[0] |
| 584 | mirror = Mirror(url) |
| 585 | if not options.skip_populate or not mirror.exists(): |
| 586 | CMDpopulate(parser, populate_args) |
| 587 | else: |
| 588 | print('Skipped populate step.') |
hinoka@google.com | 563559c | 2014-04-02 00:36:24 +0000 | [diff] [blame] | 589 | |
| 590 | # Get the repo directory. |
Andrii Shyshkalov | c50b096 | 2019-11-21 23:03:18 +0000 | [diff] [blame] | 591 | _, args2 = parser.parse_args(args) |
| 592 | url = args2[0] |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 593 | mirror = Mirror(url) |
Andrii Shyshkalov | dcfe55f | 2019-09-21 03:35:39 +0000 | [diff] [blame] | 594 | mirror.update_bootstrap(options.prune, options.gc_aggressive) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 595 | return 0 |
hinoka@google.com | 563559c | 2014-04-02 00:36:24 +0000 | [diff] [blame] | 596 | |
| 597 | |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 598 | @subcommand.usage('[url of repo to add to or update in cache]') |
| 599 | def CMDpopulate(parser, args): |
| 600 | """Ensure that the cache has all up-to-date objects for the given repo.""" |
| 601 | parser.add_option('--depth', type='int', |
| 602 | help='Only cache DEPTH commits of history') |
danakj | c41f72c | 2019-11-05 17:12:01 +0000 | [diff] [blame] | 603 | parser.add_option( |
| 604 | '--no-fetch-tags', |
| 605 | action='store_true', |
| 606 | help=('Don\'t fetch tags from the server. This can speed up ' |
| 607 | 'fetch considerably when there are many tags.')) |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 608 | parser.add_option('--shallow', '-s', action='store_true', |
| 609 | help='Only cache 10000 commits of history') |
| 610 | parser.add_option('--ref', action='append', |
| 611 | help='Specify additional refs to be fetched') |
pgervais@chromium.org | b9f2751 | 2014-08-08 15:52:33 +0000 | [diff] [blame] | 612 | parser.add_option('--no_bootstrap', '--no-bootstrap', |
| 613 | action='store_true', |
hinoka@google.com | 563559c | 2014-04-02 00:36:24 +0000 | [diff] [blame] | 614 | help='Don\'t bootstrap from Google Storage') |
Josip Sokcevic | 14a83ae | 2020-05-21 01:36:34 +0000 | [diff] [blame^] | 615 | parser.add_option('--ignore_locks', |
| 616 | '--ignore-locks', |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 617 | action='store_true', |
Josip Sokcevic | 14a83ae | 2020-05-21 01:36:34 +0000 | [diff] [blame^] | 618 | help='NOOP. This flag will be removed in the future.') |
Robert Iannucci | 0931598 | 2019-10-05 08:12:03 +0000 | [diff] [blame] | 619 | parser.add_option('--break-locks', |
| 620 | action='store_true', |
| 621 | help='Break any existing lock instead of just ignoring it') |
Edward Lemur | 579c986 | 2018-07-13 23:17:51 +0000 | [diff] [blame] | 622 | parser.add_option('--reset-fetch-config', action='store_true', default=False, |
| 623 | help='Reset the fetch config before populating the cache.') |
hinoka@google.com | 563559c | 2014-04-02 00:36:24 +0000 | [diff] [blame] | 624 | |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 625 | options, args = parser.parse_args(args) |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 626 | if not len(args) == 1: |
| 627 | parser.error('git cache populate only takes exactly one repo url.') |
Josip Sokcevic | 14a83ae | 2020-05-21 01:36:34 +0000 | [diff] [blame^] | 628 | if options.ignore_locks: |
| 629 | print('ignore_locks is no longer used. Please remove its usage.') |
| 630 | if options.break_locks: |
| 631 | print('break_locks is no longer used. Please remove its usage.') |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 632 | url = args[0] |
| 633 | |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 634 | mirror = Mirror(url, refs=options.ref) |
| 635 | kwargs = { |
danakj | c41f72c | 2019-11-05 17:12:01 +0000 | [diff] [blame] | 636 | 'no_fetch_tags': options.no_fetch_tags, |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 637 | 'verbose': options.verbose, |
| 638 | 'shallow': options.shallow, |
| 639 | 'bootstrap': not options.no_bootstrap, |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 640 | 'lock_timeout': options.timeout, |
Edward Lemur | 579c986 | 2018-07-13 23:17:51 +0000 | [diff] [blame] | 641 | 'reset_fetch_config': options.reset_fetch_config, |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 642 | } |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 643 | if options.depth: |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 644 | kwargs['depth'] = options.depth |
| 645 | mirror.populate(**kwargs) |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 646 | |
| 647 | |
szager@chromium.org | f314511 | 2014-08-07 21:02:36 +0000 | [diff] [blame] | 648 | @subcommand.usage('Fetch new commits into cache and current checkout') |
| 649 | def CMDfetch(parser, args): |
| 650 | """Update mirror, and fetch in cwd.""" |
| 651 | parser.add_option('--all', action='store_true', help='Fetch all remotes') |
szager@chromium.org | 66c8b85 | 2015-09-22 23:19:07 +0000 | [diff] [blame] | 652 | parser.add_option('--no_bootstrap', '--no-bootstrap', |
| 653 | action='store_true', |
| 654 | help='Don\'t (re)bootstrap from Google Storage') |
danakj | c41f72c | 2019-11-05 17:12:01 +0000 | [diff] [blame] | 655 | parser.add_option( |
| 656 | '--no-fetch-tags', |
| 657 | action='store_true', |
| 658 | help=('Don\'t fetch tags from the server. This can speed up ' |
| 659 | 'fetch considerably when there are many tags.')) |
szager@chromium.org | f314511 | 2014-08-07 21:02:36 +0000 | [diff] [blame] | 660 | options, args = parser.parse_args(args) |
| 661 | |
| 662 | # Figure out which remotes to fetch. This mimics the behavior of regular |
| 663 | # 'git fetch'. Note that in the case of "stacked" or "pipelined" branches, |
| 664 | # this will NOT try to traverse up the branching structure to find the |
| 665 | # ultimate remote to update. |
| 666 | remotes = [] |
| 667 | if options.all: |
| 668 | assert not args, 'fatal: fetch --all does not take a repository argument' |
Edward Lesmes | 4c3eb70 | 2020-03-25 21:09:30 +0000 | [diff] [blame] | 669 | remotes = subprocess.check_output([Mirror.git_exe, 'remote']) |
| 670 | remotes = remotes.decode('utf-8', 'ignore').splitlines() |
szager@chromium.org | f314511 | 2014-08-07 21:02:36 +0000 | [diff] [blame] | 671 | elif args: |
| 672 | remotes = args |
| 673 | else: |
| 674 | current_branch = subprocess.check_output( |
Edward Lesmes | 4c3eb70 | 2020-03-25 21:09:30 +0000 | [diff] [blame] | 675 | [Mirror.git_exe, 'rev-parse', '--abbrev-ref', 'HEAD']) |
| 676 | current_branch = current_branch.decode('utf-8', 'ignore').strip() |
szager@chromium.org | f314511 | 2014-08-07 21:02:36 +0000 | [diff] [blame] | 677 | if current_branch != 'HEAD': |
| 678 | upstream = subprocess.check_output( |
Edward Lesmes | 4c3eb70 | 2020-03-25 21:09:30 +0000 | [diff] [blame] | 679 | [Mirror.git_exe, 'config', 'branch.%s.remote' % current_branch]) |
| 680 | upstream = upstream.decode('utf-8', 'ignore').strip() |
szager@chromium.org | f314511 | 2014-08-07 21:02:36 +0000 | [diff] [blame] | 681 | if upstream and upstream != '.': |
| 682 | remotes = [upstream] |
| 683 | if not remotes: |
| 684 | remotes = ['origin'] |
| 685 | |
| 686 | cachepath = Mirror.GetCachePath() |
| 687 | git_dir = os.path.abspath(subprocess.check_output( |
Edward Lesmes | 4c3eb70 | 2020-03-25 21:09:30 +0000 | [diff] [blame] | 688 | [Mirror.git_exe, 'rev-parse', '--git-dir']).decode('utf-8', 'ignore')) |
szager@chromium.org | f314511 | 2014-08-07 21:02:36 +0000 | [diff] [blame] | 689 | git_dir = os.path.abspath(git_dir) |
| 690 | if git_dir.startswith(cachepath): |
| 691 | mirror = Mirror.FromPath(git_dir) |
szager@chromium.org | dbb6f82 | 2016-02-02 22:59:30 +0000 | [diff] [blame] | 692 | mirror.populate( |
danakj | c41f72c | 2019-11-05 17:12:01 +0000 | [diff] [blame] | 693 | bootstrap=not options.no_bootstrap, |
| 694 | no_fetch_tags=options.no_fetch_tags, |
| 695 | lock_timeout=options.timeout) |
szager@chromium.org | f314511 | 2014-08-07 21:02:36 +0000 | [diff] [blame] | 696 | return 0 |
| 697 | for remote in remotes: |
| 698 | remote_url = subprocess.check_output( |
Edward Lesmes | 4c3eb70 | 2020-03-25 21:09:30 +0000 | [diff] [blame] | 699 | [Mirror.git_exe, 'config', 'remote.%s.url' % remote]) |
| 700 | remote_url = remote_url.decode('utf-8', 'ignore').strip() |
szager@chromium.org | f314511 | 2014-08-07 21:02:36 +0000 | [diff] [blame] | 701 | if remote_url.startswith(cachepath): |
| 702 | mirror = Mirror.FromPath(remote_url) |
| 703 | mirror.print = lambda *args: None |
| 704 | print('Updating git cache...') |
szager@chromium.org | dbb6f82 | 2016-02-02 22:59:30 +0000 | [diff] [blame] | 705 | mirror.populate( |
danakj | c41f72c | 2019-11-05 17:12:01 +0000 | [diff] [blame] | 706 | bootstrap=not options.no_bootstrap, |
| 707 | no_fetch_tags=options.no_fetch_tags, |
| 708 | lock_timeout=options.timeout) |
szager@chromium.org | f314511 | 2014-08-07 21:02:36 +0000 | [diff] [blame] | 709 | subprocess.check_call([Mirror.git_exe, 'fetch', remote]) |
| 710 | return 0 |
| 711 | |
| 712 | |
Josip Sokcevic | 14a83ae | 2020-05-21 01:36:34 +0000 | [diff] [blame^] | 713 | @subcommand.usage('do not use - it is a noop.') |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 714 | def CMDunlock(parser, args): |
Josip Sokcevic | 14a83ae | 2020-05-21 01:36:34 +0000 | [diff] [blame^] | 715 | """This command does nothing.""" |
| 716 | print('This command does nothing and will be removed in the future.') |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 717 | |
| 718 | |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 719 | class OptionParser(optparse.OptionParser): |
| 720 | """Wrapper class for OptionParser to handle global options.""" |
| 721 | |
| 722 | def __init__(self, *args, **kwargs): |
| 723 | optparse.OptionParser.__init__(self, *args, prog='git cache', **kwargs) |
| 724 | self.add_option('-c', '--cache-dir', |
Robert Iannucci | a19649b | 2018-06-29 16:31:45 +0000 | [diff] [blame] | 725 | help=( |
| 726 | 'Path to the directory containing the caches. Normally ' |
| 727 | 'deduced from git config cache.cachepath or ' |
| 728 | '$GIT_CACHE_PATH.')) |
szager@chromium.org | 2c391af | 2014-05-23 09:07:15 +0000 | [diff] [blame] | 729 | self.add_option('-v', '--verbose', action='count', default=1, |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 730 | help='Increase verbosity (can be passed multiple times)') |
szager@chromium.org | 2c391af | 2014-05-23 09:07:15 +0000 | [diff] [blame] | 731 | self.add_option('-q', '--quiet', action='store_true', |
| 732 | help='Suppress all extraneous output') |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 733 | self.add_option('--timeout', type='int', default=0, |
| 734 | help='Timeout for acquiring cache lock, in seconds') |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 735 | |
| 736 | def parse_args(self, args=None, values=None): |
| 737 | options, args = optparse.OptionParser.parse_args(self, args, values) |
szager@chromium.org | 2c391af | 2014-05-23 09:07:15 +0000 | [diff] [blame] | 738 | if options.quiet: |
| 739 | options.verbose = 0 |
| 740 | |
| 741 | levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG] |
| 742 | logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)]) |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 743 | |
| 744 | try: |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 745 | global_cache_dir = Mirror.GetCachePath() |
| 746 | except RuntimeError: |
| 747 | global_cache_dir = None |
| 748 | if options.cache_dir: |
| 749 | if global_cache_dir and ( |
| 750 | os.path.abspath(options.cache_dir) != |
| 751 | os.path.abspath(global_cache_dir)): |
| 752 | logging.warn('Overriding globally-configured cache directory.') |
| 753 | Mirror.SetCachePath(options.cache_dir) |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 754 | |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 755 | return options, args |
| 756 | |
| 757 | |
| 758 | def main(argv): |
| 759 | dispatcher = subcommand.CommandDispatcher(__name__) |
| 760 | return dispatcher.execute(OptionParser(), argv) |
| 761 | |
| 762 | |
| 763 | if __name__ == '__main__': |
sbc@chromium.org | 013731e | 2015-02-26 18:28:43 +0000 | [diff] [blame] | 764 | try: |
| 765 | sys.exit(main(sys.argv[1:])) |
| 766 | except KeyboardInterrupt: |
| 767 | sys.stderr.write('interrupted\n') |
Edward Lemur | df746d0 | 2019-07-27 00:42:46 +0000 | [diff] [blame] | 768 | sys.exit(1) |