| The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 1 | # Copyright (C) 2008 The Android Open Source Project |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | # |
| 9 | # Unless required by applicable law or agreed to in writing, software |
| 10 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | # See the License for the specific language governing permissions and |
| 13 | # limitations under the License. |
| 14 | |
| LaMont Jones | bdcba7d | 2022-04-11 22:50:11 +0000 | [diff] [blame] | 15 | import collections |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 16 | import contextlib |
| Mike Frysinger | ebf04a4 | 2021-02-23 20:48:04 -0500 | [diff] [blame] | 17 | import functools |
| Mike Frysinger | acf63b2 | 2019-06-13 02:24:21 -0400 | [diff] [blame] | 18 | import http.cookiejar as cookielib |
| Mike Frysinger | 7b586f2 | 2021-02-23 18:38:39 -0500 | [diff] [blame] | 19 | import io |
| Anthony King | 85b24ac | 2014-05-06 15:57:48 +0100 | [diff] [blame] | 20 | import json |
| Mike Frysinger | ebf04a4 | 2021-02-23 20:48:04 -0500 | [diff] [blame] | 21 | import multiprocessing |
| David Pursehouse | 86d973d | 2012-08-24 10:21:02 +0900 | [diff] [blame] | 22 | import netrc |
| Mike Frysinger | 06ddc8c | 2023-08-21 21:26:51 -0400 | [diff] [blame] | 23 | import optparse |
| The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 24 | import os |
| Josip Sokcevic | 5554572 | 2024-02-22 16:38:00 -0800 | [diff] [blame] | 25 | from pathlib import Path |
| Jason Chang | daf2ad3 | 2023-08-31 17:06:36 -0700 | [diff] [blame] | 26 | import sys |
| Dan Willemsen | 0745bb2 | 2015-08-17 13:41:45 -0700 | [diff] [blame] | 27 | import tempfile |
| Shawn O. Pearce | f690687 | 2009-04-18 10:49:00 -0700 | [diff] [blame] | 28 | import time |
| Gavin Mak | df3c401 | 2025-06-17 19:40:06 -0700 | [diff] [blame] | 29 | from typing import List, NamedTuple, Optional, Set, Tuple, Union |
| Mike Frysinger | acf63b2 | 2019-06-13 02:24:21 -0400 | [diff] [blame] | 30 | import urllib.error |
| 31 | import urllib.parse |
| 32 | import urllib.request |
| Mike Frysinger | 5951e30 | 2022-05-20 23:34:44 -0400 | [diff] [blame] | 33 | import xml.parsers.expat |
| Mike Frysinger | acf63b2 | 2019-06-13 02:24:21 -0400 | [diff] [blame] | 34 | import xmlrpc.client |
| The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 35 | |
| Mike Frysinger | 6447733 | 2023-08-21 21:20:32 -0400 | [diff] [blame] | 36 | |
| Roy Lee | 18afd7f | 2010-05-09 04:32:08 +0800 | [diff] [blame] | 37 | try: |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 38 | import threading as _threading |
| Roy Lee | 18afd7f | 2010-05-09 04:32:08 +0800 | [diff] [blame] | 39 | except ImportError: |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 40 | import dummy_threading as _threading |
| Roy Lee | 18afd7f | 2010-05-09 04:32:08 +0800 | [diff] [blame] | 41 | |
| Shawn O. Pearce | 97d2b2f | 2011-09-22 17:23:41 -0700 | [diff] [blame] | 42 | try: |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 43 | import resource |
| David Pursehouse | 819827a | 2020-02-12 15:20:19 +0900 | [diff] [blame] | 44 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 45 | def _rlimit_nofile(): |
| 46 | return resource.getrlimit(resource.RLIMIT_NOFILE) |
| 47 | |
| Shawn O. Pearce | 97d2b2f | 2011-09-22 17:23:41 -0700 | [diff] [blame] | 48 | except ImportError: |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 49 | |
| 50 | def _rlimit_nofile(): |
| 51 | return (256, 256) |
| 52 | |
| Shawn O. Pearce | 97d2b2f | 2011-09-22 17:23:41 -0700 | [diff] [blame] | 53 | |
| Mike Frysinger | 6447733 | 2023-08-21 21:20:32 -0400 | [diff] [blame] | 54 | from command import Command |
| 55 | from command import DEFAULT_LOCAL_JOBS |
| 56 | from command import MirrorSafeCommand |
| 57 | from command import WORKER_BATCH_SIZE |
| 58 | from error import GitError |
| 59 | from error import RepoChangedException |
| Jason Chang | daf2ad3 | 2023-08-31 17:06:36 -0700 | [diff] [blame] | 60 | from error import RepoError |
| Mike Frysinger | 6447733 | 2023-08-21 21:20:32 -0400 | [diff] [blame] | 61 | from error import RepoExitError |
| 62 | from error import RepoUnhandledExceptionError |
| 63 | from error import SyncError |
| 64 | from error import UpdateManifestError |
| David Riley | e0684ad | 2017-04-05 00:02:59 -0700 | [diff] [blame] | 65 | import event_log |
| Mike Frysinger | 347f9ed | 2021-03-15 14:58:52 -0400 | [diff] [blame] | 66 | from git_command import git_require |
| David Pursehouse | ba7bc73 | 2015-08-20 16:55:42 +0900 | [diff] [blame] | 67 | from git_config import GetUrlCookieFile |
| Mike Frysinger | 6447733 | 2023-08-21 21:20:32 -0400 | [diff] [blame] | 68 | from git_refs import HEAD |
| 69 | from git_refs import R_HEADS |
| Raman Tenneti | 6a872c9 | 2021-01-14 19:17:50 -0800 | [diff] [blame] | 70 | import git_superproject |
| Kenny Cheng | 82d500e | 2025-06-02 21:55:04 +0800 | [diff] [blame] | 71 | from hooks import RepoHook |
| Mike Frysinger | 6447733 | 2023-08-21 21:20:32 -0400 | [diff] [blame] | 72 | import platform_utils |
| 73 | from progress import elapsed_str |
| 74 | from progress import jobs_str |
| 75 | from progress import Progress |
| 76 | from project import DeleteWorktreeError |
| Jaikumar Ganesh | 4f2517f | 2009-06-01 21:10:33 -0700 | [diff] [blame] | 77 | from project import Project |
| 78 | from project import RemoteSpec |
| Mike Frysinger | 6447733 | 2023-08-21 21:20:32 -0400 | [diff] [blame] | 79 | from project import SyncBuffer |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 80 | from repo_logging import RepoLogger |
| Joanna Wang | a6c52f5 | 2022-11-03 16:51:19 -0400 | [diff] [blame] | 81 | from repo_trace import Trace |
| Mike Frysinger | 19e409c | 2021-05-05 19:44:35 -0400 | [diff] [blame] | 82 | import ssh |
| Conley Owens | 094cdbe | 2014-01-30 15:09:59 -0800 | [diff] [blame] | 83 | from wrapper import Wrapper |
| The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 84 | |
| Mike Frysinger | 6447733 | 2023-08-21 21:20:32 -0400 | [diff] [blame] | 85 | |
| Dave Borowitz | 67700e9 | 2012-10-23 15:00:54 -0700 | [diff] [blame] | 86 | _ONE_DAY_S = 24 * 60 * 60 |
| 87 | |
| Jason Chang | 1783332 | 2023-05-23 13:06:55 -0700 | [diff] [blame] | 88 | _REPO_ALLOW_SHALLOW = os.environ.get("REPO_ALLOW_SHALLOW") |
| 89 | |
| Gavin Mak | b5991d7 | 2025-12-09 22:29:43 +0000 | [diff] [blame] | 90 | _BLOAT_PACK_COUNT_THRESHOLD = 10 |
| 91 | _BLOAT_SIZE_PACK_THRESHOLD_KB = 10 * 1024 * 1024 # 10 GiB in KiB |
| 92 | _BLOAT_SIZE_GARBAGE_THRESHOLD_KB = 1 * 1024 * 1024 # 1 GiB in KiB |
| 93 | |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 94 | logger = RepoLogger(__file__) |
| 95 | |
| David Pursehouse | 819827a | 2020-02-12 15:20:19 +0900 | [diff] [blame] | 96 | |
| Josip Sokcevic | 5554572 | 2024-02-22 16:38:00 -0800 | [diff] [blame] | 97 | def _SafeCheckoutOrder(checkouts: List[Project]) -> List[List[Project]]: |
| 98 | """Generate a sequence of checkouts that is safe to perform. The client |
| 99 | should checkout everything from n-th index before moving to n+1. |
| 100 | |
| 101 | This is only useful if manifest contains nested projects. |
| 102 | |
| 103 | E.g. if foo, foo/bar and foo/bar/baz are project paths, then foo needs to |
| 104 | finish before foo/bar can proceed, and foo/bar needs to finish before |
| 105 | foo/bar/baz.""" |
| 106 | res = [[]] |
| 107 | current = res[0] |
| 108 | |
| 109 | # depth_stack contains a current stack of parent paths. |
| 110 | depth_stack = [] |
| Josip Sokcevic | 4679022 | 2024-03-07 22:18:58 +0000 | [diff] [blame] | 111 | # Checkouts are iterated in the hierarchical order. That way, it can easily |
| 112 | # be determined if the previous checkout is parent of the current checkout. |
| 113 | # We are splitting by the path separator so the final result is |
| 114 | # hierarchical, and not just lexicographical. For example, if the projects |
| 115 | # are: foo, foo/bar, foo-bar, lexicographical order produces foo, foo-bar |
| 116 | # and foo/bar, which doesn't work. |
| 117 | for checkout in sorted(checkouts, key=lambda x: x.relpath.split("/")): |
| Josip Sokcevic | 5554572 | 2024-02-22 16:38:00 -0800 | [diff] [blame] | 118 | checkout_path = Path(checkout.relpath) |
| 119 | while depth_stack: |
| 120 | try: |
| 121 | checkout_path.relative_to(depth_stack[-1]) |
| 122 | except ValueError: |
| 123 | # Path.relative_to returns ValueError if paths are not relative. |
| 124 | # TODO(sokcevic): Switch to is_relative_to once min supported |
| 125 | # version is py3.9. |
| 126 | depth_stack.pop() |
| 127 | else: |
| 128 | if len(depth_stack) >= len(res): |
| 129 | # Another depth created. |
| 130 | res.append([]) |
| 131 | break |
| 132 | |
| 133 | current = res[len(depth_stack)] |
| 134 | current.append(checkout) |
| 135 | depth_stack.append(checkout_path) |
| 136 | |
| 137 | return res |
| 138 | |
| 139 | |
| Josip Sokcevic | 454fdaf | 2024-10-07 17:33:38 +0000 | [diff] [blame] | 140 | def _chunksize(projects: int, jobs: int) -> int: |
| 141 | """Calculate chunk size for the given number of projects and jobs.""" |
| 142 | return min(max(1, projects // jobs), WORKER_BATCH_SIZE) |
| 143 | |
| 144 | |
| LaMont Jones | 1eddca8 | 2022-09-01 15:15:04 +0000 | [diff] [blame] | 145 | class _FetchOneResult(NamedTuple): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 146 | """_FetchOne return value. |
| LaMont Jones | 1eddca8 | 2022-09-01 15:15:04 +0000 | [diff] [blame] | 147 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 148 | Attributes: |
| 149 | success (bool): True if successful. |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 150 | project_idx (int): The fetched project index. |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 151 | start (float): The starting time.time(). |
| 152 | finish (float): The ending time.time(). |
| 153 | remote_fetched (bool): True if the remote was actually queried. |
| 154 | """ |
| 155 | |
| 156 | success: bool |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 157 | errors: List[Exception] |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 158 | project_idx: int |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 159 | start: float |
| 160 | finish: float |
| 161 | remote_fetched: bool |
| LaMont Jones | 1eddca8 | 2022-09-01 15:15:04 +0000 | [diff] [blame] | 162 | |
| 163 | |
| 164 | class _FetchResult(NamedTuple): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 165 | """_Fetch return value. |
| LaMont Jones | 1eddca8 | 2022-09-01 15:15:04 +0000 | [diff] [blame] | 166 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 167 | Attributes: |
| 168 | success (bool): True if successful. |
| 169 | projects (Set[str]): The names of the git directories of fetched projects. |
| 170 | """ |
| 171 | |
| 172 | success: bool |
| 173 | projects: Set[str] |
| LaMont Jones | 1eddca8 | 2022-09-01 15:15:04 +0000 | [diff] [blame] | 174 | |
| 175 | |
| 176 | class _FetchMainResult(NamedTuple): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 177 | """_FetchMain return value. |
| LaMont Jones | 1eddca8 | 2022-09-01 15:15:04 +0000 | [diff] [blame] | 178 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 179 | Attributes: |
| 180 | all_projects (List[Project]): The fetched projects. |
| 181 | """ |
| 182 | |
| 183 | all_projects: List[Project] |
| LaMont Jones | 1eddca8 | 2022-09-01 15:15:04 +0000 | [diff] [blame] | 184 | |
| 185 | |
| 186 | class _CheckoutOneResult(NamedTuple): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 187 | """_CheckoutOne return value. |
| LaMont Jones | 1eddca8 | 2022-09-01 15:15:04 +0000 | [diff] [blame] | 188 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 189 | Attributes: |
| 190 | success (bool): True if successful. |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 191 | project_idx (int): The project index. |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 192 | start (float): The starting time.time(). |
| 193 | finish (float): The ending time.time(). |
| 194 | """ |
| 195 | |
| 196 | success: bool |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 197 | errors: List[Exception] |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 198 | project_idx: int |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 199 | start: float |
| 200 | finish: float |
| LaMont Jones | 1eddca8 | 2022-09-01 15:15:04 +0000 | [diff] [blame] | 201 | |
| 202 | |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 203 | class _SyncResult(NamedTuple): |
| 204 | """Individual project sync result for interleaved mode. |
| 205 | |
| 206 | Attributes: |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 207 | project_index (int): The index of the project in the shared list. |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 208 | relpath (str): The project's relative path from the repo client top. |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 209 | remote_fetched (bool): True if the remote was actually queried. |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 210 | fetch_success (bool): True if the fetch operation was successful. |
| Gavin Mak | d534a55 | 2025-08-13 23:42:00 -0700 | [diff] [blame] | 211 | fetch_errors (List[Exception]): The Exceptions from a failed fetch. |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 212 | fetch_start (Optional[float]): The time.time() when fetch started. |
| 213 | fetch_finish (Optional[float]): The time.time() when fetch finished. |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 214 | checkout_success (bool): True if the checkout operation was |
| 215 | successful. |
| Gavin Mak | d534a55 | 2025-08-13 23:42:00 -0700 | [diff] [blame] | 216 | checkout_errors (List[Exception]): The Exceptions from a failed |
| 217 | checkout. |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 218 | checkout_start (Optional[float]): The time.time() when checkout |
| 219 | started. |
| 220 | checkout_finish (Optional[float]): The time.time() when checkout |
| 221 | finished. |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 222 | stderr_text (str): The combined output from both fetch and checkout. |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 223 | """ |
| 224 | |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 225 | project_index: int |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 226 | relpath: str |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 227 | |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 228 | remote_fetched: bool |
| 229 | fetch_success: bool |
| Gavin Mak | d534a55 | 2025-08-13 23:42:00 -0700 | [diff] [blame] | 230 | fetch_errors: List[Exception] |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 231 | fetch_start: Optional[float] |
| 232 | fetch_finish: Optional[float] |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 233 | |
| 234 | checkout_success: bool |
| Gavin Mak | d534a55 | 2025-08-13 23:42:00 -0700 | [diff] [blame] | 235 | checkout_errors: List[Exception] |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 236 | checkout_start: Optional[float] |
| 237 | checkout_finish: Optional[float] |
| 238 | |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 239 | stderr_text: str |
| 240 | |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 241 | |
| 242 | class _InterleavedSyncResult(NamedTuple): |
| 243 | """Result of an interleaved sync. |
| 244 | |
| 245 | Attributes: |
| 246 | results (List[_SyncResult]): A list of results, one for each project |
| 247 | processed. Empty if the worker failed before creating results. |
| 248 | """ |
| 249 | |
| 250 | results: List[_SyncResult] |
| 251 | |
| 252 | |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 253 | class SuperprojectError(SyncError): |
| 254 | """Superproject sync repo.""" |
| 255 | |
| 256 | |
| 257 | class SyncFailFastError(SyncError): |
| 258 | """Sync exit error when --fail-fast set.""" |
| 259 | |
| 260 | |
| 261 | class SmartSyncError(SyncError): |
| 262 | """Smart sync exit error.""" |
| 263 | |
| 264 | |
| Jason Chang | daf2ad3 | 2023-08-31 17:06:36 -0700 | [diff] [blame] | 265 | class ManifestInterruptError(RepoError): |
| 266 | """Aggregate Error to be logged when a user interrupts a manifest update.""" |
| 267 | |
| 268 | def __init__(self, output, **kwargs): |
| 269 | super().__init__(output, **kwargs) |
| 270 | self.output = output |
| 271 | |
| 272 | def __str__(self): |
| 273 | error_type = type(self).__name__ |
| 274 | return f"{error_type}:{self.output}" |
| 275 | |
| 276 | |
| 277 | class TeeStringIO(io.StringIO): |
| 278 | """StringIO class that can write to an additional destination.""" |
| 279 | |
| 280 | def __init__( |
| 281 | self, io: Union[io.TextIOWrapper, None], *args, **kwargs |
| 282 | ) -> None: |
| 283 | super().__init__(*args, **kwargs) |
| 284 | self.io = io |
| 285 | |
| 286 | def write(self, s: str) -> int: |
| 287 | """Write to additional destination.""" |
| Daniel Kutik | b0430b5 | 2023-10-23 21:16:04 +0200 | [diff] [blame] | 288 | ret = super().write(s) |
| Jason Chang | daf2ad3 | 2023-08-31 17:06:36 -0700 | [diff] [blame] | 289 | if self.io is not None: |
| 290 | self.io.write(s) |
| Daniel Kutik | b0430b5 | 2023-10-23 21:16:04 +0200 | [diff] [blame] | 291 | return ret |
| Jason Chang | daf2ad3 | 2023-08-31 17:06:36 -0700 | [diff] [blame] | 292 | |
| 293 | |
| Shawn O. Pearce | c95583b | 2009-03-03 17:47:06 -0800 | [diff] [blame] | 294 | class Sync(Command, MirrorSafeCommand): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 295 | COMMON = True |
| 296 | MULTI_MANIFEST_SUPPORT = True |
| 297 | helpSummary = "Update working tree to the latest revision" |
| 298 | helpUsage = """ |
| The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 299 | %prog [<project>...] |
| 300 | """ |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 301 | helpDescription = """ |
| The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 302 | The '%prog' command synchronizes local project directories |
| 303 | with the remote repositories specified in the manifest. If a local |
| 304 | project does not yet exist, it will clone a new local directory from |
| 305 | the remote repository and set up tracking branches as specified in |
| 306 | the manifest. If the local project already exists, '%prog' |
| 307 | will update the remote branches and rebase any new local changes |
| 308 | on top of the new remote changes. |
| 309 | |
| 310 | '%prog' will synchronize all projects listed at the command |
| 311 | line. Projects can be specified either by name, or by a relative |
| 312 | or absolute path to the project's local directory. If no projects |
| 313 | are specified, '%prog' will synchronize all projects listed in |
| 314 | the manifest. |
| Shawn O. Pearce | 3e768c9 | 2009-04-10 16:59:36 -0700 | [diff] [blame] | 315 | |
| 316 | The -d/--detach option can be used to switch specified projects |
| 317 | back to the manifest revision. This option is especially helpful |
| 318 | if the project is currently on a topic branch, but the manifest |
| 319 | revision is temporarily needed. |
| Shawn O. Pearce | eb7af87 | 2009-04-21 08:02:04 -0700 | [diff] [blame] | 320 | |
| Nico Sallembien | a1bfd2c | 2010-04-06 10:40:01 -0700 | [diff] [blame] | 321 | The -s/--smart-sync option can be used to sync to a known good |
| 322 | build as specified by the manifest-server element in the current |
| Victor Boivie | 08c880d | 2011-04-19 10:32:52 +0200 | [diff] [blame] | 323 | manifest. The -t/--smart-tag option is similar and allows you to |
| 324 | specify a custom tag/label. |
| Nico Sallembien | a1bfd2c | 2010-04-06 10:40:01 -0700 | [diff] [blame] | 325 | |
| David Pursehouse | cf76b1b | 2012-09-14 10:31:42 +0900 | [diff] [blame] | 326 | The -u/--manifest-server-username and -p/--manifest-server-password |
| 327 | options can be used to specify a username and password to authenticate |
| 328 | with the manifest server when using the -s or -t option. |
| 329 | |
| 330 | If -u and -p are not specified when using the -s or -t option, '%prog' |
| 331 | will attempt to read authentication credentials for the manifest server |
| 332 | from the user's .netrc file. |
| 333 | |
| 334 | '%prog' will not use authentication credentials from -u/-p or .netrc |
| 335 | if the manifest server specified in the manifest file already includes |
| 336 | credentials. |
| 337 | |
| Mike Frysinger | d9e5cf0 | 2019-08-26 03:12:55 -0400 | [diff] [blame] | 338 | By default, all projects will be synced. The --fail-fast option can be used |
| Mike Frysinger | 7ae210a | 2020-05-24 14:56:52 -0400 | [diff] [blame] | 339 | to halt syncing as soon as possible when the first project fails to sync. |
| Andrei Warkentin | 5df6de0 | 2010-07-02 17:58:31 -0500 | [diff] [blame] | 340 | |
| Kevin Degi | abaa7f3 | 2014-11-12 11:27:45 -0700 | [diff] [blame] | 341 | The --force-sync option can be used to overwrite existing git |
| 342 | directories if they have previously been linked to a different |
| Roger Shimizu | ac29ac3 | 2020-06-06 02:33:40 +0900 | [diff] [blame] | 343 | object directory. WARNING: This may cause data to be lost since |
| Kevin Degi | abaa7f3 | 2014-11-12 11:27:45 -0700 | [diff] [blame] | 344 | refs may be removed when overwriting. |
| 345 | |
| Josip Sokcevic | edadb25 | 2024-02-29 09:48:37 -0800 | [diff] [blame] | 346 | The --force-checkout option can be used to force git to switch revs even if the |
| 347 | index or the working tree differs from HEAD, and if there are untracked files. |
| 348 | WARNING: This may cause data to be lost since uncommitted changes may be |
| 349 | removed. |
| 350 | |
| Oleksii Okolielov | d3c0f59 | 2018-12-17 19:23:44 -0500 | [diff] [blame] | 351 | The --force-remove-dirty option can be used to remove previously used |
| 352 | projects with uncommitted changes. WARNING: This may cause data to be |
| 353 | lost since uncommitted changes may be removed with projects that no longer |
| 354 | exist in the manifest. |
| 355 | |
| Shawn O. Pearce | e02ac0a | 2012-03-14 15:36:59 -0700 | [diff] [blame] | 356 | The --no-clone-bundle option disables any attempt to use |
| 357 | $URL/clone.bundle to bootstrap a new Git repository from a |
| 358 | resumeable bundle file on a content delivery network. This |
| 359 | may be necessary if there are problems with the local Python |
| 360 | HTTP client or proxy configuration, but the Git binary works. |
| 361 | |
| Che-Liang Chiou | b2bd91c | 2012-01-11 11:28:42 +0800 | [diff] [blame] | 362 | The --fetch-submodules option enables fetching Git submodules |
| 363 | of a project from server. |
| 364 | |
| David Pursehouse | f2fad61 | 2015-01-29 14:36:28 +0900 | [diff] [blame] | 365 | The -c/--current-branch option can be used to only fetch objects that |
| 366 | are on the branch specified by a project's revision. |
| 367 | |
| David Pursehouse | b155354 | 2014-09-04 21:28:09 +0900 | [diff] [blame] | 368 | The --optimized-fetch option can be used to only fetch projects that |
| 369 | are fixed to a sha1 revision if the sha1 revision does not already |
| 370 | exist locally. |
| 371 | |
| David Pursehouse | 74cfd27 | 2015-10-14 10:50:15 +0900 | [diff] [blame] | 372 | The --prune option can be used to remove any refs that no longer |
| 373 | exist on the remote. |
| 374 | |
| LaMont Jones | 7efab53 | 2022-09-01 15:41:12 +0000 | [diff] [blame] | 375 | The --auto-gc option can be used to trigger garbage collection on all |
| 376 | projects. By default, repo does not run garbage collection. |
| 377 | |
| Mike Frysinger | b8f7bb0 | 2018-10-10 01:05:11 -0400 | [diff] [blame] | 378 | # SSH Connections |
| Shawn O. Pearce | eb7af87 | 2009-04-21 08:02:04 -0700 | [diff] [blame] | 379 | |
| 380 | If at least one project remote URL uses an SSH connection (ssh://, |
| 381 | git+ssh://, or user@host:path syntax) repo will automatically |
| 382 | enable the SSH ControlMaster option when connecting to that host. |
| 383 | This feature permits other projects in the same '%prog' session to |
| 384 | reuse the same SSH tunnel, saving connection setup overheads. |
| 385 | |
| 386 | To disable this behavior on UNIX platforms, set the GIT_SSH |
| 387 | environment variable to 'ssh'. For example: |
| 388 | |
| 389 | export GIT_SSH=ssh |
| 390 | %prog |
| 391 | |
| Mike Frysinger | b8f7bb0 | 2018-10-10 01:05:11 -0400 | [diff] [blame] | 392 | # Compatibility |
| Shawn O. Pearce | eb7af87 | 2009-04-21 08:02:04 -0700 | [diff] [blame] | 393 | |
| 394 | This feature is automatically disabled on Windows, due to the lack |
| 395 | of UNIX domain socket support. |
| 396 | |
| 397 | This feature is not compatible with url.insteadof rewrites in the |
| 398 | user's ~/.gitconfig. '%prog' is currently not able to perform the |
| 399 | rewrite early enough to establish the ControlMaster tunnel. |
| 400 | |
| 401 | If the remote SSH daemon is Gerrit Code Review, version 2.0.10 or |
| 402 | later is required to fix a server side protocol bug. |
| 403 | |
| The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 404 | """ |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 405 | # A value of 0 means we want parallel jobs, but we'll determine the default |
| 406 | # value later on. |
| 407 | PARALLEL_JOBS = 0 |
| Shawn O. Pearce | 6392c87 | 2011-09-22 17:44:31 -0700 | [diff] [blame] | 408 | |
| Gavin Mak | daebd6c | 2025-04-09 13:59:27 -0700 | [diff] [blame] | 409 | _JOBS_WARN_THRESHOLD = 100 |
| 410 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 411 | def _Options(self, p, show_smart=True): |
| 412 | p.add_option( |
| 413 | "--jobs-network", |
| 414 | default=None, |
| 415 | type=int, |
| 416 | metavar="JOBS", |
| 417 | help="number of network jobs to run in parallel (defaults to " |
| Gavin Mak | 25858c8 | 2025-07-21 12:24:41 -0700 | [diff] [blame] | 418 | "--jobs or 1). Ignored unless --no-interleaved is set", |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 419 | ) |
| 420 | p.add_option( |
| 421 | "--jobs-checkout", |
| 422 | default=None, |
| 423 | type=int, |
| 424 | metavar="JOBS", |
| Gavin Mak | 25858c8 | 2025-07-21 12:24:41 -0700 | [diff] [blame] | 425 | help=( |
| 426 | "number of local checkout jobs to run in parallel (defaults " |
| 427 | f"to --jobs or {DEFAULT_LOCAL_JOBS}). Ignored unless " |
| 428 | "--no-interleaved is set" |
| 429 | ), |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 430 | ) |
| Mike Frysinger | 49de8ef | 2021-04-09 00:21:02 -0400 | [diff] [blame] | 431 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 432 | p.add_option( |
| 433 | "-f", |
| 434 | "--force-broken", |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 435 | action="store_true", |
| 436 | help="obsolete option (to be deleted in the future)", |
| 437 | ) |
| 438 | p.add_option( |
| 439 | "--fail-fast", |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 440 | action="store_true", |
| 441 | help="stop syncing after first error is hit", |
| 442 | ) |
| 443 | p.add_option( |
| 444 | "--force-sync", |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 445 | action="store_true", |
| 446 | help="overwrite an existing git directory if it needs to " |
| 447 | "point to a different object directory. WARNING: this " |
| 448 | "may cause loss of data", |
| 449 | ) |
| 450 | p.add_option( |
| Josip Sokcevic | edadb25 | 2024-02-29 09:48:37 -0800 | [diff] [blame] | 451 | "--force-checkout", |
| Josip Sokcevic | edadb25 | 2024-02-29 09:48:37 -0800 | [diff] [blame] | 452 | action="store_true", |
| 453 | help="force checkout even if it results in throwing away " |
| 454 | "uncommitted modifications. " |
| 455 | "WARNING: this may cause loss of data", |
| 456 | ) |
| 457 | p.add_option( |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 458 | "--force-remove-dirty", |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 459 | action="store_true", |
| 460 | help="force remove projects with uncommitted modifications if " |
| 461 | "projects no longer exist in the manifest. " |
| 462 | "WARNING: this may cause loss of data", |
| 463 | ) |
| 464 | p.add_option( |
| Jeroen Dhollander | c44ad09 | 2024-08-20 10:28:41 +0200 | [diff] [blame] | 465 | "--rebase", |
| Jeroen Dhollander | c44ad09 | 2024-08-20 10:28:41 +0200 | [diff] [blame] | 466 | action="store_true", |
| 467 | help="rebase local commits regardless of whether they are " |
| 468 | "published", |
| 469 | ) |
| 470 | p.add_option( |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 471 | "-l", |
| 472 | "--local-only", |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 473 | action="store_true", |
| 474 | help="only update working tree, don't fetch", |
| 475 | ) |
| 476 | p.add_option( |
| 477 | "--no-manifest-update", |
| 478 | "--nmu", |
| 479 | dest="mp_update", |
| 480 | action="store_false", |
| 481 | default="true", |
| 482 | help="use the existing manifest checkout as-is. " |
| 483 | "(do not update to the latest revision)", |
| 484 | ) |
| 485 | p.add_option( |
| Gavin Mak | 8535282 | 2025-06-11 00:13:52 +0000 | [diff] [blame] | 486 | "--interleaved", |
| 487 | action="store_true", |
| Gavin Mak | 25858c8 | 2025-07-21 12:24:41 -0700 | [diff] [blame] | 488 | default=True, |
| 489 | help="fetch and checkout projects in parallel (default)", |
| 490 | ) |
| 491 | p.add_option( |
| 492 | "--no-interleaved", |
| 493 | dest="interleaved", |
| 494 | action="store_false", |
| 495 | help="fetch and checkout projects in phases", |
| Gavin Mak | 8535282 | 2025-06-11 00:13:52 +0000 | [diff] [blame] | 496 | ) |
| 497 | p.add_option( |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 498 | "-n", |
| 499 | "--network-only", |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 500 | action="store_true", |
| 501 | help="fetch only, don't update working tree", |
| 502 | ) |
| 503 | p.add_option( |
| 504 | "-d", |
| 505 | "--detach", |
| 506 | dest="detach_head", |
| 507 | action="store_true", |
| 508 | help="detach projects back to manifest revision", |
| 509 | ) |
| 510 | p.add_option( |
| 511 | "-c", |
| 512 | "--current-branch", |
| 513 | dest="current_branch_only", |
| 514 | action="store_true", |
| 515 | help="fetch only current branch from server", |
| 516 | ) |
| 517 | p.add_option( |
| 518 | "--no-current-branch", |
| 519 | dest="current_branch_only", |
| 520 | action="store_false", |
| 521 | help="fetch all branches from server", |
| 522 | ) |
| 523 | p.add_option( |
| 524 | "-m", |
| 525 | "--manifest-name", |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 526 | help="temporary manifest to use for this sync", |
| 527 | metavar="NAME.xml", |
| 528 | ) |
| 529 | p.add_option( |
| 530 | "--clone-bundle", |
| 531 | action="store_true", |
| 532 | help="enable use of /clone.bundle on HTTP/HTTPS", |
| 533 | ) |
| 534 | p.add_option( |
| 535 | "--no-clone-bundle", |
| 536 | dest="clone_bundle", |
| 537 | action="store_false", |
| 538 | help="disable use of /clone.bundle on HTTP/HTTPS", |
| 539 | ) |
| 540 | p.add_option( |
| 541 | "-u", |
| 542 | "--manifest-server-username", |
| 543 | action="store", |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 544 | help="username to authenticate with the manifest server", |
| 545 | ) |
| 546 | p.add_option( |
| 547 | "-p", |
| 548 | "--manifest-server-password", |
| 549 | action="store", |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 550 | help="password to authenticate with the manifest server", |
| 551 | ) |
| 552 | p.add_option( |
| 553 | "--fetch-submodules", |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 554 | action="store_true", |
| 555 | help="fetch submodules from server", |
| 556 | ) |
| 557 | p.add_option( |
| 558 | "--use-superproject", |
| 559 | action="store_true", |
| 560 | help="use the manifest superproject to sync projects; implies -c", |
| 561 | ) |
| 562 | p.add_option( |
| 563 | "--no-use-superproject", |
| 564 | action="store_false", |
| 565 | dest="use_superproject", |
| 566 | help="disable use of manifest superprojects", |
| 567 | ) |
| 568 | p.add_option("--tags", action="store_true", help="fetch tags") |
| 569 | p.add_option( |
| 570 | "--no-tags", |
| 571 | dest="tags", |
| 572 | action="store_false", |
| 573 | help="don't fetch tags (default)", |
| 574 | ) |
| 575 | p.add_option( |
| 576 | "--optimized-fetch", |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 577 | action="store_true", |
| 578 | help="only fetch projects fixed to sha1 if revision does not exist " |
| 579 | "locally", |
| 580 | ) |
| 581 | p.add_option( |
| 582 | "--retry-fetches", |
| 583 | default=0, |
| 584 | action="store", |
| 585 | type="int", |
| 586 | help="number of times to retry fetches on transient errors", |
| 587 | ) |
| 588 | p.add_option( |
| 589 | "--prune", |
| 590 | action="store_true", |
| 591 | help="delete refs that no longer exist on the remote (default)", |
| 592 | ) |
| 593 | p.add_option( |
| 594 | "--no-prune", |
| 595 | dest="prune", |
| 596 | action="store_false", |
| 597 | help="do not delete refs that no longer exist on the remote", |
| 598 | ) |
| 599 | p.add_option( |
| 600 | "--auto-gc", |
| 601 | action="store_true", |
| 602 | default=None, |
| 603 | help="run garbage collection on all synced projects", |
| 604 | ) |
| 605 | p.add_option( |
| 606 | "--no-auto-gc", |
| 607 | dest="auto_gc", |
| 608 | action="store_false", |
| 609 | help="do not run garbage collection on any projects (default)", |
| 610 | ) |
| 611 | if show_smart: |
| 612 | p.add_option( |
| 613 | "-s", |
| 614 | "--smart-sync", |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 615 | action="store_true", |
| 616 | help="smart sync using manifest from the latest known good " |
| 617 | "build", |
| 618 | ) |
| 619 | p.add_option( |
| 620 | "-t", |
| 621 | "--smart-tag", |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 622 | action="store", |
| 623 | help="smart sync using manifest from a known tag", |
| 624 | ) |
| Shawn O. Pearce | 3e768c9 | 2009-04-10 16:59:36 -0700 | [diff] [blame] | 625 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 626 | g = p.add_option_group("repo Version options") |
| 627 | g.add_option( |
| 628 | "--no-repo-verify", |
| 629 | dest="repo_verify", |
| 630 | default=True, |
| 631 | action="store_false", |
| 632 | help="do not verify repo source code", |
| 633 | ) |
| 634 | g.add_option( |
| 635 | "--repo-upgraded", |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 636 | action="store_true", |
| Mike Frysinger | 06ddc8c | 2023-08-21 21:26:51 -0400 | [diff] [blame] | 637 | help=optparse.SUPPRESS_HELP, |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 638 | ) |
| Kenny Cheng | 82d500e | 2025-06-02 21:55:04 +0800 | [diff] [blame] | 639 | RepoHook.AddOptionGroup(p, "post-sync") |
| The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 640 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 641 | def _GetBranch(self, manifest_project): |
| 642 | """Returns the branch name for getting the approved smartsync manifest. |
| LaMont Jones | a46047a | 2022-04-07 21:57:06 +0000 | [diff] [blame] | 643 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 644 | Args: |
| 645 | manifest_project: The manifestProject to query. |
| 646 | """ |
| 647 | b = manifest_project.GetBranch(manifest_project.CurrentBranch) |
| 648 | branch = b.merge |
| 649 | if branch.startswith(R_HEADS): |
| 650 | branch = branch[len(R_HEADS) :] |
| 651 | return branch |
| Raman Tenneti | 8d43dea | 2021-02-07 16:30:27 -0800 | [diff] [blame] | 652 | |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 653 | @classmethod |
| 654 | def _GetCurrentBranchOnly(cls, opt, manifest): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 655 | """Returns whether current-branch or use-superproject options are |
| 656 | enabled. |
| Daniel Andersson | d52ca42 | 2022-04-01 12:55:38 +0200 | [diff] [blame] | 657 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 658 | Args: |
| 659 | opt: Program options returned from optparse. See _Options(). |
| 660 | manifest: The manifest to use. |
| LaMont Jones | a46047a | 2022-04-07 21:57:06 +0000 | [diff] [blame] | 661 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 662 | Returns: |
| 663 | True if a superproject is requested, otherwise the value of the |
| 664 | current_branch option (True, False or None). |
| 665 | """ |
| 666 | return ( |
| 667 | git_superproject.UseSuperproject(opt.use_superproject, manifest) |
| 668 | or opt.current_branch_only |
| 669 | ) |
| Raman Tenneti | 2ae44d7 | 2021-03-23 15:12:27 -0700 | [diff] [blame] | 670 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 671 | def _UpdateProjectsRevisionId( |
| 672 | self, opt, args, superproject_logging_data, manifest |
| 673 | ): |
| 674 | """Update revisionId of projects with the commit from the superproject. |
| Raman Tenneti | 1fd7bc2 | 2021-02-04 14:39:38 -0800 | [diff] [blame] | 675 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 676 | This function updates each project's revisionId with the commit hash |
| 677 | from the superproject. It writes the updated manifest into a file and |
| 678 | reloads the manifest from it. When appropriate, sub manifests are also |
| 679 | processed. |
| Raman Tenneti | 1fd7bc2 | 2021-02-04 14:39:38 -0800 | [diff] [blame] | 680 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 681 | Args: |
| 682 | opt: Program options returned from optparse. See _Options(). |
| 683 | args: Arguments to pass to GetProjects. See the GetProjects |
| 684 | docstring for details. |
| 685 | superproject_logging_data: A dictionary of superproject data to log. |
| 686 | manifest: The manifest to use. |
| 687 | """ |
| 688 | have_superproject = manifest.superproject or any( |
| 689 | m.superproject for m in manifest.all_children |
| 690 | ) |
| 691 | if not have_superproject: |
| 692 | return |
| LaMont Jones | bdcba7d | 2022-04-11 22:50:11 +0000 | [diff] [blame] | 693 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 694 | if opt.local_only and manifest.superproject: |
| 695 | manifest_path = manifest.superproject.manifest_path |
| 696 | if manifest_path: |
| 697 | self._ReloadManifest(manifest_path, manifest) |
| 698 | return |
| Raman Tenneti | ae86a46 | 2021-07-27 08:54:59 -0700 | [diff] [blame] | 699 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 700 | all_projects = self.GetProjects( |
| 701 | args, |
| 702 | missing_ok=True, |
| 703 | submodules_ok=opt.fetch_submodules, |
| 704 | manifest=manifest, |
| 705 | all_manifests=not opt.this_manifest_only, |
| 706 | ) |
| LaMont Jones | bdcba7d | 2022-04-11 22:50:11 +0000 | [diff] [blame] | 707 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 708 | per_manifest = collections.defaultdict(list) |
| 709 | if opt.this_manifest_only: |
| 710 | per_manifest[manifest.path_prefix] = all_projects |
| 711 | else: |
| 712 | for p in all_projects: |
| 713 | per_manifest[p.manifest.path_prefix].append(p) |
| LaMont Jones | bdcba7d | 2022-04-11 22:50:11 +0000 | [diff] [blame] | 714 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 715 | superproject_logging_data = {} |
| 716 | need_unload = False |
| 717 | for m in self.ManifestList(opt): |
| 718 | if m.path_prefix not in per_manifest: |
| 719 | continue |
| 720 | use_super = git_superproject.UseSuperproject( |
| 721 | opt.use_superproject, m |
| 722 | ) |
| 723 | if superproject_logging_data: |
| 724 | superproject_logging_data["multimanifest"] = True |
| 725 | superproject_logging_data.update( |
| 726 | superproject=use_super, |
| 727 | haslocalmanifests=bool(m.HasLocalManifests), |
| 728 | hassuperprojecttag=bool(m.superproject), |
| 729 | ) |
| 730 | if use_super and (m.IsMirror or m.IsArchive): |
| 731 | # Don't use superproject, because we have no working tree. |
| 732 | use_super = False |
| 733 | superproject_logging_data["superproject"] = False |
| 734 | superproject_logging_data["noworktree"] = True |
| 735 | if opt.use_superproject is not False: |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 736 | logger.warning( |
| 737 | "%s: not using superproject because there is no " |
| 738 | "working tree.", |
| 739 | m.path_prefix, |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 740 | ) |
| LaMont Jones | bdcba7d | 2022-04-11 22:50:11 +0000 | [diff] [blame] | 741 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 742 | if not use_super: |
| 743 | continue |
| Tomasz Wasilczyk | 208f344 | 2024-01-05 12:23:10 -0800 | [diff] [blame] | 744 | m.superproject.SetQuiet(not opt.verbose) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 745 | print_messages = git_superproject.PrintMessages( |
| 746 | opt.use_superproject, m |
| 747 | ) |
| 748 | m.superproject.SetPrintMessages(print_messages) |
| 749 | update_result = m.superproject.UpdateProjectsRevisionId( |
| 750 | per_manifest[m.path_prefix], git_event_log=self.git_event_log |
| 751 | ) |
| 752 | manifest_path = update_result.manifest_path |
| 753 | superproject_logging_data["updatedrevisionid"] = bool(manifest_path) |
| 754 | if manifest_path: |
| 755 | m.SetManifestOverride(manifest_path) |
| 756 | need_unload = True |
| 757 | else: |
| 758 | if print_messages: |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 759 | logger.warning( |
| 760 | "%s: warning: Update of revisionId from superproject " |
| 761 | "has failed, repo sync will not use superproject to " |
| 762 | "fetch the source. Please resync with the " |
| 763 | "--no-use-superproject option to avoid this repo " |
| 764 | "warning.", |
| 765 | m.path_prefix, |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 766 | ) |
| 767 | if update_result.fatal and opt.use_superproject is not None: |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 768 | raise SuperprojectError() |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 769 | if need_unload: |
| 770 | m.outer_client.manifest.Unload() |
| Raman Tenneti | 1fd7bc2 | 2021-02-04 14:39:38 -0800 | [diff] [blame] | 771 | |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 772 | @classmethod |
| 773 | def _FetchProjectList(cls, opt, projects): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 774 | """Main function of the fetch worker. |
| Mike Frysinger | b2fa30a | 2021-02-24 00:15:32 -0500 | [diff] [blame] | 775 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 776 | The projects we're given share the same underlying git object store, so |
| 777 | we have to fetch them in serial. |
| Roy Lee | 18afd7f | 2010-05-09 04:32:08 +0800 | [diff] [blame] | 778 | |
| Gavin Mak | 551285f | 2023-05-04 04:48:43 +0000 | [diff] [blame] | 779 | Delegates most of the work to _FetchOne. |
| David James | 8d20116 | 2013-10-11 17:03:19 -0700 | [diff] [blame] | 780 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 781 | Args: |
| 782 | opt: Program options returned from optparse. See _Options(). |
| 783 | projects: Projects to fetch. |
| 784 | """ |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 785 | return [cls._FetchOne(opt, x) for x in projects] |
| David James | 8d20116 | 2013-10-11 17:03:19 -0700 | [diff] [blame] | 786 | |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 787 | @classmethod |
| 788 | def _FetchOne(cls, opt, project_idx): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 789 | """Fetch git objects for a single project. |
| David James | 8d20116 | 2013-10-11 17:03:19 -0700 | [diff] [blame] | 790 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 791 | Args: |
| 792 | opt: Program options returned from optparse. See _Options(). |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 793 | project_idx: Project index for the project to fetch. |
| David James | 8d20116 | 2013-10-11 17:03:19 -0700 | [diff] [blame] | 794 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 795 | Returns: |
| 796 | Whether the fetch was successful. |
| 797 | """ |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 798 | project = cls.get_parallel_context()["projects"][project_idx] |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 799 | start = time.time() |
| Gavin Mak | 551285f | 2023-05-04 04:48:43 +0000 | [diff] [blame] | 800 | k = f"{project.name} @ {project.relpath}" |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 801 | cls.get_parallel_context()["sync_dict"][k] = start |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 802 | success = False |
| 803 | remote_fetched = False |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 804 | errors = [] |
| Jason Chang | daf2ad3 | 2023-08-31 17:06:36 -0700 | [diff] [blame] | 805 | buf = TeeStringIO(sys.stdout if opt.verbose else None) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 806 | try: |
| 807 | sync_result = project.Sync_NetworkHalf( |
| 808 | quiet=opt.quiet, |
| 809 | verbose=opt.verbose, |
| 810 | output_redir=buf, |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 811 | current_branch_only=cls._GetCurrentBranchOnly( |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 812 | opt, project.manifest |
| 813 | ), |
| 814 | force_sync=opt.force_sync, |
| 815 | clone_bundle=opt.clone_bundle, |
| 816 | tags=opt.tags, |
| 817 | archive=project.manifest.IsArchive, |
| 818 | optimized_fetch=opt.optimized_fetch, |
| 819 | retry_fetches=opt.retry_fetches, |
| 820 | prune=opt.prune, |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 821 | ssh_proxy=cls.get_parallel_context()["ssh_proxy"], |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 822 | clone_filter=project.manifest.CloneFilter, |
| 823 | partial_clone_exclude=project.manifest.PartialCloneExclude, |
| Jason Chang | 1783332 | 2023-05-23 13:06:55 -0700 | [diff] [blame] | 824 | clone_filter_for_depth=project.manifest.CloneFilterForDepth, |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 825 | ) |
| 826 | success = sync_result.success |
| 827 | remote_fetched = sync_result.remote_fetched |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 828 | if sync_result.error: |
| 829 | errors.append(sync_result.error) |
| Doug Anderson | fc06ced | 2011-03-16 15:49:18 -0700 | [diff] [blame] | 830 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 831 | output = buf.getvalue() |
| Jason Chang | daf2ad3 | 2023-08-31 17:06:36 -0700 | [diff] [blame] | 832 | if output and buf.io is None and not success: |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 833 | print("\n" + output.rstrip()) |
| Doug Anderson | fc06ced | 2011-03-16 15:49:18 -0700 | [diff] [blame] | 834 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 835 | if not success: |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 836 | logger.error( |
| 837 | "error: Cannot fetch %s from %s", |
| 838 | project.name, |
| 839 | project.remote.url, |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 840 | ) |
| 841 | except KeyboardInterrupt: |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 842 | logger.error("Keyboard interrupt while processing %s", project.name) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 843 | except GitError as e: |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 844 | logger.error("error.GitError: Cannot fetch %s", e) |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 845 | errors.append(e) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 846 | except Exception as e: |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 847 | logger.error( |
| 848 | "error: Cannot fetch %s (%s: %s)", |
| 849 | project.name, |
| 850 | type(e).__name__, |
| 851 | e, |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 852 | ) |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 853 | errors.append(e) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 854 | raise |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 855 | finally: |
| 856 | del cls.get_parallel_context()["sync_dict"][k] |
| Mike Frysinger | 7b586f2 | 2021-02-23 18:38:39 -0500 | [diff] [blame] | 857 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 858 | finish = time.time() |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 859 | return _FetchOneResult( |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 860 | success, errors, project_idx, start, finish, remote_fetched |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 861 | ) |
| David James | 8d20116 | 2013-10-11 17:03:19 -0700 | [diff] [blame] | 862 | |
| Gavin Mak | 04cba4a | 2023-05-24 21:28:28 +0000 | [diff] [blame] | 863 | def _GetSyncProgressMessage(self): |
| Gavin Mak | 551285f | 2023-05-04 04:48:43 +0000 | [diff] [blame] | 864 | earliest_time = float("inf") |
| 865 | earliest_proj = None |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 866 | items = self.get_parallel_context()["sync_dict"].items() |
| Gavin Mak | 945c006 | 2023-05-30 20:04:07 +0000 | [diff] [blame] | 867 | for project, t in items: |
| Gavin Mak | 551285f | 2023-05-04 04:48:43 +0000 | [diff] [blame] | 868 | if t < earliest_time: |
| 869 | earliest_time = t |
| 870 | earliest_proj = project |
| 871 | |
| Josip Sokcevic | 71122f9 | 2023-05-26 02:44:37 +0000 | [diff] [blame] | 872 | if not earliest_proj: |
| Gavin Mak | 945c006 | 2023-05-30 20:04:07 +0000 | [diff] [blame] | 873 | # This function is called when sync is still running but in some |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 874 | # cases (by chance), sync_dict can contain no entries. Return some |
| Gavin Mak | 945c006 | 2023-05-30 20:04:07 +0000 | [diff] [blame] | 875 | # text to indicate that sync is still working. |
| 876 | return "..working.." |
| Josip Sokcevic | 71122f9 | 2023-05-26 02:44:37 +0000 | [diff] [blame] | 877 | |
| Gavin Mak | 551285f | 2023-05-04 04:48:43 +0000 | [diff] [blame] | 878 | elapsed = time.time() - earliest_time |
| Gavin Mak | 945c006 | 2023-05-30 20:04:07 +0000 | [diff] [blame] | 879 | jobs = jobs_str(len(items)) |
| Gavin Mak | 04cba4a | 2023-05-24 21:28:28 +0000 | [diff] [blame] | 880 | return f"{jobs} | {elapsed_str(elapsed)} {earliest_proj}" |
| Gavin Mak | 551285f | 2023-05-04 04:48:43 +0000 | [diff] [blame] | 881 | |
| Kuang-che Wu | ab2d321 | 2024-11-06 13:03:42 +0800 | [diff] [blame] | 882 | @classmethod |
| 883 | def InitWorker(cls): |
| 884 | # Force connect to the manager server now. |
| 885 | # This is good because workers are initialized one by one. Without this, |
| 886 | # multiple workers may connect to the manager when handling the first |
| 887 | # job at the same time. Then the connection may fail if too many |
| 888 | # connections are pending and execeeded the socket listening backlog, |
| 889 | # especially on MacOS. |
| 890 | len(cls.get_parallel_context()["sync_dict"]) |
| 891 | |
| Jason Chang | daf2ad3 | 2023-08-31 17:06:36 -0700 | [diff] [blame] | 892 | def _Fetch(self, projects, opt, err_event, ssh_proxy, errors): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 893 | ret = True |
| Mike Frysinger | b2fa30a | 2021-02-24 00:15:32 -0500 | [diff] [blame] | 894 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 895 | fetched = set() |
| 896 | remote_fetched = set() |
| Gavin Mak | edcaa94 | 2023-04-27 05:58:57 +0000 | [diff] [blame] | 897 | pm = Progress( |
| 898 | "Fetching", |
| 899 | len(projects), |
| 900 | delay=False, |
| 901 | quiet=opt.quiet, |
| 902 | show_elapsed=True, |
| Gavin Mak | 551285f | 2023-05-04 04:48:43 +0000 | [diff] [blame] | 903 | elide=True, |
| Gavin Mak | edcaa94 | 2023-04-27 05:58:57 +0000 | [diff] [blame] | 904 | ) |
| Roy Lee | 18afd7f | 2010-05-09 04:32:08 +0800 | [diff] [blame] | 905 | |
| Gavin Mak | 551285f | 2023-05-04 04:48:43 +0000 | [diff] [blame] | 906 | sync_event = _threading.Event() |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 907 | sync_progress_thread = self._CreateSyncProgressThread(pm, sync_event) |
| Gavin Mak | 551285f | 2023-05-04 04:48:43 +0000 | [diff] [blame] | 908 | |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 909 | def _ProcessResults(pool, pm, results_sets): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 910 | ret = True |
| 911 | for results in results_sets: |
| 912 | for result in results: |
| 913 | success = result.success |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 914 | project = projects[result.project_idx] |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 915 | start = result.start |
| 916 | finish = result.finish |
| 917 | self._fetch_times.Set(project, finish - start) |
| Gavin Mak | 1d2e99d | 2023-07-22 02:56:44 +0000 | [diff] [blame] | 918 | self._local_sync_state.SetFetchTime(project) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 919 | self.event_log.AddSync( |
| 920 | project, |
| 921 | event_log.TASK_SYNC_NETWORK, |
| 922 | start, |
| 923 | finish, |
| 924 | success, |
| 925 | ) |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 926 | if result.errors: |
| 927 | errors.extend(result.errors) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 928 | if result.remote_fetched: |
| 929 | remote_fetched.add(project) |
| 930 | # Check for any errors before running any more tasks. |
| 931 | # ...we'll let existing jobs finish, though. |
| 932 | if not success: |
| 933 | ret = False |
| 934 | else: |
| 935 | fetched.add(project.gitdir) |
| Gavin Mak | 551285f | 2023-05-04 04:48:43 +0000 | [diff] [blame] | 936 | pm.update() |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 937 | if not ret and opt.fail_fast: |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 938 | if pool: |
| 939 | pool.close() |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 940 | break |
| Mike Frysinger | b5d075d | 2021-03-01 00:56:38 -0500 | [diff] [blame] | 941 | return ret |
| Xin Li | 745be2e | 2019-06-03 11:24:30 -0700 | [diff] [blame] | 942 | |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 943 | with self.ParallelContext(): |
| 944 | self.get_parallel_context()["projects"] = projects |
| 945 | self.get_parallel_context()[ |
| 946 | "sync_dict" |
| 947 | ] = multiprocessing.Manager().dict() |
| Mike Frysinger | ebf04a4 | 2021-02-23 20:48:04 -0500 | [diff] [blame] | 948 | |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 949 | objdir_project_map = dict() |
| 950 | for index, project in enumerate(projects): |
| 951 | objdir_project_map.setdefault(project.objdir, []).append(index) |
| 952 | projects_list = list(objdir_project_map.values()) |
| 953 | |
| Peter Kjellerstedt | 616e314 | 2024-11-20 21:10:29 +0100 | [diff] [blame] | 954 | jobs = max(1, min(opt.jobs_network, len(projects_list))) |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 955 | |
| 956 | # We pass the ssh proxy settings via the class. This allows |
| 957 | # multiprocessing to pickle it up when spawning children. We can't |
| 958 | # pass it as an argument to _FetchProjectList below as |
| 959 | # multiprocessing is unable to pickle those. |
| 960 | self.get_parallel_context()["ssh_proxy"] = ssh_proxy |
| 961 | |
| 962 | sync_progress_thread.start() |
| Josip Sokcevic | 454fdaf | 2024-10-07 17:33:38 +0000 | [diff] [blame] | 963 | if not opt.quiet: |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 964 | pm.update(inc=0, msg="warming up") |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 965 | try: |
| 966 | ret = self.ExecuteInParallel( |
| 967 | jobs, |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 968 | functools.partial(self._FetchProjectList, opt), |
| 969 | projects_list, |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 970 | callback=_ProcessResults, |
| 971 | output=pm, |
| 972 | # Use chunksize=1 to avoid the chance that some workers are |
| 973 | # idle while other workers still have more than one job in |
| 974 | # their chunk queue. |
| 975 | chunksize=1, |
| Kuang-che Wu | ab2d321 | 2024-11-06 13:03:42 +0800 | [diff] [blame] | 976 | initializer=self.InitWorker, |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 977 | ) |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 978 | finally: |
| 979 | sync_event.set() |
| 980 | sync_progress_thread.join() |
| LaMont Jones | fa8d939 | 2022-11-02 22:01:29 +0000 | [diff] [blame] | 981 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 982 | if not self.outer_client.manifest.IsArchive: |
| 983 | self._GCProjects(projects, opt, err_event) |
| Mike Frysinger | 65af260 | 2021-04-08 22:47:44 -0400 | [diff] [blame] | 984 | |
| Jason Chang | daf2ad3 | 2023-08-31 17:06:36 -0700 | [diff] [blame] | 985 | return _FetchResult(ret, fetched) |
| LaMont Jones | fa8d939 | 2022-11-02 22:01:29 +0000 | [diff] [blame] | 986 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 987 | def _FetchMain( |
| Jason Chang | daf2ad3 | 2023-08-31 17:06:36 -0700 | [diff] [blame] | 988 | self, opt, args, all_projects, err_event, ssh_proxy, manifest, errors |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 989 | ): |
| 990 | """The main network fetch loop. |
| Mike Frysinger | 65af260 | 2021-04-08 22:47:44 -0400 | [diff] [blame] | 991 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 992 | Args: |
| 993 | opt: Program options returned from optparse. See _Options(). |
| 994 | args: Command line args used to filter out projects. |
| 995 | all_projects: List of all projects that should be fetched. |
| 996 | err_event: Whether an error was hit while processing. |
| 997 | ssh_proxy: SSH manager for clients & masters. |
| 998 | manifest: The manifest to use. |
| Dave Borowitz | 1885721 | 2012-10-23 17:02:59 -0700 | [diff] [blame] | 999 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1000 | Returns: |
| 1001 | List of all projects that should be checked out. |
| 1002 | """ |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1003 | to_fetch = [] |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1004 | to_fetch.extend(all_projects) |
| 1005 | to_fetch.sort(key=self._fetch_times.Get, reverse=True) |
| Dave Borowitz | 1885721 | 2012-10-23 17:02:59 -0700 | [diff] [blame] | 1006 | |
| Gavin Mak | 1afe96a | 2025-10-20 11:13:09 -0700 | [diff] [blame] | 1007 | try: |
| 1008 | result = self._Fetch(to_fetch, opt, err_event, ssh_proxy, errors) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1009 | success = result.success |
| Gavin Mak | 1afe96a | 2025-10-20 11:13:09 -0700 | [diff] [blame] | 1010 | fetched = result.projects |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1011 | if not success: |
| 1012 | err_event.set() |
| Gavin Mak | 1afe96a | 2025-10-20 11:13:09 -0700 | [diff] [blame] | 1013 | |
| 1014 | if opt.network_only: |
| 1015 | # Bail out now; the rest touches the working tree. |
| 1016 | if err_event.is_set(): |
| 1017 | e = SyncError( |
| 1018 | "error: Exited sync due to fetch errors.", |
| 1019 | aggregate_errors=errors, |
| 1020 | ) |
| 1021 | |
| 1022 | logger.error(e) |
| 1023 | raise e |
| 1024 | return _FetchMainResult([]) |
| 1025 | |
| 1026 | # Iteratively fetch missing and/or nested unregistered submodules. |
| 1027 | previously_missing_set = set() |
| 1028 | while True: |
| 1029 | self._ReloadManifest(None, manifest) |
| 1030 | all_projects = self.GetProjects( |
| 1031 | args, |
| 1032 | missing_ok=True, |
| 1033 | submodules_ok=opt.fetch_submodules, |
| 1034 | manifest=manifest, |
| 1035 | all_manifests=not opt.this_manifest_only, |
| 1036 | ) |
| 1037 | missing = [] |
| 1038 | for project in all_projects: |
| 1039 | if project.gitdir not in fetched: |
| 1040 | missing.append(project) |
| 1041 | if not missing: |
| 1042 | break |
| 1043 | # Stop us from non-stopped fetching actually-missing repos: If |
| 1044 | # set of missing repos has not been changed from last fetch, we |
| 1045 | # break. |
| 1046 | missing_set = {p.name for p in missing} |
| 1047 | if previously_missing_set == missing_set: |
| 1048 | break |
| 1049 | previously_missing_set = missing_set |
| 1050 | result = self._Fetch(missing, opt, err_event, ssh_proxy, errors) |
| 1051 | success = result.success |
| 1052 | new_fetched = result.projects |
| 1053 | if not success: |
| 1054 | err_event.set() |
| 1055 | fetched.update(new_fetched) |
| 1056 | finally: |
| 1057 | self._fetch_times.Save() |
| 1058 | self._local_sync_state.Save() |
| Jaikumar Ganesh | 4f2517f | 2009-06-01 21:10:33 -0700 | [diff] [blame] | 1059 | |
| Jason Chang | daf2ad3 | 2023-08-31 17:06:36 -0700 | [diff] [blame] | 1060 | return _FetchMainResult(all_projects) |
| Jaikumar Ganesh | 4f2517f | 2009-06-01 21:10:33 -0700 | [diff] [blame] | 1061 | |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 1062 | @classmethod |
| Josip Sokcevic | edadb25 | 2024-02-29 09:48:37 -0800 | [diff] [blame] | 1063 | def _CheckoutOne( |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 1064 | cls, |
| Jeroen Dhollander | c44ad09 | 2024-08-20 10:28:41 +0200 | [diff] [blame] | 1065 | detach_head, |
| 1066 | force_sync, |
| 1067 | force_checkout, |
| 1068 | force_rebase, |
| 1069 | verbose, |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 1070 | project_idx, |
| Josip Sokcevic | edadb25 | 2024-02-29 09:48:37 -0800 | [diff] [blame] | 1071 | ): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1072 | """Checkout work tree for one project |
| jiajia tang | a590e64 | 2021-04-25 20:02:02 +0800 | [diff] [blame] | 1073 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1074 | Args: |
| 1075 | detach_head: Whether to leave a detached HEAD. |
| Josip Sokcevic | edadb25 | 2024-02-29 09:48:37 -0800 | [diff] [blame] | 1076 | force_sync: Force checking out of .git directory (e.g. overwrite |
| 1077 | existing git directory that was previously linked to a different |
| 1078 | object directory). |
| 1079 | force_checkout: Force checking out of the repo content. |
| Jeroen Dhollander | c44ad09 | 2024-08-20 10:28:41 +0200 | [diff] [blame] | 1080 | force_rebase: Force rebase. |
| Tomasz Wasilczyk | 4c80921 | 2023-12-08 13:42:17 -0800 | [diff] [blame] | 1081 | verbose: Whether to show verbose messages. |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 1082 | project_idx: Project index for the project to checkout. |
| jiajia tang | a590e64 | 2021-04-25 20:02:02 +0800 | [diff] [blame] | 1083 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1084 | Returns: |
| 1085 | Whether the fetch was successful. |
| 1086 | """ |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 1087 | project = cls.get_parallel_context()["projects"][project_idx] |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1088 | start = time.time() |
| 1089 | syncbuf = SyncBuffer( |
| 1090 | project.manifest.manifestProject.config, detach_head=detach_head |
| LaMont Jones | bdcba7d | 2022-04-11 22:50:11 +0000 | [diff] [blame] | 1091 | ) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1092 | success = False |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1093 | errors = [] |
| David Pursehouse | 59b4174 | 2015-05-07 14:36:09 +0900 | [diff] [blame] | 1094 | try: |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1095 | project.Sync_LocalHalf( |
| Josip Sokcevic | edadb25 | 2024-02-29 09:48:37 -0800 | [diff] [blame] | 1096 | syncbuf, |
| 1097 | force_sync=force_sync, |
| 1098 | force_checkout=force_checkout, |
| Jeroen Dhollander | c44ad09 | 2024-08-20 10:28:41 +0200 | [diff] [blame] | 1099 | force_rebase=force_rebase, |
| Josip Sokcevic | edadb25 | 2024-02-29 09:48:37 -0800 | [diff] [blame] | 1100 | verbose=verbose, |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1101 | ) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1102 | success = syncbuf.Finish() |
| Gavin Mak | a64149a | 2025-08-13 22:48:36 -0700 | [diff] [blame] | 1103 | errors.extend(syncbuf.errors) |
| Josip Sokcevic | d93fe60 | 2025-01-08 18:31:46 +0000 | [diff] [blame] | 1104 | except KeyboardInterrupt: |
| 1105 | logger.error("Keyboard interrupt while processing %s", project.name) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1106 | except GitError as e: |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 1107 | logger.error( |
| 1108 | "error.GitError: Cannot checkout %s: %s", project.name, e |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1109 | ) |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1110 | errors.append(e) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1111 | except Exception as e: |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 1112 | logger.error( |
| 1113 | "error: Cannot checkout %s: %s: %s", |
| 1114 | project.name, |
| 1115 | type(e).__name__, |
| 1116 | e, |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1117 | ) |
| 1118 | raise |
| Nico Sallembien | a1bfd2c | 2010-04-06 10:40:01 -0700 | [diff] [blame] | 1119 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1120 | if not success: |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 1121 | logger.error("error: Cannot checkout %s", project.name) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1122 | finish = time.time() |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 1123 | return _CheckoutOneResult(success, errors, project_idx, start, finish) |
| Mike Frysinger | 5a03308 | 2019-09-23 19:21:20 -0400 | [diff] [blame] | 1124 | |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1125 | def _Checkout(self, all_projects, opt, err_results, checkout_errors): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1126 | """Checkout projects listed in all_projects |
| The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 1127 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1128 | Args: |
| 1129 | all_projects: List of all projects that should be checked out. |
| 1130 | opt: Program options returned from optparse. See _Options(). |
| 1131 | err_results: A list of strings, paths to git repos where checkout |
| 1132 | failed. |
| 1133 | """ |
| 1134 | # Only checkout projects with worktrees. |
| 1135 | all_projects = [x for x in all_projects if x.worktree] |
| The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 1136 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1137 | def _ProcessResults(pool, pm, results): |
| 1138 | ret = True |
| 1139 | for result in results: |
| 1140 | success = result.success |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 1141 | project = self.get_parallel_context()["projects"][ |
| 1142 | result.project_idx |
| 1143 | ] |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1144 | start = result.start |
| 1145 | finish = result.finish |
| 1146 | self.event_log.AddSync( |
| 1147 | project, event_log.TASK_SYNC_LOCAL, start, finish, success |
| 1148 | ) |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1149 | |
| 1150 | if result.errors: |
| 1151 | checkout_errors.extend(result.errors) |
| 1152 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1153 | # Check for any errors before running any more tasks. |
| 1154 | # ...we'll let existing jobs finish, though. |
| Gavin Mak | 1d2e99d | 2023-07-22 02:56:44 +0000 | [diff] [blame] | 1155 | if success: |
| 1156 | self._local_sync_state.SetCheckoutTime(project) |
| 1157 | else: |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1158 | ret = False |
| 1159 | err_results.append( |
| 1160 | project.RelPath(local=opt.this_manifest_only) |
| 1161 | ) |
| 1162 | if opt.fail_fast: |
| 1163 | if pool: |
| 1164 | pool.close() |
| 1165 | return ret |
| 1166 | pm.update(msg=project.name) |
| 1167 | return ret |
| Shawn O. Pearce | c9ef744 | 2008-11-03 10:32:09 -0800 | [diff] [blame] | 1168 | |
| Josip Sokcevic | 5554572 | 2024-02-22 16:38:00 -0800 | [diff] [blame] | 1169 | for projects in _SafeCheckoutOrder(all_projects): |
| Kuang-che Wu | 39ffd99 | 2024-10-18 23:32:08 +0800 | [diff] [blame] | 1170 | with self.ParallelContext(): |
| 1171 | self.get_parallel_context()["projects"] = projects |
| 1172 | proc_res = self.ExecuteInParallel( |
| 1173 | opt.jobs_checkout, |
| 1174 | functools.partial( |
| 1175 | self._CheckoutOne, |
| 1176 | opt.detach_head, |
| 1177 | opt.force_sync, |
| 1178 | opt.force_checkout, |
| 1179 | opt.rebase, |
| 1180 | opt.verbose, |
| 1181 | ), |
| 1182 | range(len(projects)), |
| 1183 | callback=_ProcessResults, |
| 1184 | output=Progress( |
| 1185 | "Checking out", len(all_projects), quiet=opt.quiet |
| 1186 | ), |
| 1187 | # Use chunksize=1 to avoid the chance that some workers are |
| 1188 | # idle while other workers still have more than one job in |
| 1189 | # their chunk queue. |
| 1190 | chunksize=1, |
| 1191 | ) |
| Simran Basi | b9a1b73 | 2015-08-20 12:19:28 -0700 | [diff] [blame] | 1192 | |
| Gavin Mak | 1d2e99d | 2023-07-22 02:56:44 +0000 | [diff] [blame] | 1193 | self._local_sync_state.Save() |
| 1194 | return proc_res and not err_results |
| 1195 | |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 1196 | def _PrintManifestNotices(self, opt): |
| 1197 | """Print all manifest notices, but only once.""" |
| 1198 | printed_notices = set() |
| 1199 | # Print all manifest notices, but only once. |
| 1200 | # Sort by path_prefix to ensure consistent ordering. |
| 1201 | for m in sorted(self.ManifestList(opt), key=lambda x: x.path_prefix): |
| 1202 | if m.notice and m.notice not in printed_notices: |
| 1203 | print(m.notice) |
| 1204 | printed_notices.add(m.notice) |
| 1205 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1206 | @staticmethod |
| 1207 | def _GetPreciousObjectsState(project: Project, opt): |
| 1208 | """Get the preciousObjects state for the project. |
| Mike Frysinger | 355f439 | 2022-07-20 17:15:29 -0400 | [diff] [blame] | 1209 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1210 | Args: |
| 1211 | project (Project): the project to examine, and possibly correct. |
| 1212 | opt (optparse.Values): options given to sync. |
| Raman Tenneti | 1fd7bc2 | 2021-02-04 14:39:38 -0800 | [diff] [blame] | 1213 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1214 | Returns: |
| 1215 | Expected state of extensions.preciousObjects: |
| 1216 | False: Should be disabled. (not present) |
| 1217 | True: Should be enabled. |
| 1218 | """ |
| 1219 | if project.use_git_worktrees: |
| 1220 | return False |
| 1221 | projects = project.manifest.GetProjectsWithName( |
| 1222 | project.name, all_manifests=True |
| 1223 | ) |
| 1224 | if len(projects) == 1: |
| 1225 | return False |
| 1226 | if len(projects) > 1: |
| 1227 | # Objects are potentially shared with another project. |
| 1228 | # See the logic in Project.Sync_NetworkHalf regarding UseAlternates. |
| 1229 | # - When False, shared projects share (via symlink) |
| 1230 | # .repo/project-objects/{PROJECT_NAME}.git as the one-and-only |
| 1231 | # objects directory. All objects are precious, since there is no |
| 1232 | # project with a complete set of refs. |
| 1233 | # - When True, shared projects share (via info/alternates) |
| 1234 | # .repo/project-objects/{PROJECT_NAME}.git as an alternate object |
| 1235 | # store, which is written only on the first clone of the project, |
| 1236 | # and is not written subsequently. (When Sync_NetworkHalf sees |
| 1237 | # that it exists, it makes sure that the alternates file points |
| 1238 | # there, and uses a project-local .git/objects directory for all |
| 1239 | # syncs going forward. |
| 1240 | # We do not support switching between the options. The environment |
| 1241 | # variable is present for testing and migration only. |
| 1242 | return not project.UseAlternates |
| Simran Basi | b9a1b73 | 2015-08-20 12:19:28 -0700 | [diff] [blame] | 1243 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1244 | return False |
| Dan Willemsen | 5ea32d1 | 2015-09-08 13:27:20 -0700 | [diff] [blame] | 1245 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1246 | def _SetPreciousObjectsState(self, project: Project, opt): |
| 1247 | """Correct the preciousObjects state for the project. |
| 1248 | |
| 1249 | Args: |
| 1250 | project: the project to examine, and possibly correct. |
| 1251 | opt: options given to sync. |
| 1252 | """ |
| 1253 | expected = self._GetPreciousObjectsState(project, opt) |
| 1254 | actual = ( |
| 1255 | project.config.GetBoolean("extensions.preciousObjects") or False |
| 1256 | ) |
| 1257 | relpath = project.RelPath(local=opt.this_manifest_only) |
| 1258 | |
| 1259 | if expected != actual: |
| 1260 | # If this is unexpected, log it and repair. |
| 1261 | Trace( |
| 1262 | f"{relpath} expected preciousObjects={expected}, got {actual}" |
| 1263 | ) |
| 1264 | if expected: |
| 1265 | if not opt.quiet: |
| Aravind Vasudevan | 83c66ec | 2023-09-28 19:06:59 +0000 | [diff] [blame] | 1266 | print( |
| 1267 | "\r%s: Shared project %s found, disabling pruning." |
| 1268 | % (relpath, project.name) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1269 | ) |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 1270 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1271 | if git_require((2, 7, 0)): |
| 1272 | project.EnableRepositoryExtension("preciousObjects") |
| 1273 | else: |
| 1274 | # This isn't perfect, but it's the best we can do with old |
| 1275 | # git. |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 1276 | logger.warning( |
| 1277 | "%s: WARNING: shared projects are unreliable when " |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1278 | "using old versions of git; please upgrade to " |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 1279 | "git-2.7.0+.", |
| 1280 | relpath, |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1281 | ) |
| 1282 | project.config.SetString("gc.pruneExpire", "never") |
| 1283 | else: |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1284 | project.config.SetString("extensions.preciousObjects", None) |
| 1285 | project.config.SetString("gc.pruneExpire", None) |
| 1286 | |
| 1287 | def _GCProjects(self, projects, opt, err_event): |
| 1288 | """Perform garbage collection. |
| 1289 | |
| 1290 | If We are skipping garbage collection (opt.auto_gc not set), we still |
| 1291 | want to potentially mark objects precious, so that `git gc` does not |
| 1292 | discard shared objects. |
| 1293 | """ |
| 1294 | if not opt.auto_gc: |
| 1295 | # Just repair preciousObjects state, and return. |
| 1296 | for project in projects: |
| 1297 | self._SetPreciousObjectsState(project, opt) |
| 1298 | return |
| 1299 | |
| 1300 | pm = Progress( |
| 1301 | "Garbage collecting", len(projects), delay=False, quiet=opt.quiet |
| 1302 | ) |
| 1303 | pm.update(inc=0, msg="prescan") |
| 1304 | |
| 1305 | tidy_dirs = {} |
| 1306 | for project in projects: |
| 1307 | self._SetPreciousObjectsState(project, opt) |
| 1308 | |
| 1309 | project.config.SetString("gc.autoDetach", "false") |
| 1310 | # Only call git gc once per objdir, but call pack-refs for the |
| 1311 | # remainder. |
| 1312 | if project.objdir not in tidy_dirs: |
| 1313 | tidy_dirs[project.objdir] = ( |
| 1314 | True, # Run a full gc. |
| 1315 | project.bare_git, |
| 1316 | ) |
| 1317 | elif project.gitdir not in tidy_dirs: |
| 1318 | tidy_dirs[project.gitdir] = ( |
| 1319 | False, # Do not run a full gc; just run pack-refs. |
| 1320 | project.bare_git, |
| 1321 | ) |
| 1322 | |
| 1323 | jobs = opt.jobs |
| 1324 | |
| 1325 | if jobs < 2: |
| 1326 | for run_gc, bare_git in tidy_dirs.values(): |
| 1327 | pm.update(msg=bare_git._project.name) |
| 1328 | |
| 1329 | if run_gc: |
| 1330 | bare_git.gc("--auto") |
| 1331 | else: |
| 1332 | bare_git.pack_refs() |
| 1333 | pm.end() |
| 1334 | return |
| 1335 | |
| 1336 | cpu_count = os.cpu_count() |
| 1337 | config = {"pack.threads": cpu_count // jobs if cpu_count > jobs else 1} |
| 1338 | |
| 1339 | threads = set() |
| 1340 | sem = _threading.Semaphore(jobs) |
| 1341 | |
| 1342 | def tidy_up(run_gc, bare_git): |
| 1343 | pm.start(bare_git._project.name) |
| 1344 | try: |
| 1345 | try: |
| 1346 | if run_gc: |
| 1347 | bare_git.gc("--auto", config=config) |
| 1348 | else: |
| 1349 | bare_git.pack_refs(config=config) |
| 1350 | except GitError: |
| 1351 | err_event.set() |
| 1352 | except Exception: |
| 1353 | err_event.set() |
| 1354 | raise |
| 1355 | finally: |
| 1356 | pm.finish(bare_git._project.name) |
| 1357 | sem.release() |
| 1358 | |
| 1359 | for run_gc, bare_git in tidy_dirs.values(): |
| 1360 | if err_event.is_set() and opt.fail_fast: |
| 1361 | break |
| 1362 | sem.acquire() |
| 1363 | t = _threading.Thread( |
| 1364 | target=tidy_up, |
| 1365 | args=( |
| 1366 | run_gc, |
| 1367 | bare_git, |
| 1368 | ), |
| 1369 | ) |
| 1370 | t.daemon = True |
| 1371 | threads.add(t) |
| 1372 | t.start() |
| 1373 | |
| 1374 | for t in threads: |
| 1375 | t.join() |
| 1376 | pm.end() |
| 1377 | |
| Gavin Mak | b5991d7 | 2025-12-09 22:29:43 +0000 | [diff] [blame] | 1378 | @classmethod |
| 1379 | def _CheckOneBloatedProject(cls, project_index: int) -> Optional[str]: |
| 1380 | """Checks if a single project is bloated. |
| 1381 | |
| 1382 | Args: |
| 1383 | project_index: The index of the project in the parallel context. |
| 1384 | |
| 1385 | Returns: |
| 1386 | The name of the project if it is bloated, else None. |
| 1387 | """ |
| 1388 | project = cls.get_parallel_context()["projects"][project_index] |
| 1389 | |
| 1390 | if not project.Exists or not project.worktree: |
| 1391 | return None |
| 1392 | |
| 1393 | # Only check dirty or locally modified projects. These can't be |
| 1394 | # freshly cloned and will accumulate garbage. |
| 1395 | try: |
| 1396 | is_dirty = project.IsDirty(consider_untracked=True) |
| 1397 | |
| 1398 | manifest_rev = project.GetRevisionId(project.bare_ref.all) |
| 1399 | head_rev = project.work_git.rev_parse(HEAD) |
| 1400 | has_local_commits = manifest_rev != head_rev |
| 1401 | |
| 1402 | if not (is_dirty or has_local_commits): |
| 1403 | return None |
| 1404 | |
| 1405 | output = project.bare_git.count_objects("-v") |
| 1406 | except Exception: |
| 1407 | return None |
| 1408 | |
| 1409 | stats = {} |
| 1410 | for line in output.splitlines(): |
| 1411 | try: |
| 1412 | key, value = line.split(": ", 1) |
| 1413 | stats[key.strip()] = int(value.strip()) |
| 1414 | except ValueError: |
| 1415 | pass |
| 1416 | |
| 1417 | pack_count = stats.get("packs", 0) |
| 1418 | size_pack_kb = stats.get("size-pack", 0) |
| 1419 | size_garbage_kb = stats.get("size-garbage", 0) |
| 1420 | |
| 1421 | is_fragmented = ( |
| 1422 | pack_count > _BLOAT_PACK_COUNT_THRESHOLD |
| 1423 | and size_pack_kb > _BLOAT_SIZE_PACK_THRESHOLD_KB |
| 1424 | ) |
| 1425 | has_excessive_garbage = ( |
| 1426 | size_garbage_kb > _BLOAT_SIZE_GARBAGE_THRESHOLD_KB |
| 1427 | ) |
| 1428 | |
| 1429 | if is_fragmented or has_excessive_garbage: |
| 1430 | return project.name |
| 1431 | return None |
| 1432 | |
| 1433 | def _CheckForBloatedProjects(self, projects, opt): |
| 1434 | """Check for shallow projects that are accumulating unoptimized data. |
| 1435 | |
| 1436 | For projects with clone-depth="1" that are dirty (have local changes), |
| 1437 | run 'git count-objects -v' and warn if the repository is accumulating |
| 1438 | excessive pack files or garbage. |
| 1439 | """ |
| Gavin Mak | 5b0b551 | 2025-12-15 18:49:13 +0000 | [diff] [blame] | 1440 | # We only care about bloated projects if we have a git version that |
| 1441 | # supports --no-auto-gc (2.23.0+) since what we use to disable auto-gc |
| 1442 | # in Project._RemoteFetch. |
| 1443 | if not git_require((2, 23, 0)): |
| 1444 | return |
| 1445 | |
| Gavin Mak | b5991d7 | 2025-12-09 22:29:43 +0000 | [diff] [blame] | 1446 | projects = [p for p in projects if p.clone_depth] |
| 1447 | if not projects: |
| 1448 | return |
| 1449 | |
| 1450 | bloated_projects = [] |
| 1451 | pm = Progress( |
| 1452 | "Checking for bloat", len(projects), delay=False, quiet=opt.quiet |
| 1453 | ) |
| 1454 | |
| 1455 | def _ProcessResults(pool, pm, results): |
| 1456 | for result in results: |
| 1457 | if result: |
| 1458 | bloated_projects.append(result) |
| 1459 | pm.update(msg="") |
| 1460 | |
| 1461 | with self.ParallelContext(): |
| 1462 | self.get_parallel_context()["projects"] = projects |
| 1463 | self.ExecuteInParallel( |
| 1464 | opt.jobs, |
| 1465 | self._CheckOneBloatedProject, |
| 1466 | range(len(projects)), |
| 1467 | callback=_ProcessResults, |
| 1468 | output=pm, |
| 1469 | chunksize=1, |
| 1470 | ) |
| 1471 | pm.end() |
| 1472 | |
| 1473 | for project_name in bloated_projects: |
| 1474 | warn_msg = ( |
| 1475 | f'warning: Project "{project_name}" is accumulating ' |
| 1476 | 'unoptimized data. Please run "repo sync --auto-gc" or ' |
| 1477 | '"repo gc --repack" to clean up.' |
| 1478 | ) |
| 1479 | self.git_event_log.ErrorEvent(warn_msg) |
| 1480 | logger.warning(warn_msg) |
| 1481 | |
| Gavin Mak | f7a3f99 | 2025-06-23 09:04:26 -0700 | [diff] [blame] | 1482 | def _UpdateRepoProject(self, opt, manifest, errors): |
| 1483 | """Fetch the repo project and check for updates.""" |
| 1484 | if opt.local_only: |
| 1485 | return |
| 1486 | |
| 1487 | rp = manifest.repoProject |
| 1488 | now = time.time() |
| 1489 | # If we've fetched in the last day, don't bother fetching again. |
| 1490 | if (now - rp.LastFetch) < _ONE_DAY_S: |
| 1491 | return |
| 1492 | |
| 1493 | with multiprocessing.Manager() as manager: |
| 1494 | with ssh.ProxyManager(manager) as ssh_proxy: |
| 1495 | ssh_proxy.sock() |
| 1496 | start = time.time() |
| 1497 | buf = TeeStringIO(sys.stdout if opt.verbose else None) |
| 1498 | sync_result = rp.Sync_NetworkHalf( |
| 1499 | quiet=opt.quiet, |
| 1500 | verbose=opt.verbose, |
| 1501 | output_redir=buf, |
| 1502 | current_branch_only=self._GetCurrentBranchOnly( |
| 1503 | opt, manifest |
| 1504 | ), |
| 1505 | force_sync=opt.force_sync, |
| 1506 | clone_bundle=opt.clone_bundle, |
| 1507 | tags=opt.tags, |
| 1508 | archive=manifest.IsArchive, |
| 1509 | optimized_fetch=opt.optimized_fetch, |
| 1510 | retry_fetches=opt.retry_fetches, |
| 1511 | prune=opt.prune, |
| 1512 | ssh_proxy=ssh_proxy, |
| 1513 | clone_filter=manifest.CloneFilter, |
| 1514 | partial_clone_exclude=manifest.PartialCloneExclude, |
| 1515 | clone_filter_for_depth=manifest.CloneFilterForDepth, |
| 1516 | ) |
| 1517 | if sync_result.error: |
| 1518 | errors.append(sync_result.error) |
| 1519 | |
| 1520 | finish = time.time() |
| 1521 | self.event_log.AddSync( |
| 1522 | rp, |
| 1523 | event_log.TASK_SYNC_NETWORK, |
| 1524 | start, |
| 1525 | finish, |
| 1526 | sync_result.success, |
| 1527 | ) |
| 1528 | if not sync_result.success: |
| 1529 | logger.error("error: Cannot fetch repo tool %s", rp.name) |
| 1530 | return |
| 1531 | |
| 1532 | # After fetching, check if a new version of repo is available and |
| 1533 | # restart. This is only done if the user hasn't explicitly disabled it. |
| 1534 | if os.environ.get("REPO_SKIP_SELF_UPDATE", "0") == "0": |
| 1535 | _PostRepoFetch(rp, opt.repo_verify) |
| 1536 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1537 | def _ReloadManifest(self, manifest_name, manifest): |
| 1538 | """Reload the manfiest from the file specified by the |manifest_name|. |
| 1539 | |
| 1540 | It unloads the manifest if |manifest_name| is None. |
| 1541 | |
| 1542 | Args: |
| 1543 | manifest_name: Manifest file to be reloaded. |
| 1544 | manifest: The manifest to use. |
| 1545 | """ |
| Dan Willemsen | 5ea32d1 | 2015-09-08 13:27:20 -0700 | [diff] [blame] | 1546 | if manifest_name: |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1547 | # Override calls Unload already. |
| 1548 | manifest.Override(manifest_name) |
| Dan Willemsen | 5ea32d1 | 2015-09-08 13:27:20 -0700 | [diff] [blame] | 1549 | else: |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1550 | manifest.Unload() |
| Simran Basi | b9a1b73 | 2015-08-20 12:19:28 -0700 | [diff] [blame] | 1551 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1552 | def UpdateProjectList(self, opt, manifest): |
| 1553 | """Update the cached projects list for |manifest| |
| LaMont Jones | bdcba7d | 2022-04-11 22:50:11 +0000 | [diff] [blame] | 1554 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1555 | In a multi-manifest checkout, each manifest has its own project.list. |
| The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 1556 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1557 | Args: |
| 1558 | opt: Program options returned from optparse. See _Options(). |
| 1559 | manifest: The manifest to use. |
| Mike Frysinger | 5a03308 | 2019-09-23 19:21:20 -0400 | [diff] [blame] | 1560 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1561 | Returns: |
| 1562 | 0: success |
| 1563 | 1: failure |
| 1564 | """ |
| 1565 | new_project_paths = [] |
| 1566 | for project in self.GetProjects( |
| 1567 | None, missing_ok=True, manifest=manifest, all_manifests=False |
| 1568 | ): |
| 1569 | if project.relpath: |
| 1570 | new_project_paths.append(project.relpath) |
| 1571 | file_name = "project.list" |
| 1572 | file_path = os.path.join(manifest.subdir, file_name) |
| 1573 | old_project_paths = [] |
| Mike Frysinger | 339f2df | 2021-05-06 00:44:42 -0400 | [diff] [blame] | 1574 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1575 | if os.path.exists(file_path): |
| Jason R. Coombs | 034950b | 2023-10-20 23:32:02 +0545 | [diff] [blame] | 1576 | with open(file_path) as fd: |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1577 | old_project_paths = fd.read().split("\n") |
| 1578 | # In reversed order, so subfolders are deleted before parent folder. |
| 1579 | for path in sorted(old_project_paths, reverse=True): |
| 1580 | if not path: |
| 1581 | continue |
| 1582 | if path not in new_project_paths: |
| 1583 | # If the path has already been deleted, we don't need to do |
| 1584 | # it. |
| 1585 | gitdir = os.path.join(manifest.topdir, path, ".git") |
| 1586 | if os.path.exists(gitdir): |
| 1587 | project = Project( |
| 1588 | manifest=manifest, |
| 1589 | name=path, |
| 1590 | remote=RemoteSpec("origin"), |
| 1591 | gitdir=gitdir, |
| 1592 | objdir=gitdir, |
| 1593 | use_git_worktrees=os.path.isfile(gitdir), |
| 1594 | worktree=os.path.join(manifest.topdir, path), |
| 1595 | relpath=path, |
| 1596 | revisionExpr="HEAD", |
| 1597 | revisionId=None, |
| 1598 | groups=None, |
| 1599 | ) |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1600 | project.DeleteWorktree( |
| Tomasz Wasilczyk | 4c80921 | 2023-12-08 13:42:17 -0800 | [diff] [blame] | 1601 | verbose=opt.verbose, force=opt.force_remove_dirty |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1602 | ) |
| Mike Frysinger | 5a03308 | 2019-09-23 19:21:20 -0400 | [diff] [blame] | 1603 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1604 | new_project_paths.sort() |
| 1605 | with open(file_path, "w") as fd: |
| 1606 | fd.write("\n".join(new_project_paths)) |
| 1607 | fd.write("\n") |
| 1608 | return 0 |
| Che-Liang Chiou | b2bd91c | 2012-01-11 11:28:42 +0800 | [diff] [blame] | 1609 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1610 | def UpdateCopyLinkfileList(self, manifest): |
| 1611 | """Save all dests of copyfile and linkfile, and update them if needed. |
| Shawn O. Pearce | cd1d7ff | 2009-06-04 16:15:53 -0700 | [diff] [blame] | 1612 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1613 | Returns: |
| 1614 | Whether update was successful. |
| 1615 | """ |
| 1616 | new_paths = {} |
| 1617 | new_linkfile_paths = [] |
| 1618 | new_copyfile_paths = [] |
| 1619 | for project in self.GetProjects( |
| 1620 | None, missing_ok=True, manifest=manifest, all_manifests=False |
| 1621 | ): |
| 1622 | new_linkfile_paths.extend(x.dest for x in project.linkfiles) |
| 1623 | new_copyfile_paths.extend(x.dest for x in project.copyfiles) |
| Jaikumar Ganesh | 4f2517f | 2009-06-01 21:10:33 -0700 | [diff] [blame] | 1624 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1625 | new_paths = { |
| 1626 | "linkfile": new_linkfile_paths, |
| 1627 | "copyfile": new_copyfile_paths, |
| 1628 | } |
| jiajia tang | a590e64 | 2021-04-25 20:02:02 +0800 | [diff] [blame] | 1629 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1630 | copylinkfile_name = "copy-link-files.json" |
| 1631 | copylinkfile_path = os.path.join(manifest.subdir, copylinkfile_name) |
| 1632 | old_copylinkfile_paths = {} |
| The Android Open Source Project | cf31fe9 | 2008-10-21 07:00:00 -0700 | [diff] [blame] | 1633 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1634 | if os.path.exists(copylinkfile_path): |
| 1635 | with open(copylinkfile_path, "rb") as fp: |
| 1636 | try: |
| 1637 | old_copylinkfile_paths = json.load(fp) |
| 1638 | except Exception: |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 1639 | logger.error( |
| 1640 | "error: %s is not a json formatted file.", |
| 1641 | copylinkfile_path, |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1642 | ) |
| 1643 | platform_utils.remove(copylinkfile_path) |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1644 | raise |
| Doug Anderson | 2b8db3c | 2010-11-01 15:08:06 -0700 | [diff] [blame] | 1645 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1646 | need_remove_files = [] |
| 1647 | need_remove_files.extend( |
| 1648 | set(old_copylinkfile_paths.get("linkfile", [])) |
| 1649 | - set(new_linkfile_paths) |
| 1650 | ) |
| 1651 | need_remove_files.extend( |
| 1652 | set(old_copylinkfile_paths.get("copyfile", [])) |
| 1653 | - set(new_copyfile_paths) |
| 1654 | ) |
| Mike Frysinger | 5a03308 | 2019-09-23 19:21:20 -0400 | [diff] [blame] | 1655 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1656 | for need_remove_file in need_remove_files: |
| 1657 | # Try to remove the updated copyfile or linkfile. |
| 1658 | # So, if the file is not exist, nothing need to do. |
| Josip Sokcevic | 9500aca | 2024-12-13 18:24:20 +0000 | [diff] [blame] | 1659 | platform_utils.remove( |
| 1660 | os.path.join(self.client.topdir, need_remove_file), |
| 1661 | missing_ok=True, |
| 1662 | ) |
| Raman Tenneti | 7954de1 | 2021-07-28 14:36:49 -0700 | [diff] [blame] | 1663 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1664 | # Create copy-link-files.json, save dest path of "copyfile" and |
| 1665 | # "linkfile". |
| 1666 | with open(copylinkfile_path, "w", encoding="utf-8") as fp: |
| 1667 | json.dump(new_paths, fp) |
| 1668 | return True |
| Raman Tenneti | 7954de1 | 2021-07-28 14:36:49 -0700 | [diff] [blame] | 1669 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1670 | def _SmartSyncSetup(self, opt, smart_sync_manifest_path, manifest): |
| 1671 | if not manifest.manifest_server: |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1672 | raise SmartSyncError( |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1673 | "error: cannot smart sync: no manifest server defined in " |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1674 | "manifest" |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1675 | ) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1676 | |
| 1677 | manifest_server = manifest.manifest_server |
| 1678 | if not opt.quiet: |
| Aravind Vasudevan | 83c66ec | 2023-09-28 19:06:59 +0000 | [diff] [blame] | 1679 | print("Using manifest server %s" % manifest_server) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1680 | |
| 1681 | if "@" not in manifest_server: |
| 1682 | username = None |
| 1683 | password = None |
| 1684 | if opt.manifest_server_username and opt.manifest_server_password: |
| 1685 | username = opt.manifest_server_username |
| 1686 | password = opt.manifest_server_password |
| 1687 | else: |
| 1688 | try: |
| 1689 | info = netrc.netrc() |
| Jason R. Coombs | ae824fb | 2023-10-20 23:32:40 +0545 | [diff] [blame] | 1690 | except OSError: |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1691 | # .netrc file does not exist or could not be opened. |
| 1692 | pass |
| 1693 | else: |
| 1694 | try: |
| 1695 | parse_result = urllib.parse.urlparse(manifest_server) |
| 1696 | if parse_result.hostname: |
| 1697 | auth = info.authenticators(parse_result.hostname) |
| 1698 | if auth: |
| 1699 | username, _account, password = auth |
| 1700 | else: |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 1701 | logger.error( |
| 1702 | "No credentials found for %s in .netrc", |
| 1703 | parse_result.hostname, |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1704 | ) |
| 1705 | except netrc.NetrcParseError as e: |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 1706 | logger.error("Error parsing .netrc file: %s", e) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1707 | |
| 1708 | if username and password: |
| 1709 | manifest_server = manifest_server.replace( |
| Jason R. Coombs | b32ccbb | 2023-09-29 11:04:49 -0400 | [diff] [blame] | 1710 | "://", f"://{username}:{password}@", 1 |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1711 | ) |
| 1712 | |
| 1713 | transport = PersistentTransport(manifest_server) |
| 1714 | if manifest_server.startswith("persistent-"): |
| 1715 | manifest_server = manifest_server[len("persistent-") :] |
| 1716 | |
| Mike Frysinger | dfdf577 | 2025-01-30 19:11:36 -0500 | [diff] [blame] | 1717 | # Changes in behavior should update docs/smart-sync.md accordingly. |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1718 | try: |
| 1719 | server = xmlrpc.client.Server(manifest_server, transport=transport) |
| 1720 | if opt.smart_sync: |
| 1721 | branch = self._GetBranch(manifest.manifestProject) |
| 1722 | |
| 1723 | if "SYNC_TARGET" in os.environ: |
| 1724 | target = os.environ["SYNC_TARGET"] |
| 1725 | [success, manifest_str] = server.GetApprovedManifest( |
| 1726 | branch, target |
| 1727 | ) |
| 1728 | elif ( |
| 1729 | "TARGET_PRODUCT" in os.environ |
| 1730 | and "TARGET_BUILD_VARIANT" in os.environ |
| Navil | 1e19f7d | 2024-09-11 16:49:49 +0000 | [diff] [blame] | 1731 | and "TARGET_RELEASE" in os.environ |
| 1732 | ): |
| 1733 | target = "%s-%s-%s" % ( |
| 1734 | os.environ["TARGET_PRODUCT"], |
| 1735 | os.environ["TARGET_RELEASE"], |
| 1736 | os.environ["TARGET_BUILD_VARIANT"], |
| 1737 | ) |
| 1738 | [success, manifest_str] = server.GetApprovedManifest( |
| 1739 | branch, target |
| 1740 | ) |
| 1741 | elif ( |
| 1742 | "TARGET_PRODUCT" in os.environ |
| 1743 | and "TARGET_BUILD_VARIANT" in os.environ |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1744 | ): |
| 1745 | target = "%s-%s" % ( |
| 1746 | os.environ["TARGET_PRODUCT"], |
| 1747 | os.environ["TARGET_BUILD_VARIANT"], |
| 1748 | ) |
| 1749 | [success, manifest_str] = server.GetApprovedManifest( |
| 1750 | branch, target |
| 1751 | ) |
| 1752 | else: |
| 1753 | [success, manifest_str] = server.GetApprovedManifest(branch) |
| 1754 | else: |
| 1755 | assert opt.smart_tag |
| 1756 | [success, manifest_str] = server.GetManifest(opt.smart_tag) |
| 1757 | |
| 1758 | if success: |
| 1759 | manifest_name = os.path.basename(smart_sync_manifest_path) |
| 1760 | try: |
| 1761 | with open(smart_sync_manifest_path, "w") as f: |
| 1762 | f.write(manifest_str) |
| Jason R. Coombs | ae824fb | 2023-10-20 23:32:40 +0545 | [diff] [blame] | 1763 | except OSError as e: |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1764 | raise SmartSyncError( |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1765 | "error: cannot write manifest to %s:\n%s" |
| 1766 | % (smart_sync_manifest_path, e), |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1767 | aggregate_errors=[e], |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1768 | ) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1769 | self._ReloadManifest(manifest_name, manifest) |
| 1770 | else: |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1771 | raise SmartSyncError( |
| 1772 | "error: manifest server RPC call failed: %s" % manifest_str |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1773 | ) |
| Jason R. Coombs | ae824fb | 2023-10-20 23:32:40 +0545 | [diff] [blame] | 1774 | except (OSError, xmlrpc.client.Fault) as e: |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1775 | raise SmartSyncError( |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1776 | "error: cannot connect to manifest server %s:\n%s" |
| 1777 | % (manifest.manifest_server, e), |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1778 | aggregate_errors=[e], |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1779 | ) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1780 | except xmlrpc.client.ProtocolError as e: |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1781 | raise SmartSyncError( |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1782 | "error: cannot connect to manifest server %s:\n%d %s" |
| 1783 | % (manifest.manifest_server, e.errcode, e.errmsg), |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1784 | aggregate_errors=[e], |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1785 | ) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1786 | |
| 1787 | return manifest_name |
| 1788 | |
| Jason Chang | daf2ad3 | 2023-08-31 17:06:36 -0700 | [diff] [blame] | 1789 | def _UpdateAllManifestProjects(self, opt, mp, manifest_name, errors): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1790 | """Fetch & update the local manifest project. |
| 1791 | |
| 1792 | After syncing the manifest project, if the manifest has any sub |
| 1793 | manifests, those are recursively processed. |
| 1794 | |
| 1795 | Args: |
| 1796 | opt: Program options returned from optparse. See _Options(). |
| 1797 | mp: the manifestProject to query. |
| 1798 | manifest_name: Manifest file to be reloaded. |
| 1799 | """ |
| 1800 | if not mp.standalone_manifest_url: |
| Jason Chang | daf2ad3 | 2023-08-31 17:06:36 -0700 | [diff] [blame] | 1801 | self._UpdateManifestProject(opt, mp, manifest_name, errors) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1802 | |
| 1803 | if mp.manifest.submanifests: |
| 1804 | for submanifest in mp.manifest.submanifests.values(): |
| 1805 | child = submanifest.repo_client.manifest |
| 1806 | child.manifestProject.SyncWithPossibleInit( |
| 1807 | submanifest, |
| 1808 | current_branch_only=self._GetCurrentBranchOnly(opt, child), |
| 1809 | verbose=opt.verbose, |
| 1810 | tags=opt.tags, |
| 1811 | git_event_log=self.git_event_log, |
| 1812 | ) |
| 1813 | self._UpdateAllManifestProjects( |
| Jason Chang | daf2ad3 | 2023-08-31 17:06:36 -0700 | [diff] [blame] | 1814 | opt, child.manifestProject, None, errors |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1815 | ) |
| 1816 | |
| Jason Chang | daf2ad3 | 2023-08-31 17:06:36 -0700 | [diff] [blame] | 1817 | def _UpdateManifestProject(self, opt, mp, manifest_name, errors): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1818 | """Fetch & update the local manifest project. |
| 1819 | |
| 1820 | Args: |
| 1821 | opt: Program options returned from optparse. See _Options(). |
| 1822 | mp: the manifestProject to query. |
| 1823 | manifest_name: Manifest file to be reloaded. |
| 1824 | """ |
| 1825 | if not opt.local_only: |
| 1826 | start = time.time() |
| Jason Chang | daf2ad3 | 2023-08-31 17:06:36 -0700 | [diff] [blame] | 1827 | buf = TeeStringIO(sys.stdout) |
| 1828 | try: |
| 1829 | result = mp.Sync_NetworkHalf( |
| Tomasz Wasilczyk | 208f344 | 2024-01-05 12:23:10 -0800 | [diff] [blame] | 1830 | quiet=not opt.verbose, |
| Jason Chang | daf2ad3 | 2023-08-31 17:06:36 -0700 | [diff] [blame] | 1831 | output_redir=buf, |
| 1832 | verbose=opt.verbose, |
| 1833 | current_branch_only=self._GetCurrentBranchOnly( |
| 1834 | opt, mp.manifest |
| 1835 | ), |
| 1836 | force_sync=opt.force_sync, |
| 1837 | tags=opt.tags, |
| 1838 | optimized_fetch=opt.optimized_fetch, |
| 1839 | retry_fetches=opt.retry_fetches, |
| 1840 | submodules=mp.manifest.HasSubmodules, |
| 1841 | clone_filter=mp.manifest.CloneFilter, |
| 1842 | partial_clone_exclude=mp.manifest.PartialCloneExclude, |
| 1843 | clone_filter_for_depth=mp.manifest.CloneFilterForDepth, |
| 1844 | ) |
| 1845 | if result.error: |
| 1846 | errors.append(result.error) |
| 1847 | except KeyboardInterrupt: |
| 1848 | errors.append( |
| 1849 | ManifestInterruptError(buf.getvalue(), project=mp.name) |
| 1850 | ) |
| 1851 | raise |
| 1852 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1853 | finish = time.time() |
| 1854 | self.event_log.AddSync( |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1855 | mp, event_log.TASK_SYNC_NETWORK, start, finish, result.success |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1856 | ) |
| 1857 | |
| 1858 | if mp.HasChanges: |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1859 | errors = [] |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1860 | syncbuf = SyncBuffer(mp.config) |
| 1861 | start = time.time() |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1862 | mp.Sync_LocalHalf( |
| Tomasz Wasilczyk | 4c80921 | 2023-12-08 13:42:17 -0800 | [diff] [blame] | 1863 | syncbuf, |
| 1864 | submodules=mp.manifest.HasSubmodules, |
| Tomasz Wasilczyk | 4c80921 | 2023-12-08 13:42:17 -0800 | [diff] [blame] | 1865 | verbose=opt.verbose, |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1866 | ) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1867 | clean = syncbuf.Finish() |
| Gavin Mak | a64149a | 2025-08-13 22:48:36 -0700 | [diff] [blame] | 1868 | errors.extend(syncbuf.errors) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1869 | self.event_log.AddSync( |
| 1870 | mp, event_log.TASK_SYNC_LOCAL, start, time.time(), clean |
| 1871 | ) |
| 1872 | if not clean: |
| Yiwei Zhang | d379e77 | 2023-12-20 20:39:59 +0000 | [diff] [blame] | 1873 | raise UpdateManifestError(aggregate_errors=errors) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1874 | self._ReloadManifest(manifest_name, mp.manifest) |
| 1875 | |
| 1876 | def ValidateOptions(self, opt, args): |
| 1877 | if opt.force_broken: |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 1878 | logger.warning( |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1879 | "warning: -f/--force-broken is now the default behavior, and " |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 1880 | "the options are deprecated" |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1881 | ) |
| 1882 | if opt.network_only and opt.detach_head: |
| 1883 | self.OptionParser.error("cannot combine -n and -d") |
| 1884 | if opt.network_only and opt.local_only: |
| 1885 | self.OptionParser.error("cannot combine -n and -l") |
| 1886 | if opt.manifest_name and opt.smart_sync: |
| 1887 | self.OptionParser.error("cannot combine -m and -s") |
| 1888 | if opt.manifest_name and opt.smart_tag: |
| 1889 | self.OptionParser.error("cannot combine -m and -t") |
| 1890 | if opt.manifest_server_username or opt.manifest_server_password: |
| 1891 | if not (opt.smart_sync or opt.smart_tag): |
| 1892 | self.OptionParser.error( |
| 1893 | "-u and -p may only be combined with -s or -t" |
| 1894 | ) |
| 1895 | if None in [ |
| 1896 | opt.manifest_server_username, |
| 1897 | opt.manifest_server_password, |
| 1898 | ]: |
| 1899 | self.OptionParser.error("both -u and -p must be given") |
| 1900 | |
| 1901 | if opt.prune is None: |
| 1902 | opt.prune = True |
| 1903 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1904 | def _ValidateOptionsWithManifest(self, opt, mp): |
| 1905 | """Like ValidateOptions, but after we've updated the manifest. |
| 1906 | |
| 1907 | Needed to handle sync-xxx option defaults in the manifest. |
| 1908 | |
| 1909 | Args: |
| 1910 | opt: The options to process. |
| 1911 | mp: The manifest project to pull defaults from. |
| 1912 | """ |
| 1913 | if not opt.jobs: |
| 1914 | # If the user hasn't made a choice, use the manifest value. |
| 1915 | opt.jobs = mp.manifest.default.sync_j |
| 1916 | if opt.jobs: |
| 1917 | # If --jobs has a non-default value, propagate it as the default for |
| 1918 | # --jobs-xxx flags too. |
| 1919 | if not opt.jobs_network: |
| 1920 | opt.jobs_network = opt.jobs |
| 1921 | if not opt.jobs_checkout: |
| 1922 | opt.jobs_checkout = opt.jobs |
| 1923 | else: |
| 1924 | # Neither user nor manifest have made a choice, so setup defaults. |
| 1925 | if not opt.jobs_network: |
| 1926 | opt.jobs_network = 1 |
| 1927 | if not opt.jobs_checkout: |
| 1928 | opt.jobs_checkout = DEFAULT_LOCAL_JOBS |
| 1929 | opt.jobs = os.cpu_count() |
| 1930 | |
| 1931 | # Try to stay under user rlimit settings. |
| 1932 | # |
| 1933 | # Since each worker requires at 3 file descriptors to run `git fetch`, |
| 1934 | # use that to scale down the number of jobs. Unfortunately there isn't |
| 1935 | # an easy way to determine this reliably as systems change, but it was |
| 1936 | # last measured by hand in 2011. |
| 1937 | soft_limit, _ = _rlimit_nofile() |
| 1938 | jobs_soft_limit = max(1, (soft_limit - 5) // 3) |
| 1939 | opt.jobs = min(opt.jobs, jobs_soft_limit) |
| 1940 | opt.jobs_network = min(opt.jobs_network, jobs_soft_limit) |
| 1941 | opt.jobs_checkout = min(opt.jobs_checkout, jobs_soft_limit) |
| 1942 | |
| Gavin Mak | daebd6c | 2025-04-09 13:59:27 -0700 | [diff] [blame] | 1943 | # Warn once if effective job counts seem excessively high. |
| 1944 | # Prioritize --jobs, then --jobs-network, then --jobs-checkout. |
| 1945 | job_options_to_check = ( |
| 1946 | ("--jobs", opt.jobs), |
| 1947 | ("--jobs-network", opt.jobs_network), |
| 1948 | ("--jobs-checkout", opt.jobs_checkout), |
| 1949 | ) |
| 1950 | for name, value in job_options_to_check: |
| 1951 | if value > self._JOBS_WARN_THRESHOLD: |
| 1952 | logger.warning( |
| 1953 | "High job count (%d > %d) specified for %s; this may " |
| 1954 | "lead to excessive resource usage or diminishing returns.", |
| 1955 | value, |
| 1956 | self._JOBS_WARN_THRESHOLD, |
| 1957 | name, |
| 1958 | ) |
| 1959 | break |
| 1960 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1961 | def Execute(self, opt, args): |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1962 | errors = [] |
| 1963 | try: |
| 1964 | self._ExecuteHelper(opt, args, errors) |
| Jason Chang | 26fa318 | 2024-02-05 15:15:20 -0800 | [diff] [blame] | 1965 | except (RepoExitError, RepoChangedException): |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1966 | raise |
| 1967 | except (KeyboardInterrupt, Exception) as e: |
| 1968 | raise RepoUnhandledExceptionError(e, aggregate_errors=errors) |
| 1969 | |
| Kenny Cheng | 82d500e | 2025-06-02 21:55:04 +0800 | [diff] [blame] | 1970 | # Run post-sync hook only after successful sync |
| 1971 | self._RunPostSyncHook(opt) |
| 1972 | |
| 1973 | def _RunPostSyncHook(self, opt): |
| 1974 | """Run post-sync hook if configured in manifest <repo-hooks>.""" |
| 1975 | hook = RepoHook.FromSubcmd( |
| 1976 | hook_type="post-sync", |
| 1977 | manifest=self.manifest, |
| 1978 | opt=opt, |
| 1979 | abort_if_user_denies=False, |
| 1980 | ) |
| 1981 | success = hook.Run(repo_topdir=self.client.topdir) |
| 1982 | if not success: |
| 1983 | print("Warning: post-sync hook reported failure.") |
| 1984 | |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 1985 | def _ExecuteHelper(self, opt, args, errors): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 1986 | manifest = self.outer_manifest |
| 1987 | if not opt.outer_manifest: |
| 1988 | manifest = self.manifest |
| 1989 | |
| 1990 | if opt.manifest_name: |
| 1991 | manifest.Override(opt.manifest_name) |
| 1992 | |
| 1993 | manifest_name = opt.manifest_name |
| 1994 | smart_sync_manifest_path = os.path.join( |
| 1995 | manifest.manifestProject.worktree, "smart_sync_override.xml" |
| 1996 | ) |
| 1997 | |
| 1998 | if opt.clone_bundle is None: |
| 1999 | opt.clone_bundle = manifest.CloneBundle |
| 2000 | |
| 2001 | if opt.smart_sync or opt.smart_tag: |
| 2002 | manifest_name = self._SmartSyncSetup( |
| 2003 | opt, smart_sync_manifest_path, manifest |
| 2004 | ) |
| 2005 | else: |
| 2006 | if os.path.isfile(smart_sync_manifest_path): |
| 2007 | try: |
| 2008 | platform_utils.remove(smart_sync_manifest_path) |
| 2009 | except OSError as e: |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 2010 | logger.error( |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2011 | "error: failed to remove existing smart sync override " |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 2012 | "manifest: %s", |
| 2013 | e, |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2014 | ) |
| 2015 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2016 | rp = manifest.repoProject |
| 2017 | rp.PreSync() |
| 2018 | cb = rp.CurrentBranch |
| 2019 | if cb: |
| 2020 | base = rp.GetBranch(cb).merge |
| 2021 | if not base or not base.startswith("refs/heads/"): |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 2022 | logger.warning( |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2023 | "warning: repo is not tracking a remote branch, so it will " |
| 2024 | "not receive updates; run `repo init --repo-rev=stable` to " |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 2025 | "fix." |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2026 | ) |
| 2027 | |
| 2028 | for m in self.ManifestList(opt): |
| 2029 | if not m.manifestProject.standalone_manifest_url: |
| 2030 | m.manifestProject.PreSync() |
| 2031 | |
| 2032 | if opt.repo_upgraded: |
| 2033 | _PostRepoUpgrade(manifest, quiet=opt.quiet) |
| 2034 | |
| 2035 | mp = manifest.manifestProject |
| Jason Chang | 1783332 | 2023-05-23 13:06:55 -0700 | [diff] [blame] | 2036 | |
| 2037 | if _REPO_ALLOW_SHALLOW is not None: |
| 2038 | if _REPO_ALLOW_SHALLOW == "1": |
| 2039 | mp.ConfigureCloneFilterForDepth(None) |
| 2040 | elif ( |
| 2041 | _REPO_ALLOW_SHALLOW == "0" and mp.clone_filter_for_depth is None |
| 2042 | ): |
| 2043 | mp.ConfigureCloneFilterForDepth("blob:none") |
| 2044 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2045 | if opt.mp_update: |
| Jason Chang | daf2ad3 | 2023-08-31 17:06:36 -0700 | [diff] [blame] | 2046 | self._UpdateAllManifestProjects(opt, mp, manifest_name, errors) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2047 | else: |
| Aravind Vasudevan | 83c66ec | 2023-09-28 19:06:59 +0000 | [diff] [blame] | 2048 | print("Skipping update of local manifest project.") |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2049 | |
| 2050 | # Now that the manifests are up-to-date, setup options whose defaults |
| 2051 | # might be in the manifest. |
| 2052 | self._ValidateOptionsWithManifest(opt, mp) |
| 2053 | |
| Gavin Mak | f7a3f99 | 2025-06-23 09:04:26 -0700 | [diff] [blame] | 2054 | # Update the repo project and check for new versions of repo. |
| 2055 | self._UpdateRepoProject(opt, manifest, errors) |
| 2056 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2057 | superproject_logging_data = {} |
| 2058 | self._UpdateProjectsRevisionId( |
| 2059 | opt, args, superproject_logging_data, manifest |
| 2060 | ) |
| 2061 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2062 | all_projects = self.GetProjects( |
| 2063 | args, |
| 2064 | missing_ok=True, |
| 2065 | submodules_ok=opt.fetch_submodules, |
| 2066 | manifest=manifest, |
| 2067 | all_manifests=not opt.this_manifest_only, |
| 2068 | ) |
| 2069 | |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 2070 | # Log the repo projects by existing and new. |
| 2071 | existing = [x for x in all_projects if x.Exists] |
| 2072 | mp.config.SetString("repo.existingprojectcount", str(len(existing))) |
| 2073 | mp.config.SetString( |
| 2074 | "repo.newprojectcount", str(len(all_projects) - len(existing)) |
| 2075 | ) |
| 2076 | |
| 2077 | self._fetch_times = _FetchTimes(manifest) |
| 2078 | self._local_sync_state = LocalSyncState(manifest) |
| 2079 | |
| Gavin Mak | 8535282 | 2025-06-11 00:13:52 +0000 | [diff] [blame] | 2080 | if opt.interleaved: |
| 2081 | sync_method = self._SyncInterleaved |
| 2082 | else: |
| 2083 | sync_method = self._SyncPhased |
| 2084 | |
| 2085 | sync_method( |
| 2086 | opt, |
| 2087 | args, |
| 2088 | errors, |
| 2089 | manifest, |
| 2090 | mp, |
| 2091 | all_projects, |
| 2092 | superproject_logging_data, |
| 2093 | ) |
| 2094 | |
| 2095 | # Log the previous sync analysis state from the config. |
| 2096 | self.git_event_log.LogDataConfigEvents( |
| 2097 | mp.config.GetSyncAnalysisStateData(), "previous_sync_state" |
| 2098 | ) |
| 2099 | |
| 2100 | # Update and log with the new sync analysis state. |
| 2101 | mp.config.UpdateSyncAnalysisState(opt, superproject_logging_data) |
| 2102 | self.git_event_log.LogDataConfigEvents( |
| 2103 | mp.config.GetSyncAnalysisStateData(), "current_sync_state" |
| 2104 | ) |
| 2105 | |
| 2106 | self._local_sync_state.PruneRemovedProjects() |
| 2107 | if self._local_sync_state.IsPartiallySynced(): |
| 2108 | logger.warning( |
| 2109 | "warning: Partial syncs are not supported. For the best " |
| 2110 | "experience, sync the entire tree." |
| 2111 | ) |
| 2112 | |
| Gavin Mak | 871e4c7 | 2025-12-15 20:08:59 +0000 | [diff] [blame] | 2113 | if existing: |
| 2114 | self._CheckForBloatedProjects(all_projects, opt) |
| Gavin Mak | b5991d7 | 2025-12-09 22:29:43 +0000 | [diff] [blame] | 2115 | |
| Gavin Mak | 8535282 | 2025-06-11 00:13:52 +0000 | [diff] [blame] | 2116 | if not opt.quiet: |
| 2117 | print("repo sync has finished successfully.") |
| 2118 | |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 2119 | def _CreateSyncProgressThread( |
| 2120 | self, pm: Progress, stop_event: _threading.Event |
| 2121 | ) -> _threading.Thread: |
| 2122 | """Creates and returns a daemon thread to update a Progress object. |
| 2123 | |
| 2124 | The returned thread is not yet started. The thread will periodically |
| 2125 | update the progress bar with information from _GetSyncProgressMessage |
| 2126 | until the stop_event is set. |
| 2127 | |
| 2128 | Args: |
| 2129 | pm: The Progress object to update. |
| 2130 | stop_event: The threading.Event to signal the monitor to stop. |
| 2131 | |
| 2132 | Returns: |
| 2133 | The configured _threading.Thread object. |
| 2134 | """ |
| 2135 | |
| 2136 | def _monitor_loop(): |
| 2137 | """The target function for the monitor thread.""" |
| 2138 | while True: |
| 2139 | # Update the progress bar with the current status message. |
| 2140 | pm.update(inc=0, msg=self._GetSyncProgressMessage()) |
| 2141 | # Wait for 1 second or until the stop_event is set. |
| 2142 | if stop_event.wait(timeout=1): |
| 2143 | return |
| 2144 | |
| 2145 | return _threading.Thread(target=_monitor_loop, daemon=True) |
| 2146 | |
| Gavin Mak | df3c401 | 2025-06-17 19:40:06 -0700 | [diff] [blame] | 2147 | def _UpdateManifestLists( |
| 2148 | self, |
| 2149 | opt: optparse.Values, |
| 2150 | err_event: multiprocessing.Event, |
| 2151 | errors: List[Exception], |
| 2152 | ) -> Tuple[bool, bool]: |
| 2153 | """Updates project lists and copy/link files for all manifests. |
| 2154 | |
| 2155 | Args: |
| 2156 | opt: Program options from optparse. |
| 2157 | err_event: An event to set if any error occurs. |
| 2158 | errors: A list to append any encountered exceptions to. |
| 2159 | |
| 2160 | Returns: |
| 2161 | A tuple (err_update_projects, err_update_linkfiles) indicating |
| 2162 | an error for each task. |
| 2163 | """ |
| 2164 | err_update_projects = False |
| 2165 | err_update_linkfiles = False |
| 2166 | for m in self.ManifestList(opt): |
| 2167 | if m.IsMirror or m.IsArchive: |
| 2168 | continue |
| 2169 | |
| 2170 | try: |
| 2171 | self.UpdateProjectList(opt, m) |
| 2172 | except Exception as e: |
| 2173 | err_event.set() |
| 2174 | err_update_projects = True |
| 2175 | errors.append(e) |
| 2176 | if isinstance(e, DeleteWorktreeError): |
| 2177 | errors.extend(e.aggregate_errors) |
| 2178 | if opt.fail_fast: |
| 2179 | logger.error("error: Local checkouts *not* updated.") |
| 2180 | raise SyncFailFastError(aggregate_errors=errors) |
| 2181 | |
| 2182 | try: |
| 2183 | self.UpdateCopyLinkfileList(m) |
| 2184 | except Exception as e: |
| 2185 | err_event.set() |
| 2186 | err_update_linkfiles = True |
| 2187 | errors.append(e) |
| 2188 | if opt.fail_fast: |
| 2189 | logger.error( |
| 2190 | "error: Local update copyfile or linkfile failed." |
| 2191 | ) |
| 2192 | raise SyncFailFastError(aggregate_errors=errors) |
| 2193 | return err_update_projects, err_update_linkfiles |
| 2194 | |
| Gavin Mak | 99b5a17 | 2025-06-17 20:15:50 -0700 | [diff] [blame] | 2195 | def _ReportErrors( |
| 2196 | self, |
| 2197 | errors, |
| 2198 | err_network_sync=False, |
| 2199 | failing_network_repos=None, |
| 2200 | err_checkout=False, |
| 2201 | failing_checkout_repos=None, |
| 2202 | err_update_projects=False, |
| 2203 | err_update_linkfiles=False, |
| 2204 | ): |
| 2205 | """Logs detailed error messages and raises a SyncError.""" |
| 2206 | |
| 2207 | def print_and_log(err_msg): |
| 2208 | self.git_event_log.ErrorEvent(err_msg) |
| 2209 | logger.error("%s", err_msg) |
| 2210 | |
| 2211 | print_and_log("error: Unable to fully sync the tree") |
| 2212 | if err_network_sync: |
| 2213 | print_and_log("error: Downloading network changes failed.") |
| 2214 | if failing_network_repos: |
| 2215 | logger.error( |
| 2216 | "Failing repos (network):\n%s", |
| 2217 | "\n".join(sorted(failing_network_repos)), |
| 2218 | ) |
| 2219 | if err_update_projects: |
| 2220 | print_and_log("error: Updating local project lists failed.") |
| 2221 | if err_update_linkfiles: |
| 2222 | print_and_log("error: Updating copyfiles or linkfiles failed.") |
| 2223 | if err_checkout: |
| 2224 | print_and_log("error: Checking out local projects failed.") |
| 2225 | if failing_checkout_repos: |
| 2226 | logger.error( |
| 2227 | "Failing repos (checkout):\n%s", |
| 2228 | "\n".join(sorted(failing_checkout_repos)), |
| 2229 | ) |
| 2230 | logger.error( |
| 2231 | 'Try re-running with "-j1 --fail-fast" to exit at the first error.' |
| 2232 | ) |
| 2233 | raise SyncError(aggregate_errors=errors) |
| 2234 | |
| Gavin Mak | 8535282 | 2025-06-11 00:13:52 +0000 | [diff] [blame] | 2235 | def _SyncPhased( |
| 2236 | self, |
| 2237 | opt, |
| 2238 | args, |
| 2239 | errors, |
| 2240 | manifest, |
| 2241 | mp, |
| 2242 | all_projects, |
| 2243 | superproject_logging_data, |
| 2244 | ): |
| 2245 | """Sync projects by separating network and local operations. |
| 2246 | |
| 2247 | This method performs sync in two distinct, sequential phases: |
| 2248 | 1. Network Phase: Fetches updates for all projects from their remotes. |
| 2249 | 2. Local Phase: Checks out the updated revisions into the local |
| 2250 | worktrees for all projects. |
| 2251 | |
| 2252 | This approach ensures that the local work-tree is not modified until |
| 2253 | all network operations are complete, providing a transactional-like |
| 2254 | safety net for the checkout state. |
| 2255 | """ |
| 2256 | err_event = multiprocessing.Event() |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2257 | err_network_sync = False |
| 2258 | err_update_projects = False |
| 2259 | err_update_linkfiles = False |
| 2260 | |
| Josip Sokcevic | 5ae8292 | 2025-01-31 12:00:52 -0800 | [diff] [blame] | 2261 | if not opt.local_only: |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2262 | with multiprocessing.Manager() as manager: |
| 2263 | with ssh.ProxyManager(manager) as ssh_proxy: |
| 2264 | # Initialize the socket dir once in the parent. |
| 2265 | ssh_proxy.sock() |
| 2266 | result = self._FetchMain( |
| Jason Chang | daf2ad3 | 2023-08-31 17:06:36 -0700 | [diff] [blame] | 2267 | opt, |
| 2268 | args, |
| 2269 | all_projects, |
| 2270 | err_event, |
| 2271 | ssh_proxy, |
| 2272 | manifest, |
| 2273 | errors, |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2274 | ) |
| 2275 | all_projects = result.all_projects |
| 2276 | |
| 2277 | if opt.network_only: |
| 2278 | return |
| 2279 | |
| 2280 | # If we saw an error, exit with code 1 so that other scripts can |
| 2281 | # check. |
| 2282 | if err_event.is_set(): |
| 2283 | err_network_sync = True |
| 2284 | if opt.fail_fast: |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 2285 | logger.error( |
| 2286 | "error: Exited sync due to fetch errors.\n" |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2287 | "Local checkouts *not* updated. Resolve network issues " |
| 2288 | "& retry.\n" |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 2289 | "`repo sync -l` will update some local checkouts." |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2290 | ) |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 2291 | raise SyncFailFastError(aggregate_errors=errors) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2292 | |
| Gavin Mak | df3c401 | 2025-06-17 19:40:06 -0700 | [diff] [blame] | 2293 | err_update_projects, err_update_linkfiles = self._UpdateManifestLists( |
| 2294 | opt, |
| 2295 | err_event, |
| 2296 | errors, |
| 2297 | ) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2298 | |
| 2299 | err_results = [] |
| 2300 | # NB: We don't exit here because this is the last step. |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 2301 | err_checkout = not self._Checkout( |
| 2302 | all_projects, opt, err_results, errors |
| 2303 | ) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2304 | if err_checkout: |
| 2305 | err_event.set() |
| 2306 | |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2307 | self._PrintManifestNotices(opt) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2308 | |
| 2309 | # If we saw an error, exit with code 1 so that other scripts can check. |
| 2310 | if err_event.is_set(): |
| Gavin Mak | 99b5a17 | 2025-06-17 20:15:50 -0700 | [diff] [blame] | 2311 | self._ReportErrors( |
| 2312 | errors, |
| 2313 | err_network_sync=err_network_sync, |
| 2314 | err_checkout=err_checkout, |
| 2315 | failing_checkout_repos=err_results, |
| 2316 | err_update_projects=err_update_projects, |
| 2317 | err_update_linkfiles=err_update_linkfiles, |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2318 | ) |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2319 | |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 2320 | @classmethod |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2321 | def _SyncOneProject(cls, opt, project_index, project) -> _SyncResult: |
| 2322 | """Syncs a single project for interleaved sync.""" |
| 2323 | fetch_success = False |
| 2324 | remote_fetched = False |
| Gavin Mak | d534a55 | 2025-08-13 23:42:00 -0700 | [diff] [blame] | 2325 | fetch_errors = [] |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2326 | fetch_start = None |
| 2327 | fetch_finish = None |
| 2328 | network_output = "" |
| 2329 | |
| 2330 | if opt.local_only: |
| 2331 | fetch_success = True |
| 2332 | else: |
| 2333 | fetch_start = time.time() |
| 2334 | network_output_capture = io.StringIO() |
| 2335 | try: |
| 2336 | ssh_proxy = cls.get_parallel_context().get("ssh_proxy") |
| 2337 | sync_result = project.Sync_NetworkHalf( |
| 2338 | quiet=opt.quiet, |
| 2339 | verbose=opt.verbose, |
| 2340 | output_redir=network_output_capture, |
| 2341 | current_branch_only=cls._GetCurrentBranchOnly( |
| 2342 | opt, project.manifest |
| 2343 | ), |
| 2344 | force_sync=opt.force_sync, |
| 2345 | clone_bundle=opt.clone_bundle, |
| 2346 | tags=opt.tags, |
| 2347 | archive=project.manifest.IsArchive, |
| 2348 | optimized_fetch=opt.optimized_fetch, |
| 2349 | retry_fetches=opt.retry_fetches, |
| 2350 | prune=opt.prune, |
| 2351 | ssh_proxy=ssh_proxy, |
| 2352 | clone_filter=project.manifest.CloneFilter, |
| 2353 | partial_clone_exclude=project.manifest.PartialCloneExclude, |
| 2354 | clone_filter_for_depth=project.manifest.CloneFilterForDepth, |
| 2355 | ) |
| 2356 | fetch_success = sync_result.success |
| 2357 | remote_fetched = sync_result.remote_fetched |
| Gavin Mak | d534a55 | 2025-08-13 23:42:00 -0700 | [diff] [blame] | 2358 | if sync_result.error: |
| 2359 | fetch_errors.append(sync_result.error) |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2360 | except KeyboardInterrupt: |
| 2361 | logger.error( |
| 2362 | "Keyboard interrupt while processing %s", project.name |
| 2363 | ) |
| 2364 | except GitError as e: |
| Gavin Mak | d534a55 | 2025-08-13 23:42:00 -0700 | [diff] [blame] | 2365 | fetch_errors.append(e) |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2366 | logger.error("error.GitError: Cannot fetch %s", e) |
| 2367 | except Exception as e: |
| Gavin Mak | d534a55 | 2025-08-13 23:42:00 -0700 | [diff] [blame] | 2368 | fetch_errors.append(e) |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2369 | logger.error( |
| 2370 | "error: Cannot fetch %s (%s: %s)", |
| 2371 | project.name, |
| 2372 | type(e).__name__, |
| 2373 | e, |
| 2374 | ) |
| 2375 | finally: |
| 2376 | fetch_finish = time.time() |
| 2377 | network_output = network_output_capture.getvalue() |
| 2378 | |
| 2379 | checkout_success = False |
| Gavin Mak | d534a55 | 2025-08-13 23:42:00 -0700 | [diff] [blame] | 2380 | checkout_errors = [] |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2381 | checkout_start = None |
| 2382 | checkout_finish = None |
| 2383 | checkout_stderr = "" |
| 2384 | |
| Gavin Mak | 720bd1e | 2025-07-23 15:23:10 -0700 | [diff] [blame] | 2385 | if fetch_success: |
| 2386 | # We skip checkout if it's network-only or if the project has no |
| 2387 | # working tree (e.g., a mirror). |
| 2388 | if opt.network_only or not project.worktree: |
| 2389 | checkout_success = True |
| 2390 | else: |
| 2391 | # This is a normal project that needs a checkout. |
| 2392 | checkout_start = time.time() |
| 2393 | stderr_capture = io.StringIO() |
| 2394 | try: |
| 2395 | with contextlib.redirect_stderr(stderr_capture): |
| 2396 | syncbuf = SyncBuffer( |
| 2397 | project.manifest.manifestProject.config, |
| 2398 | detach_head=opt.detach_head, |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2399 | ) |
| Gavin Mak | 720bd1e | 2025-07-23 15:23:10 -0700 | [diff] [blame] | 2400 | project.Sync_LocalHalf( |
| 2401 | syncbuf, |
| 2402 | force_sync=opt.force_sync, |
| 2403 | force_checkout=opt.force_checkout, |
| 2404 | force_rebase=opt.rebase, |
| Gavin Mak | 720bd1e | 2025-07-23 15:23:10 -0700 | [diff] [blame] | 2405 | verbose=opt.verbose, |
| 2406 | ) |
| 2407 | checkout_success = syncbuf.Finish() |
| Gavin Mak | a64149a | 2025-08-13 22:48:36 -0700 | [diff] [blame] | 2408 | if syncbuf.errors: |
| Gavin Mak | d534a55 | 2025-08-13 23:42:00 -0700 | [diff] [blame] | 2409 | checkout_errors.extend(syncbuf.errors) |
| Gavin Mak | 720bd1e | 2025-07-23 15:23:10 -0700 | [diff] [blame] | 2410 | except KeyboardInterrupt: |
| 2411 | logger.error( |
| 2412 | "Keyboard interrupt while processing %s", project.name |
| 2413 | ) |
| 2414 | except GitError as e: |
| Gavin Mak | d534a55 | 2025-08-13 23:42:00 -0700 | [diff] [blame] | 2415 | checkout_errors.append(e) |
| Gavin Mak | 720bd1e | 2025-07-23 15:23:10 -0700 | [diff] [blame] | 2416 | logger.error( |
| 2417 | "error.GitError: Cannot checkout %s: %s", |
| 2418 | project.name, |
| 2419 | e, |
| 2420 | ) |
| 2421 | except Exception as e: |
| Gavin Mak | d534a55 | 2025-08-13 23:42:00 -0700 | [diff] [blame] | 2422 | checkout_errors.append(e) |
| Gavin Mak | 720bd1e | 2025-07-23 15:23:10 -0700 | [diff] [blame] | 2423 | logger.error( |
| 2424 | "error: Cannot checkout %s: %s: %s", |
| 2425 | project.name, |
| 2426 | type(e).__name__, |
| 2427 | e, |
| 2428 | ) |
| 2429 | finally: |
| 2430 | checkout_finish = time.time() |
| 2431 | checkout_stderr = stderr_capture.getvalue() |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2432 | |
| 2433 | # Consolidate all captured output. |
| 2434 | captured_parts = [] |
| 2435 | if network_output: |
| 2436 | captured_parts.append(network_output) |
| 2437 | if checkout_stderr: |
| 2438 | captured_parts.append(checkout_stderr) |
| 2439 | stderr_text = "\n".join(captured_parts) |
| 2440 | |
| 2441 | return _SyncResult( |
| 2442 | project_index=project_index, |
| 2443 | relpath=project.relpath, |
| 2444 | fetch_success=fetch_success, |
| 2445 | remote_fetched=remote_fetched, |
| 2446 | checkout_success=checkout_success, |
| Gavin Mak | d534a55 | 2025-08-13 23:42:00 -0700 | [diff] [blame] | 2447 | fetch_errors=fetch_errors, |
| 2448 | checkout_errors=checkout_errors, |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2449 | stderr_text=stderr_text.strip(), |
| 2450 | fetch_start=fetch_start, |
| 2451 | fetch_finish=fetch_finish, |
| 2452 | checkout_start=checkout_start, |
| 2453 | checkout_finish=checkout_finish, |
| 2454 | ) |
| 2455 | |
| 2456 | @classmethod |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 2457 | def _SyncProjectList(cls, opt, project_indices) -> _InterleavedSyncResult: |
| 2458 | """Worker for interleaved sync. |
| 2459 | |
| 2460 | This function is responsible for syncing a group of projects that share |
| 2461 | a git object directory. |
| 2462 | |
| 2463 | Args: |
| 2464 | opt: Program options returned from optparse. See _Options(). |
| 2465 | project_indices: A list of indices into the projects list stored in |
| 2466 | the parallel context. |
| 2467 | |
| 2468 | Returns: |
| 2469 | An `_InterleavedSyncResult` containing the results for each project. |
| 2470 | """ |
| 2471 | results = [] |
| 2472 | context = cls.get_parallel_context() |
| 2473 | projects = context["projects"] |
| 2474 | sync_dict = context["sync_dict"] |
| 2475 | |
| 2476 | assert project_indices, "_SyncProjectList called with no indices." |
| 2477 | |
| 2478 | # Use the first project as the representative for the progress bar. |
| 2479 | first_project = projects[project_indices[0]] |
| 2480 | key = f"{first_project.name} @ {first_project.relpath}" |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2481 | sync_dict[key] = time.time() |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 2482 | |
| 2483 | try: |
| 2484 | for idx in project_indices: |
| 2485 | project = projects[idx] |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2486 | results.append(cls._SyncOneProject(opt, idx, project)) |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 2487 | finally: |
| 2488 | del sync_dict[key] |
| 2489 | |
| 2490 | return _InterleavedSyncResult(results=results) |
| 2491 | |
| 2492 | def _ProcessSyncInterleavedResults( |
| 2493 | self, |
| Gavin Mak | a6e1a59 | 2025-08-13 01:51:59 +0000 | [diff] [blame] | 2494 | finished_relpaths: Set[str], |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 2495 | err_event: _threading.Event, |
| 2496 | errors: List[Exception], |
| 2497 | opt: optparse.Values, |
| 2498 | pool: Optional[multiprocessing.Pool], |
| 2499 | pm: Progress, |
| 2500 | results_sets: List[_InterleavedSyncResult], |
| 2501 | ): |
| 2502 | """Callback to process results from interleaved sync workers.""" |
| 2503 | ret = True |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2504 | projects = self.get_parallel_context()["projects"] |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 2505 | for result_group in results_sets: |
| 2506 | for result in result_group.results: |
| 2507 | pm.update() |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2508 | project = projects[result.project_index] |
| 2509 | |
| Gavin Mak | 380bf95 | 2025-08-13 01:10:37 +0000 | [diff] [blame] | 2510 | success = result.fetch_success and result.checkout_success |
| 2511 | if result.stderr_text and (opt.verbose or not success): |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2512 | pm.display_message(result.stderr_text) |
| 2513 | |
| 2514 | if result.fetch_start: |
| 2515 | self._fetch_times.Set( |
| 2516 | project, |
| 2517 | result.fetch_finish - result.fetch_start, |
| 2518 | ) |
| 2519 | self._local_sync_state.SetFetchTime(project) |
| 2520 | self.event_log.AddSync( |
| 2521 | project, |
| 2522 | event_log.TASK_SYNC_NETWORK, |
| 2523 | result.fetch_start, |
| 2524 | result.fetch_finish, |
| 2525 | result.fetch_success, |
| 2526 | ) |
| 2527 | if result.checkout_start: |
| 2528 | if result.checkout_success: |
| 2529 | self._local_sync_state.SetCheckoutTime(project) |
| 2530 | self.event_log.AddSync( |
| 2531 | project, |
| 2532 | event_log.TASK_SYNC_LOCAL, |
| 2533 | result.checkout_start, |
| 2534 | result.checkout_finish, |
| 2535 | result.checkout_success, |
| 2536 | ) |
| 2537 | |
| Gavin Mak | a6e1a59 | 2025-08-13 01:51:59 +0000 | [diff] [blame] | 2538 | finished_relpaths.add(result.relpath) |
| 2539 | |
| 2540 | if not success: |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 2541 | ret = False |
| 2542 | err_event.set() |
| Gavin Mak | d534a55 | 2025-08-13 23:42:00 -0700 | [diff] [blame] | 2543 | if result.fetch_errors: |
| 2544 | errors.extend(result.fetch_errors) |
| Gavin Mak | 99b5a17 | 2025-06-17 20:15:50 -0700 | [diff] [blame] | 2545 | self._interleaved_err_network = True |
| 2546 | self._interleaved_err_network_results.append( |
| 2547 | result.relpath |
| 2548 | ) |
| Gavin Mak | d534a55 | 2025-08-13 23:42:00 -0700 | [diff] [blame] | 2549 | if result.checkout_errors: |
| 2550 | errors.extend(result.checkout_errors) |
| Gavin Mak | 99b5a17 | 2025-06-17 20:15:50 -0700 | [diff] [blame] | 2551 | self._interleaved_err_checkout = True |
| 2552 | self._interleaved_err_checkout_results.append( |
| 2553 | result.relpath |
| 2554 | ) |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 2555 | |
| 2556 | if not ret and opt.fail_fast: |
| 2557 | if pool: |
| 2558 | pool.close() |
| 2559 | break |
| 2560 | return ret |
| 2561 | |
| Gavin Mak | 8535282 | 2025-06-11 00:13:52 +0000 | [diff] [blame] | 2562 | def _SyncInterleaved( |
| 2563 | self, |
| 2564 | opt, |
| 2565 | args, |
| 2566 | errors, |
| 2567 | manifest, |
| 2568 | mp, |
| 2569 | all_projects, |
| 2570 | superproject_logging_data, |
| 2571 | ): |
| 2572 | """Sync projects by performing network and local operations in parallel. |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2573 | |
| Gavin Mak | 8535282 | 2025-06-11 00:13:52 +0000 | [diff] [blame] | 2574 | This method processes each project (or groups of projects that share git |
| 2575 | objects) independently. For each project, it performs the fetch and |
| 2576 | checkout operations back-to-back. These independent tasks are run in |
| 2577 | parallel. |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2578 | |
| Gavin Mak | 8535282 | 2025-06-11 00:13:52 +0000 | [diff] [blame] | 2579 | It respects two constraints for correctness: |
| 2580 | 1. Projects in nested directories (e.g. 'foo' and 'foo/bar') are |
| 2581 | processed in hierarchical order. |
| 2582 | 2. Projects that share git objects are processed serially to prevent |
| 2583 | race conditions. |
| 2584 | """ |
| Gavin Mak | 99b5a17 | 2025-06-17 20:15:50 -0700 | [diff] [blame] | 2585 | # Temporary state for tracking errors in interleaved mode. |
| 2586 | self._interleaved_err_network = False |
| 2587 | self._interleaved_err_network_results = [] |
| 2588 | self._interleaved_err_checkout = False |
| 2589 | self._interleaved_err_checkout_results = [] |
| 2590 | |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 2591 | err_event = multiprocessing.Event() |
| Gavin Mak | a6e1a59 | 2025-08-13 01:51:59 +0000 | [diff] [blame] | 2592 | finished_relpaths = set() |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 2593 | project_list = list(all_projects) |
| 2594 | pm = Progress( |
| 2595 | "Syncing", |
| 2596 | len(project_list), |
| 2597 | delay=False, |
| 2598 | quiet=opt.quiet, |
| 2599 | show_elapsed=True, |
| 2600 | elide=True, |
| 2601 | ) |
| 2602 | previously_pending_relpaths = set() |
| 2603 | |
| 2604 | sync_event = _threading.Event() |
| 2605 | sync_progress_thread = self._CreateSyncProgressThread(pm, sync_event) |
| 2606 | |
| Gavin Mak | 1afe96a | 2025-10-20 11:13:09 -0700 | [diff] [blame] | 2607 | try: |
| 2608 | with multiprocessing.Manager() as manager, ssh.ProxyManager( |
| 2609 | manager |
| 2610 | ) as ssh_proxy: |
| 2611 | ssh_proxy.sock() |
| 2612 | with self.ParallelContext(): |
| 2613 | self.get_parallel_context()["ssh_proxy"] = ssh_proxy |
| 2614 | # TODO(gavinmak): Use multprocessing.Queue instead of dict. |
| 2615 | self.get_parallel_context()[ |
| 2616 | "sync_dict" |
| 2617 | ] = multiprocessing.Manager().dict() |
| 2618 | sync_progress_thread.start() |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 2619 | |
| Gavin Mak | 1afe96a | 2025-10-20 11:13:09 -0700 | [diff] [blame] | 2620 | try: |
| 2621 | # Outer loop for dynamic project discovery. This |
| 2622 | # continues until no unsynced projects remain. |
| 2623 | while True: |
| 2624 | projects_to_sync = [ |
| 2625 | p |
| 2626 | for p in project_list |
| 2627 | if p.relpath not in finished_relpaths |
| 2628 | ] |
| 2629 | if not projects_to_sync: |
| 2630 | break |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 2631 | |
| Gavin Mak | 1afe96a | 2025-10-20 11:13:09 -0700 | [diff] [blame] | 2632 | pending_relpaths = { |
| 2633 | p.relpath for p in projects_to_sync |
| 2634 | } |
| 2635 | if previously_pending_relpaths == pending_relpaths: |
| 2636 | stalled_projects_str = "\n".join( |
| 2637 | f" - {path}" |
| 2638 | for path in sorted(list(pending_relpaths)) |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2639 | ) |
| Gavin Mak | 1afe96a | 2025-10-20 11:13:09 -0700 | [diff] [blame] | 2640 | logger.error( |
| 2641 | "The following projects failed and could " |
| 2642 | "not be synced:\n%s", |
| 2643 | stalled_projects_str, |
| 2644 | ) |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2645 | err_event.set() |
| Gavin Mak | 1afe96a | 2025-10-20 11:13:09 -0700 | [diff] [blame] | 2646 | break |
| 2647 | previously_pending_relpaths = pending_relpaths |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2648 | |
| Gavin Mak | 1afe96a | 2025-10-20 11:13:09 -0700 | [diff] [blame] | 2649 | self.get_parallel_context()[ |
| 2650 | "projects" |
| 2651 | ] = projects_to_sync |
| 2652 | project_index_map = { |
| 2653 | p: i for i, p in enumerate(projects_to_sync) |
| 2654 | } |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2655 | |
| Gavin Mak | 1afe96a | 2025-10-20 11:13:09 -0700 | [diff] [blame] | 2656 | # Inner loop to process projects in a hierarchical |
| 2657 | # order. This iterates through levels of project |
| 2658 | # dependencies (e.g. 'foo' then 'foo/bar'). All |
| 2659 | # projects in one level can be processed in |
| 2660 | # parallel, but we must wait for a level to complete |
| 2661 | # before starting the next. |
| 2662 | for level_projects in _SafeCheckoutOrder( |
| 2663 | projects_to_sync |
| 2664 | ): |
| 2665 | if not level_projects: |
| 2666 | continue |
| 2667 | |
| 2668 | objdir_project_map = collections.defaultdict( |
| 2669 | list |
| 2670 | ) |
| 2671 | for p in level_projects: |
| 2672 | objdir_project_map[p.objdir].append( |
| 2673 | project_index_map[p] |
| 2674 | ) |
| 2675 | |
| 2676 | work_items = list(objdir_project_map.values()) |
| 2677 | if not work_items: |
| 2678 | continue |
| 2679 | |
| 2680 | jobs = max(1, min(opt.jobs, len(work_items))) |
| 2681 | callback = functools.partial( |
| 2682 | self._ProcessSyncInterleavedResults, |
| 2683 | finished_relpaths, |
| 2684 | err_event, |
| 2685 | errors, |
| 2686 | opt, |
| 2687 | ) |
| 2688 | if not self.ExecuteInParallel( |
| 2689 | jobs, |
| 2690 | functools.partial( |
| 2691 | self._SyncProjectList, opt |
| 2692 | ), |
| 2693 | work_items, |
| 2694 | callback=callback, |
| 2695 | output=pm, |
| 2696 | chunksize=1, |
| 2697 | initializer=self.InitWorker, |
| 2698 | ): |
| 2699 | err_event.set() |
| 2700 | |
| 2701 | if err_event.is_set() and opt.fail_fast: |
| 2702 | raise SyncFailFastError( |
| 2703 | aggregate_errors=errors |
| 2704 | ) |
| 2705 | |
| 2706 | self._ReloadManifest(None, manifest) |
| 2707 | project_list = self.GetProjects( |
| 2708 | args, |
| 2709 | missing_ok=True, |
| 2710 | submodules_ok=opt.fetch_submodules, |
| 2711 | manifest=manifest, |
| 2712 | all_manifests=not opt.this_manifest_only, |
| 2713 | ) |
| 2714 | pm.update_total(len(project_list)) |
| 2715 | finally: |
| 2716 | sync_event.set() |
| 2717 | sync_progress_thread.join() |
| 2718 | finally: |
| 2719 | self._fetch_times.Save() |
| 2720 | self._local_sync_state.Save() |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 2721 | |
| 2722 | pm.end() |
| 2723 | |
| Gavin Mak | 99b5a17 | 2025-06-17 20:15:50 -0700 | [diff] [blame] | 2724 | err_update_projects, err_update_linkfiles = self._UpdateManifestLists( |
| 2725 | opt, err_event, errors |
| 2726 | ) |
| Gavin Mak | 7b6ffed | 2025-06-13 17:53:38 -0700 | [diff] [blame] | 2727 | if not self.outer_client.manifest.IsArchive: |
| 2728 | self._GCProjects(project_list, opt, err_event) |
| 2729 | |
| 2730 | self._PrintManifestNotices(opt) |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 2731 | if err_event.is_set(): |
| Gavin Mak | 99b5a17 | 2025-06-17 20:15:50 -0700 | [diff] [blame] | 2732 | self._ReportErrors( |
| 2733 | errors, |
| 2734 | err_network_sync=self._interleaved_err_network, |
| 2735 | failing_network_repos=self._interleaved_err_network_results, |
| 2736 | err_checkout=self._interleaved_err_checkout, |
| 2737 | failing_checkout_repos=self._interleaved_err_checkout_results, |
| 2738 | err_update_projects=err_update_projects, |
| 2739 | err_update_linkfiles=err_update_linkfiles, |
| Gavin Mak | b4b323a | 2025-06-17 10:54:41 -0700 | [diff] [blame] | 2740 | ) |
| Mike Frysinger | e19d9e1 | 2020-02-12 11:23:32 -0500 | [diff] [blame] | 2741 | |
| David Pursehouse | 819827a | 2020-02-12 15:20:19 +0900 | [diff] [blame] | 2742 | |
| Shawn O. Pearce | 80d2ceb | 2012-10-26 12:23:05 -0700 | [diff] [blame] | 2743 | def _PostRepoUpgrade(manifest, quiet=False): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2744 | # Link the docs for the internal .repo/ layout for people. |
| 2745 | link = os.path.join(manifest.repodir, "internal-fs-layout.md") |
| 2746 | if not platform_utils.islink(link): |
| 2747 | target = os.path.join("repo", "docs", "internal-fs-layout.md") |
| 2748 | try: |
| 2749 | platform_utils.symlink(target, link) |
| 2750 | except Exception: |
| 2751 | pass |
| Mike Frysinger | fdeb20f | 2021-11-14 03:53:04 -0500 | [diff] [blame] | 2752 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2753 | wrapper = Wrapper() |
| 2754 | if wrapper.NeedSetupGnuPG(): |
| 2755 | wrapper.SetupGnuPG(quiet) |
| 2756 | for project in manifest.projects: |
| 2757 | if project.Exists: |
| 2758 | project.PostRepoUpgrade() |
| Shawn O. Pearce | e756c41 | 2009-04-13 11:51:15 -0700 | [diff] [blame] | 2759 | |
| David Pursehouse | 819827a | 2020-02-12 15:20:19 +0900 | [diff] [blame] | 2760 | |
| Mike Frysinger | c58ec4d | 2020-02-17 14:36:08 -0500 | [diff] [blame] | 2761 | def _PostRepoFetch(rp, repo_verify=True, verbose=False): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2762 | if rp.HasChanges: |
| Aravind Vasudevan | 8bc5000 | 2023-10-13 19:22:47 +0000 | [diff] [blame] | 2763 | logger.warning("info: A new version of repo is available") |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2764 | wrapper = Wrapper() |
| 2765 | try: |
| 2766 | rev = rp.bare_git.describe(rp.GetRevisionId()) |
| 2767 | except GitError: |
| 2768 | rev = None |
| 2769 | _, new_rev = wrapper.check_repo_rev( |
| 2770 | rp.gitdir, rev, repo_verify=repo_verify |
| 2771 | ) |
| 2772 | # See if we're held back due to missing signed tag. |
| 2773 | current_revid = rp.bare_git.rev_parse("HEAD") |
| 2774 | new_revid = rp.bare_git.rev_parse("--verify", new_rev) |
| 2775 | if current_revid != new_revid: |
| 2776 | # We want to switch to the new rev, but also not trash any |
| 2777 | # uncommitted changes. This helps with local testing/hacking. |
| 2778 | # If a local change has been made, we will throw that away. |
| 2779 | # We also have to make sure this will switch to an older commit if |
| 2780 | # that's the latest tag in order to support release rollback. |
| 2781 | try: |
| Josip Sokcevic | fc901b9 | 2025-03-12 20:40:49 +0000 | [diff] [blame] | 2782 | # Refresh index since reset --keep won't do it. |
| 2783 | rp.work_git.update_index("-q", "--refresh") |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2784 | rp.work_git.reset("--keep", new_rev) |
| 2785 | except GitError as e: |
| Jason Chang | 32b5956 | 2023-07-14 16:45:35 -0700 | [diff] [blame] | 2786 | raise RepoUnhandledExceptionError(e) |
| Aravind Vasudevan | 83c66ec | 2023-09-28 19:06:59 +0000 | [diff] [blame] | 2787 | print("info: Restarting repo with latest version") |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2788 | raise RepoChangedException(["--repo-upgraded"]) |
| 2789 | else: |
| Aravind Vasudevan | e914ec2 | 2023-08-31 20:57:31 +0000 | [diff] [blame] | 2790 | logger.warning("warning: Skipped upgrade to unverified version") |
| Shawn O. Pearce | e756c41 | 2009-04-13 11:51:15 -0700 | [diff] [blame] | 2791 | else: |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2792 | if verbose: |
| Aravind Vasudevan | ce0ed79 | 2023-10-06 18:36:22 +0000 | [diff] [blame] | 2793 | print("repo version %s is current" % rp.work_git.describe(HEAD)) |
| Shawn O. Pearce | e756c41 | 2009-04-13 11:51:15 -0700 | [diff] [blame] | 2794 | |
| David Pursehouse | 819827a | 2020-02-12 15:20:19 +0900 | [diff] [blame] | 2795 | |
| Mike Frysinger | d4aee65 | 2023-10-19 05:13:32 -0400 | [diff] [blame] | 2796 | class _FetchTimes: |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2797 | _ALPHA = 0.5 |
| Dave Borowitz | d947858 | 2012-10-23 16:35:39 -0700 | [diff] [blame] | 2798 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2799 | def __init__(self, manifest): |
| 2800 | self._path = os.path.join(manifest.repodir, ".repo_fetchtimes.json") |
| Gavin Mak | 041f977 | 2023-05-10 20:41:12 +0000 | [diff] [blame] | 2801 | self._saved = None |
| 2802 | self._seen = {} |
| Dave Borowitz | 67700e9 | 2012-10-23 15:00:54 -0700 | [diff] [blame] | 2803 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2804 | def Get(self, project): |
| 2805 | self._Load() |
| Gavin Mak | 041f977 | 2023-05-10 20:41:12 +0000 | [diff] [blame] | 2806 | return self._saved.get(project.name, _ONE_DAY_S) |
| Dave Borowitz | 67700e9 | 2012-10-23 15:00:54 -0700 | [diff] [blame] | 2807 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2808 | def Set(self, project, t): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2809 | name = project.name |
| Gavin Mak | 041f977 | 2023-05-10 20:41:12 +0000 | [diff] [blame] | 2810 | |
| 2811 | # For shared projects, save the longest time. |
| 2812 | self._seen[name] = max(self._seen.get(name, 0), t) |
| Dave Borowitz | 67700e9 | 2012-10-23 15:00:54 -0700 | [diff] [blame] | 2813 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2814 | def _Load(self): |
| Gavin Mak | 041f977 | 2023-05-10 20:41:12 +0000 | [diff] [blame] | 2815 | if self._saved is None: |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2816 | try: |
| 2817 | with open(self._path) as f: |
| Gavin Mak | 041f977 | 2023-05-10 20:41:12 +0000 | [diff] [blame] | 2818 | self._saved = json.load(f) |
| Jason R. Coombs | ae824fb | 2023-10-20 23:32:40 +0545 | [diff] [blame] | 2819 | except (OSError, ValueError): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2820 | platform_utils.remove(self._path, missing_ok=True) |
| Gavin Mak | 041f977 | 2023-05-10 20:41:12 +0000 | [diff] [blame] | 2821 | self._saved = {} |
| Dave Borowitz | 67700e9 | 2012-10-23 15:00:54 -0700 | [diff] [blame] | 2822 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2823 | def Save(self): |
| Gavin Mak | 1afe96a | 2025-10-20 11:13:09 -0700 | [diff] [blame] | 2824 | if not self._seen: |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2825 | return |
| Dave Borowitz | d947858 | 2012-10-23 16:35:39 -0700 | [diff] [blame] | 2826 | |
| Gavin Mak | 1afe96a | 2025-10-20 11:13:09 -0700 | [diff] [blame] | 2827 | self._Load() |
| 2828 | |
| Gavin Mak | 041f977 | 2023-05-10 20:41:12 +0000 | [diff] [blame] | 2829 | for name, t in self._seen.items(): |
| 2830 | # Keep a moving average across the previous/current sync runs. |
| 2831 | old = self._saved.get(name, t) |
| Gavin Mak | 1afe96a | 2025-10-20 11:13:09 -0700 | [diff] [blame] | 2832 | self._saved[name] = (self._ALPHA * t) + ((1 - self._ALPHA) * old) |
| Dave Borowitz | d947858 | 2012-10-23 16:35:39 -0700 | [diff] [blame] | 2833 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2834 | try: |
| 2835 | with open(self._path, "w") as f: |
| Gavin Mak | 1afe96a | 2025-10-20 11:13:09 -0700 | [diff] [blame] | 2836 | json.dump(self._saved, f, indent=2) |
| Jason R. Coombs | ae824fb | 2023-10-20 23:32:40 +0545 | [diff] [blame] | 2837 | except (OSError, TypeError): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2838 | platform_utils.remove(self._path, missing_ok=True) |
| 2839 | |
| Dan Willemsen | 0745bb2 | 2015-08-17 13:41:45 -0700 | [diff] [blame] | 2840 | |
| Mike Frysinger | d4aee65 | 2023-10-19 05:13:32 -0400 | [diff] [blame] | 2841 | class LocalSyncState: |
| Gavin Mak | 1d2e99d | 2023-07-22 02:56:44 +0000 | [diff] [blame] | 2842 | _LAST_FETCH = "last_fetch" |
| 2843 | _LAST_CHECKOUT = "last_checkout" |
| 2844 | |
| 2845 | def __init__(self, manifest): |
| Gavin Mak | f0aeb22 | 2023-08-08 04:43:36 +0000 | [diff] [blame] | 2846 | self._manifest = manifest |
| 2847 | self._path = os.path.join( |
| 2848 | self._manifest.repodir, ".repo_localsyncstate.json" |
| 2849 | ) |
| Gavin Mak | 1d2e99d | 2023-07-22 02:56:44 +0000 | [diff] [blame] | 2850 | self._time = time.time() |
| 2851 | self._state = None |
| 2852 | self._Load() |
| 2853 | |
| 2854 | def SetFetchTime(self, project): |
| 2855 | self._Set(project, self._LAST_FETCH) |
| 2856 | |
| 2857 | def SetCheckoutTime(self, project): |
| 2858 | self._Set(project, self._LAST_CHECKOUT) |
| 2859 | |
| 2860 | def GetFetchTime(self, project): |
| 2861 | return self._Get(project, self._LAST_FETCH) |
| 2862 | |
| 2863 | def GetCheckoutTime(self, project): |
| 2864 | return self._Get(project, self._LAST_CHECKOUT) |
| 2865 | |
| 2866 | def _Get(self, project, key): |
| 2867 | self._Load() |
| 2868 | p = project.relpath |
| 2869 | if p not in self._state: |
| 2870 | return |
| 2871 | return self._state[p].get(key) |
| 2872 | |
| 2873 | def _Set(self, project, key): |
| 2874 | p = project.relpath |
| 2875 | if p not in self._state: |
| 2876 | self._state[p] = {} |
| 2877 | self._state[p][key] = self._time |
| 2878 | |
| 2879 | def _Load(self): |
| 2880 | if self._state is None: |
| 2881 | try: |
| 2882 | with open(self._path) as f: |
| 2883 | self._state = json.load(f) |
| Jason R. Coombs | ae824fb | 2023-10-20 23:32:40 +0545 | [diff] [blame] | 2884 | except (OSError, ValueError): |
| Gavin Mak | 1d2e99d | 2023-07-22 02:56:44 +0000 | [diff] [blame] | 2885 | platform_utils.remove(self._path, missing_ok=True) |
| 2886 | self._state = {} |
| 2887 | |
| 2888 | def Save(self): |
| 2889 | if not self._state: |
| 2890 | return |
| 2891 | try: |
| 2892 | with open(self._path, "w") as f: |
| 2893 | json.dump(self._state, f, indent=2) |
| Jason R. Coombs | ae824fb | 2023-10-20 23:32:40 +0545 | [diff] [blame] | 2894 | except (OSError, TypeError): |
| Gavin Mak | 1d2e99d | 2023-07-22 02:56:44 +0000 | [diff] [blame] | 2895 | platform_utils.remove(self._path, missing_ok=True) |
| 2896 | |
| Gavin Mak | f0aeb22 | 2023-08-08 04:43:36 +0000 | [diff] [blame] | 2897 | def PruneRemovedProjects(self): |
| 2898 | """Remove entries don't exist on disk and save.""" |
| 2899 | if not self._state: |
| 2900 | return |
| 2901 | delete = set() |
| 2902 | for path in self._state: |
| 2903 | gitdir = os.path.join(self._manifest.topdir, path, ".git") |
| Matt Schulte | 0dd0a83 | 2023-11-30 11:00:16 -0800 | [diff] [blame] | 2904 | if not os.path.exists(gitdir) or os.path.islink(gitdir): |
| Gavin Mak | f0aeb22 | 2023-08-08 04:43:36 +0000 | [diff] [blame] | 2905 | delete.add(path) |
| 2906 | if not delete: |
| 2907 | return |
| 2908 | for path in delete: |
| 2909 | del self._state[path] |
| 2910 | self.Save() |
| 2911 | |
| 2912 | def IsPartiallySynced(self): |
| 2913 | """Return whether a partial sync state is detected.""" |
| 2914 | self._Load() |
| 2915 | prev_checkout_t = None |
| Gavin Mak | 321b793 | 2023-08-22 03:10:01 +0000 | [diff] [blame] | 2916 | for path, data in self._state.items(): |
| 2917 | if path == self._manifest.repoProject.relpath: |
| 2918 | # The repo project isn't included in most syncs so we should |
| 2919 | # ignore it here. |
| 2920 | continue |
| Gavin Mak | f0aeb22 | 2023-08-08 04:43:36 +0000 | [diff] [blame] | 2921 | checkout_t = data.get(self._LAST_CHECKOUT) |
| 2922 | if not checkout_t: |
| 2923 | return True |
| 2924 | prev_checkout_t = prev_checkout_t or checkout_t |
| 2925 | if prev_checkout_t != checkout_t: |
| 2926 | return True |
| 2927 | return False |
| 2928 | |
| Gavin Mak | 1d2e99d | 2023-07-22 02:56:44 +0000 | [diff] [blame] | 2929 | |
| Dan Willemsen | 0745bb2 | 2015-08-17 13:41:45 -0700 | [diff] [blame] | 2930 | # This is a replacement for xmlrpc.client.Transport using urllib2 |
| 2931 | # and supporting persistent-http[s]. It cannot change hosts from |
| 2932 | # request to request like the normal transport, the real url |
| 2933 | # is passed during initialization. |
| 2934 | class PersistentTransport(xmlrpc.client.Transport): |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2935 | def __init__(self, orig_host): |
| Daniel Kutik | b99272c | 2023-10-23 21:20:07 +0200 | [diff] [blame] | 2936 | super().__init__() |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2937 | self.orig_host = orig_host |
| Dan Willemsen | 0745bb2 | 2015-08-17 13:41:45 -0700 | [diff] [blame] | 2938 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2939 | def request(self, host, handler, request_body, verbose=False): |
| 2940 | with GetUrlCookieFile(self.orig_host, not verbose) as ( |
| 2941 | cookiefile, |
| 2942 | proxy, |
| 2943 | ): |
| 2944 | # Python doesn't understand cookies with the #HttpOnly_ prefix |
| 2945 | # Since we're only using them for HTTP, copy the file temporarily, |
| 2946 | # stripping those prefixes away. |
| 2947 | if cookiefile: |
| 2948 | tmpcookiefile = tempfile.NamedTemporaryFile(mode="w") |
| 2949 | tmpcookiefile.write("# HTTP Cookie File") |
| 2950 | try: |
| 2951 | with open(cookiefile) as f: |
| 2952 | for line in f: |
| 2953 | if line.startswith("#HttpOnly_"): |
| 2954 | line = line[len("#HttpOnly_") :] |
| 2955 | tmpcookiefile.write(line) |
| 2956 | tmpcookiefile.flush() |
| Dan Willemsen | 0745bb2 | 2015-08-17 13:41:45 -0700 | [diff] [blame] | 2957 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2958 | cookiejar = cookielib.MozillaCookieJar(tmpcookiefile.name) |
| 2959 | try: |
| 2960 | cookiejar.load() |
| 2961 | except cookielib.LoadError: |
| 2962 | cookiejar = cookielib.CookieJar() |
| 2963 | finally: |
| 2964 | tmpcookiefile.close() |
| 2965 | else: |
| 2966 | cookiejar = cookielib.CookieJar() |
| Dan Willemsen | 0745bb2 | 2015-08-17 13:41:45 -0700 | [diff] [blame] | 2967 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2968 | proxyhandler = urllib.request.ProxyHandler |
| 2969 | if proxy: |
| 2970 | proxyhandler = urllib.request.ProxyHandler( |
| 2971 | {"http": proxy, "https": proxy} |
| 2972 | ) |
| Dan Willemsen | 0745bb2 | 2015-08-17 13:41:45 -0700 | [diff] [blame] | 2973 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2974 | opener = urllib.request.build_opener( |
| 2975 | urllib.request.HTTPCookieProcessor(cookiejar), proxyhandler |
| 2976 | ) |
| Dan Willemsen | 0745bb2 | 2015-08-17 13:41:45 -0700 | [diff] [blame] | 2977 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2978 | url = urllib.parse.urljoin(self.orig_host, handler) |
| 2979 | parse_results = urllib.parse.urlparse(url) |
| Dan Willemsen | 0745bb2 | 2015-08-17 13:41:45 -0700 | [diff] [blame] | 2980 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2981 | scheme = parse_results.scheme |
| 2982 | if scheme == "persistent-http": |
| 2983 | scheme = "http" |
| 2984 | if scheme == "persistent-https": |
| 2985 | # If we're proxying through persistent-https, use http. The |
| 2986 | # proxy itself will do the https. |
| 2987 | if proxy: |
| 2988 | scheme = "http" |
| 2989 | else: |
| 2990 | scheme = "https" |
| Dan Willemsen | 0745bb2 | 2015-08-17 13:41:45 -0700 | [diff] [blame] | 2991 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2992 | # Parse out any authentication information using the base class. |
| 2993 | host, extra_headers, _ = self.get_host_info(parse_results.netloc) |
| Dan Willemsen | 0745bb2 | 2015-08-17 13:41:45 -0700 | [diff] [blame] | 2994 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 2995 | url = urllib.parse.urlunparse( |
| 2996 | ( |
| 2997 | scheme, |
| 2998 | host, |
| 2999 | parse_results.path, |
| 3000 | parse_results.params, |
| 3001 | parse_results.query, |
| 3002 | parse_results.fragment, |
| 3003 | ) |
| 3004 | ) |
| Dan Willemsen | 0745bb2 | 2015-08-17 13:41:45 -0700 | [diff] [blame] | 3005 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 3006 | request = urllib.request.Request(url, request_body) |
| 3007 | if extra_headers is not None: |
| 3008 | for name, header in extra_headers: |
| 3009 | request.add_header(name, header) |
| 3010 | request.add_header("Content-Type", "text/xml") |
| 3011 | try: |
| 3012 | response = opener.open(request) |
| 3013 | except urllib.error.HTTPError as e: |
| 3014 | if e.code == 501: |
| 3015 | # We may have been redirected through a login process |
| 3016 | # but our POST turned into a GET. Retry. |
| 3017 | response = opener.open(request) |
| 3018 | else: |
| 3019 | raise |
| Dan Willemsen | 0745bb2 | 2015-08-17 13:41:45 -0700 | [diff] [blame] | 3020 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 3021 | p, u = xmlrpc.client.getparser() |
| 3022 | # Response should be fairly small, so read it all at once. |
| 3023 | # This way we can show it to the user in case of error (e.g. HTML). |
| 3024 | data = response.read() |
| 3025 | try: |
| 3026 | p.feed(data) |
| 3027 | except xml.parsers.expat.ExpatError as e: |
| Jason R. Coombs | ae824fb | 2023-10-20 23:32:40 +0545 | [diff] [blame] | 3028 | raise OSError( |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 3029 | f"Parsing the manifest failed: {e}\n" |
| 3030 | f"Please report this to your manifest server admin.\n" |
| 3031 | f'Here is the full response:\n{data.decode("utf-8")}' |
| 3032 | ) |
| 3033 | p.close() |
| 3034 | return u.close() |
| Dan Willemsen | 0745bb2 | 2015-08-17 13:41:45 -0700 | [diff] [blame] | 3035 | |
| Gavin Mak | ea2e330 | 2023-03-11 06:46:20 +0000 | [diff] [blame] | 3036 | def close(self): |
| 3037 | pass |