blob: 9dc7feaed0cb5a3392a82f8dc86c3b99803959c3 [file] [log] [blame]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001# 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
Shawn O. Pearce438ee1c2008-11-03 09:59:36 -080015import errno
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070016import filecmp
Wink Saville4c426ef2015-06-03 08:05:17 -070017import glob
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070018import os
LaMont Jonesd82be3e2022-04-05 19:30:46 +000019import platform
Shawn O. Pearcec325dc32011-10-03 08:30:24 -070020import random
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070021import re
22import shutil
23import stat
Shawn O. Pearce5e7127d2012-08-02 14:57:37 -070024import subprocess
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070025import sys
Julien Campergue335f5ef2013-10-16 11:02:35 +020026import tarfile
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +080027import tempfile
Shawn O. Pearcec325dc32011-10-03 08:30:24 -070028import time
Mike Frysinger64477332023-08-21 21:20:32 -040029from typing import List, NamedTuple
Mike Frysingeracf63b22019-06-13 02:24:21 -040030import urllib.parse
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -070031
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070032from color import Coloring
Mike Frysinger64477332023-08-21 21:20:32 -040033from error import DownloadError
34from error import GitError
35from error import ManifestInvalidPathError
36from error import ManifestInvalidRevisionError
37from error import ManifestParseError
38from error import NoManifestException
39from error import RepoError
40from error import UploadError
LaMont Jones0de4fc32022-04-21 17:18:35 +000041import fetch
Mike Frysinger64477332023-08-21 21:20:32 -040042from git_command import git_require
43from git_command import GitCommand
44from git_config import GetSchemeFromUrl
45from git_config import GetUrlCookieFile
46from git_config import GitConfig
Mike Frysinger64477332023-08-21 21:20:32 -040047from git_config import IsId
48from git_refs import GitRefs
49from git_refs import HEAD
50from git_refs import R_HEADS
51from git_refs import R_M
52from git_refs import R_PUB
53from git_refs import R_TAGS
54from git_refs import R_WORKTREE_M
LaMont Jonesff6b1da2022-06-01 21:03:34 +000055import git_superproject
LaMont Jones55ee3042022-04-06 17:10:21 +000056from git_trace2_event_log import EventLog
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070057import platform_utils
Mike Frysinger70d861f2019-08-26 15:22:36 -040058import progress
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +000059from repo_logging import RepoLogger
Joanna Wanga6c52f52022-11-03 16:51:19 -040060from repo_trace import Trace
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070061
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -070062
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +000063logger = RepoLogger(__file__)
64
65
LaMont Jones1eddca82022-09-01 15:15:04 +000066class SyncNetworkHalfResult(NamedTuple):
Gavin Makea2e3302023-03-11 06:46:20 +000067 """Sync_NetworkHalf return value."""
68
Gavin Makea2e3302023-03-11 06:46:20 +000069 # Did we query the remote? False when optimized_fetch is True and we have
70 # the commit already present.
71 remote_fetched: bool
Jason Chang32b59562023-07-14 16:45:35 -070072 # Error from SyncNetworkHalf
73 error: Exception = None
74
75 @property
76 def success(self) -> bool:
77 return not self.error
78
79
80class SyncNetworkHalfError(RepoError):
81 """Failure trying to sync."""
82
83
84class DeleteWorktreeError(RepoError):
85 """Failure to delete worktree."""
86
87 def __init__(
88 self, *args, aggregate_errors: List[Exception] = None, **kwargs
89 ) -> None:
90 super().__init__(*args, **kwargs)
91 self.aggregate_errors = aggregate_errors or []
92
93
94class DeleteDirtyWorktreeError(DeleteWorktreeError):
95 """Failure to delete worktree due to uncommitted changes."""
LaMont Jones1eddca82022-09-01 15:15:04 +000096
Sergiy Belozorov78e82ec2023-01-05 18:57:31 +010097
George Engelbrecht9bc283e2020-04-02 12:36:09 -060098# Maximum sleep time allowed during retries.
99MAXIMUM_RETRY_SLEEP_SEC = 3600.0
100# +-10% random jitter is added to each Fetches retry sleep duration.
101RETRY_JITTER_PERCENT = 0.1
102
LaMont Jonesfa8d9392022-11-02 22:01:29 +0000103# Whether to use alternates. Switching back and forth is *NOT* supported.
Mike Frysinger1d00a7e2021-12-21 00:40:31 -0500104# TODO(vapier): Remove knob once behavior is verified.
Gavin Makea2e3302023-03-11 06:46:20 +0000105_ALTERNATES = os.environ.get("REPO_USE_ALTERNATES") == "1"
George Engelbrecht9bc283e2020-04-02 12:36:09 -0600106
Sergiy Belozorov78e82ec2023-01-05 18:57:31 +0100107
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700108def _lwrite(path, content):
Gavin Makea2e3302023-03-11 06:46:20 +0000109 lock = "%s.lock" % path
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700110
Gavin Makea2e3302023-03-11 06:46:20 +0000111 # Maintain Unix line endings on all OS's to match git behavior.
112 with open(lock, "w", newline="\n") as fd:
113 fd.write(content)
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700114
Gavin Makea2e3302023-03-11 06:46:20 +0000115 try:
116 platform_utils.rename(lock, path)
117 except OSError:
118 platform_utils.remove(lock)
119 raise
Shawn O. Pearceaccc56d2009-04-18 14:45:51 -0700120
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700121
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700122def not_rev(r):
Gavin Makea2e3302023-03-11 06:46:20 +0000123 return "^" + r
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700124
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700125
Shawn O. Pearceb54a3922009-01-05 16:18:58 -0800126def sq(r):
Gavin Makea2e3302023-03-11 06:46:20 +0000127 return "'" + r.replace("'", "'''") + "'"
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800128
David Pursehouse819827a2020-02-12 15:20:19 +0900129
Jonathan Nieder93719792015-03-17 11:29:58 -0700130_project_hook_list = None
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700131
132
Jonathan Nieder93719792015-03-17 11:29:58 -0700133def _ProjectHooks():
Gavin Makea2e3302023-03-11 06:46:20 +0000134 """List the hooks present in the 'hooks' directory.
Jonathan Nieder93719792015-03-17 11:29:58 -0700135
Gavin Makea2e3302023-03-11 06:46:20 +0000136 These hooks are project hooks and are copied to the '.git/hooks' directory
137 of all subprojects.
Jonathan Nieder93719792015-03-17 11:29:58 -0700138
Gavin Makea2e3302023-03-11 06:46:20 +0000139 This function caches the list of hooks (based on the contents of the
140 'repo/hooks' directory) on the first call.
Jonathan Nieder93719792015-03-17 11:29:58 -0700141
Gavin Makea2e3302023-03-11 06:46:20 +0000142 Returns:
143 A list of absolute paths to all of the files in the hooks directory.
144 """
145 global _project_hook_list
146 if _project_hook_list is None:
147 d = platform_utils.realpath(os.path.abspath(os.path.dirname(__file__)))
148 d = os.path.join(d, "hooks")
149 _project_hook_list = [
150 os.path.join(d, x) for x in platform_utils.listdir(d)
151 ]
152 return _project_hook_list
Jonathan Nieder93719792015-03-17 11:29:58 -0700153
154
Mike Frysingerd4aee652023-10-19 05:13:32 -0400155class DownloadedChange:
Gavin Makea2e3302023-03-11 06:46:20 +0000156 _commit_cache = None
Shawn O. Pearce632768b2008-10-23 11:58:52 -0700157
Gavin Makea2e3302023-03-11 06:46:20 +0000158 def __init__(self, project, base, change_id, ps_id, commit):
159 self.project = project
160 self.base = base
161 self.change_id = change_id
162 self.ps_id = ps_id
163 self.commit = commit
Shawn O. Pearce632768b2008-10-23 11:58:52 -0700164
Gavin Makea2e3302023-03-11 06:46:20 +0000165 @property
166 def commits(self):
167 if self._commit_cache is None:
168 self._commit_cache = self.project.bare_git.rev_list(
169 "--abbrev=8",
170 "--abbrev-commit",
171 "--pretty=oneline",
172 "--reverse",
173 "--date-order",
174 not_rev(self.base),
175 self.commit,
176 "--",
177 )
178 return self._commit_cache
Shawn O. Pearce632768b2008-10-23 11:58:52 -0700179
180
Mike Frysingerd4aee652023-10-19 05:13:32 -0400181class ReviewableBranch:
Gavin Makea2e3302023-03-11 06:46:20 +0000182 _commit_cache = None
183 _base_exists = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700184
Gavin Makea2e3302023-03-11 06:46:20 +0000185 def __init__(self, project, branch, base):
186 self.project = project
187 self.branch = branch
188 self.base = base
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700189
Gavin Makea2e3302023-03-11 06:46:20 +0000190 @property
191 def name(self):
192 return self.branch.name
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700193
Gavin Makea2e3302023-03-11 06:46:20 +0000194 @property
195 def commits(self):
196 if self._commit_cache is None:
197 args = (
198 "--abbrev=8",
199 "--abbrev-commit",
200 "--pretty=oneline",
201 "--reverse",
202 "--date-order",
203 not_rev(self.base),
204 R_HEADS + self.name,
205 "--",
206 )
207 try:
Jason Chang87058c62023-09-27 11:34:43 -0700208 self._commit_cache = self.project.bare_git.rev_list(
209 *args, log_as_error=self.base_exists
210 )
Gavin Makea2e3302023-03-11 06:46:20 +0000211 except GitError:
212 # We weren't able to probe the commits for this branch. Was it
213 # tracking a branch that no longer exists? If so, return no
214 # commits. Otherwise, rethrow the error as we don't know what's
215 # going on.
216 if self.base_exists:
217 raise
Mike Frysinger6da17752019-09-11 18:43:17 -0400218
Gavin Makea2e3302023-03-11 06:46:20 +0000219 self._commit_cache = []
Mike Frysinger6da17752019-09-11 18:43:17 -0400220
Gavin Makea2e3302023-03-11 06:46:20 +0000221 return self._commit_cache
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700222
Gavin Makea2e3302023-03-11 06:46:20 +0000223 @property
224 def unabbrev_commits(self):
225 r = dict()
226 for commit in self.project.bare_git.rev_list(
227 not_rev(self.base), R_HEADS + self.name, "--"
228 ):
229 r[commit[0:8]] = commit
230 return r
Shawn O. Pearcec99883f2008-11-11 17:12:43 -0800231
Gavin Makea2e3302023-03-11 06:46:20 +0000232 @property
233 def date(self):
234 return self.project.bare_git.log(
235 "--pretty=format:%cd", "-n", "1", R_HEADS + self.name, "--"
236 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700237
Gavin Makea2e3302023-03-11 06:46:20 +0000238 @property
239 def base_exists(self):
240 """Whether the branch we're tracking exists.
Mike Frysinger6da17752019-09-11 18:43:17 -0400241
Gavin Makea2e3302023-03-11 06:46:20 +0000242 Normally it should, but sometimes branches we track can get deleted.
243 """
244 if self._base_exists is None:
245 try:
246 self.project.bare_git.rev_parse("--verify", not_rev(self.base))
247 # If we're still here, the base branch exists.
248 self._base_exists = True
249 except GitError:
250 # If we failed to verify, the base branch doesn't exist.
251 self._base_exists = False
Mike Frysinger6da17752019-09-11 18:43:17 -0400252
Gavin Makea2e3302023-03-11 06:46:20 +0000253 return self._base_exists
Mike Frysinger6da17752019-09-11 18:43:17 -0400254
Gavin Makea2e3302023-03-11 06:46:20 +0000255 def UploadForReview(
256 self,
257 people,
258 dryrun=False,
259 auto_topic=False,
260 hashtags=(),
261 labels=(),
262 private=False,
263 notify=None,
264 wip=False,
265 ready=False,
266 dest_branch=None,
267 validate_certs=True,
268 push_options=None,
269 ):
270 self.project.UploadForReview(
271 branch=self.name,
272 people=people,
273 dryrun=dryrun,
274 auto_topic=auto_topic,
275 hashtags=hashtags,
276 labels=labels,
277 private=private,
278 notify=notify,
279 wip=wip,
280 ready=ready,
281 dest_branch=dest_branch,
282 validate_certs=validate_certs,
283 push_options=push_options,
284 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700285
Gavin Makea2e3302023-03-11 06:46:20 +0000286 def GetPublishedRefs(self):
287 refs = {}
288 output = self.project.bare_git.ls_remote(
289 self.branch.remote.SshReviewUrl(self.project.UserEmail),
290 "refs/changes/*",
291 )
292 for line in output.split("\n"):
293 try:
294 (sha, ref) = line.split()
295 refs[sha] = ref
296 except ValueError:
297 pass
Ficus Kirkpatrickbc7ef672009-05-04 12:45:11 -0700298
Gavin Makea2e3302023-03-11 06:46:20 +0000299 return refs
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700300
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700301
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700302class StatusColoring(Coloring):
Gavin Makea2e3302023-03-11 06:46:20 +0000303 def __init__(self, config):
304 super().__init__(config, "status")
305 self.project = self.printer("header", attr="bold")
306 self.branch = self.printer("header", attr="bold")
307 self.nobranch = self.printer("nobranch", fg="red")
308 self.important = self.printer("important", fg="red")
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700309
Gavin Makea2e3302023-03-11 06:46:20 +0000310 self.added = self.printer("added", fg="green")
311 self.changed = self.printer("changed", fg="red")
312 self.untracked = self.printer("untracked", fg="red")
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700313
314
315class DiffColoring(Coloring):
Gavin Makea2e3302023-03-11 06:46:20 +0000316 def __init__(self, config):
317 super().__init__(config, "diff")
318 self.project = self.printer("header", attr="bold")
319 self.fail = self.printer("fail", fg="red")
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700320
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700321
Mike Frysingerd4aee652023-10-19 05:13:32 -0400322class Annotation:
Gavin Makea2e3302023-03-11 06:46:20 +0000323 def __init__(self, name, value, keep):
324 self.name = name
325 self.value = value
326 self.keep = keep
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700327
Gavin Makea2e3302023-03-11 06:46:20 +0000328 def __eq__(self, other):
329 if not isinstance(other, Annotation):
330 return False
331 return self.__dict__ == other.__dict__
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700332
Gavin Makea2e3302023-03-11 06:46:20 +0000333 def __lt__(self, other):
334 # This exists just so that lists of Annotation objects can be sorted,
335 # for use in comparisons.
336 if not isinstance(other, Annotation):
337 raise ValueError("comparison is not between two Annotation objects")
338 if self.name == other.name:
339 if self.value == other.value:
340 return self.keep < other.keep
341 return self.value < other.value
342 return self.name < other.name
Jack Neus6ea0cae2021-07-20 20:52:33 +0000343
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700344
Mike Frysingere6a202f2019-08-02 15:57:57 -0400345def _SafeExpandPath(base, subpath, skipfinal=False):
Gavin Makea2e3302023-03-11 06:46:20 +0000346 """Make sure |subpath| is completely safe under |base|.
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700347
Gavin Makea2e3302023-03-11 06:46:20 +0000348 We make sure no intermediate symlinks are traversed, and that the final path
349 is not a special file (e.g. not a socket or fifo).
Mike Frysingere6a202f2019-08-02 15:57:57 -0400350
Gavin Makea2e3302023-03-11 06:46:20 +0000351 NB: We rely on a number of paths already being filtered out while parsing
352 the manifest. See the validation logic in manifest_xml.py for more details.
353 """
354 # Split up the path by its components. We can't use os.path.sep exclusively
355 # as some platforms (like Windows) will convert / to \ and that bypasses all
356 # our constructed logic here. Especially since manifest authors only use
357 # / in their paths.
358 resep = re.compile(r"[/%s]" % re.escape(os.path.sep))
359 components = resep.split(subpath)
360 if skipfinal:
361 # Whether the caller handles the final component itself.
362 finalpart = components.pop()
Mike Frysingere6a202f2019-08-02 15:57:57 -0400363
Gavin Makea2e3302023-03-11 06:46:20 +0000364 path = base
365 for part in components:
366 if part in {".", ".."}:
367 raise ManifestInvalidPathError(
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -0400368 f'{subpath}: "{part}" not allowed in paths'
Gavin Makea2e3302023-03-11 06:46:20 +0000369 )
Mike Frysingere6a202f2019-08-02 15:57:57 -0400370
Gavin Makea2e3302023-03-11 06:46:20 +0000371 path = os.path.join(path, part)
372 if platform_utils.islink(path):
373 raise ManifestInvalidPathError(
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -0400374 f"{path}: traversing symlinks not allow"
Gavin Makea2e3302023-03-11 06:46:20 +0000375 )
Mike Frysingere6a202f2019-08-02 15:57:57 -0400376
Gavin Makea2e3302023-03-11 06:46:20 +0000377 if os.path.exists(path):
378 if not os.path.isfile(path) and not platform_utils.isdir(path):
379 raise ManifestInvalidPathError(
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -0400380 f"{path}: only regular files & directories allowed"
Gavin Makea2e3302023-03-11 06:46:20 +0000381 )
Mike Frysingere6a202f2019-08-02 15:57:57 -0400382
Gavin Makea2e3302023-03-11 06:46:20 +0000383 if skipfinal:
384 path = os.path.join(path, finalpart)
Mike Frysingere6a202f2019-08-02 15:57:57 -0400385
Gavin Makea2e3302023-03-11 06:46:20 +0000386 return path
Mike Frysingere6a202f2019-08-02 15:57:57 -0400387
388
Mike Frysingerd4aee652023-10-19 05:13:32 -0400389class _CopyFile:
Gavin Makea2e3302023-03-11 06:46:20 +0000390 """Container for <copyfile> manifest element."""
Mike Frysingere6a202f2019-08-02 15:57:57 -0400391
Gavin Makea2e3302023-03-11 06:46:20 +0000392 def __init__(self, git_worktree, src, topdir, dest):
393 """Register a <copyfile> request.
Mike Frysingere6a202f2019-08-02 15:57:57 -0400394
Gavin Makea2e3302023-03-11 06:46:20 +0000395 Args:
396 git_worktree: Absolute path to the git project checkout.
397 src: Relative path under |git_worktree| of file to read.
398 topdir: Absolute path to the top of the repo client checkout.
399 dest: Relative path under |topdir| of file to write.
400 """
401 self.git_worktree = git_worktree
402 self.topdir = topdir
403 self.src = src
404 self.dest = dest
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700405
Gavin Makea2e3302023-03-11 06:46:20 +0000406 def _Copy(self):
407 src = _SafeExpandPath(self.git_worktree, self.src)
408 dest = _SafeExpandPath(self.topdir, self.dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -0400409
Gavin Makea2e3302023-03-11 06:46:20 +0000410 if platform_utils.isdir(src):
411 raise ManifestInvalidPathError(
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -0400412 f"{self.src}: copying from directory not supported"
Gavin Makea2e3302023-03-11 06:46:20 +0000413 )
414 if platform_utils.isdir(dest):
415 raise ManifestInvalidPathError(
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -0400416 f"{self.dest}: copying to directory not allowed"
Gavin Makea2e3302023-03-11 06:46:20 +0000417 )
Mike Frysingere6a202f2019-08-02 15:57:57 -0400418
Gavin Makea2e3302023-03-11 06:46:20 +0000419 # Copy file if it does not exist or is out of date.
420 if not os.path.exists(dest) or not filecmp.cmp(src, dest):
421 try:
422 # Remove existing file first, since it might be read-only.
423 if os.path.exists(dest):
424 platform_utils.remove(dest)
425 else:
426 dest_dir = os.path.dirname(dest)
427 if not platform_utils.isdir(dest_dir):
428 os.makedirs(dest_dir)
429 shutil.copy(src, dest)
430 # Make the file read-only.
431 mode = os.stat(dest)[stat.ST_MODE]
432 mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
433 os.chmod(dest, mode)
Jason R. Coombsae824fb2023-10-20 23:32:40 +0545434 except OSError:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +0000435 logger.error("error: Cannot copy file %s to %s", src, dest)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700436
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700437
Mike Frysingerd4aee652023-10-19 05:13:32 -0400438class _LinkFile:
Gavin Makea2e3302023-03-11 06:46:20 +0000439 """Container for <linkfile> manifest element."""
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700440
Gavin Makea2e3302023-03-11 06:46:20 +0000441 def __init__(self, git_worktree, src, topdir, dest):
442 """Register a <linkfile> request.
Mike Frysingere6a202f2019-08-02 15:57:57 -0400443
Gavin Makea2e3302023-03-11 06:46:20 +0000444 Args:
445 git_worktree: Absolute path to the git project checkout.
446 src: Target of symlink relative to path under |git_worktree|.
447 topdir: Absolute path to the top of the repo client checkout.
448 dest: Relative path under |topdir| of symlink to create.
449 """
450 self.git_worktree = git_worktree
451 self.topdir = topdir
452 self.src = src
453 self.dest = dest
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500454
Gavin Makea2e3302023-03-11 06:46:20 +0000455 def __linkIt(self, relSrc, absDest):
456 # Link file if it does not exist or is out of date.
457 if not platform_utils.islink(absDest) or (
458 platform_utils.readlink(absDest) != relSrc
459 ):
460 try:
461 # Remove existing file first, since it might be read-only.
462 if os.path.lexists(absDest):
463 platform_utils.remove(absDest)
464 else:
465 dest_dir = os.path.dirname(absDest)
466 if not platform_utils.isdir(dest_dir):
467 os.makedirs(dest_dir)
468 platform_utils.symlink(relSrc, absDest)
Jason R. Coombsae824fb2023-10-20 23:32:40 +0545469 except OSError:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +0000470 logger.error(
471 "error: Cannot link file %s to %s", relSrc, absDest
472 )
Gavin Makea2e3302023-03-11 06:46:20 +0000473
474 def _Link(self):
475 """Link the self.src & self.dest paths.
476
477 Handles wild cards on the src linking all of the files in the source in
478 to the destination directory.
479 """
480 # Some people use src="." to create stable links to projects. Let's
481 # allow that but reject all other uses of "." to keep things simple.
482 if self.src == ".":
483 src = self.git_worktree
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500484 else:
Gavin Makea2e3302023-03-11 06:46:20 +0000485 src = _SafeExpandPath(self.git_worktree, self.src)
Wink Saville4c426ef2015-06-03 08:05:17 -0700486
Gavin Makea2e3302023-03-11 06:46:20 +0000487 if not glob.has_magic(src):
488 # Entity does not contain a wild card so just a simple one to one
489 # link operation.
490 dest = _SafeExpandPath(self.topdir, self.dest, skipfinal=True)
491 # dest & src are absolute paths at this point. Make sure the target
492 # of the symlink is relative in the context of the repo client
493 # checkout.
494 relpath = os.path.relpath(src, os.path.dirname(dest))
495 self.__linkIt(relpath, dest)
496 else:
497 dest = _SafeExpandPath(self.topdir, self.dest)
498 # Entity contains a wild card.
499 if os.path.exists(dest) and not platform_utils.isdir(dest):
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +0000500 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +0000501 "Link error: src with wildcard, %s must be a directory",
502 dest,
503 )
504 else:
505 for absSrcFile in glob.glob(src):
506 # Create a releative path from source dir to destination
507 # dir.
508 absSrcDir = os.path.dirname(absSrcFile)
509 relSrcDir = os.path.relpath(absSrcDir, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -0400510
Gavin Makea2e3302023-03-11 06:46:20 +0000511 # Get the source file name.
512 srcFile = os.path.basename(absSrcFile)
Mike Frysingere6a202f2019-08-02 15:57:57 -0400513
Gavin Makea2e3302023-03-11 06:46:20 +0000514 # Now form the final full paths to srcFile. They will be
515 # absolute for the desintaiton and relative for the source.
516 absDest = os.path.join(dest, srcFile)
517 relSrc = os.path.join(relSrcDir, srcFile)
518 self.__linkIt(relSrc, absDest)
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500519
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700520
Mike Frysingerd4aee652023-10-19 05:13:32 -0400521class RemoteSpec:
Gavin Makea2e3302023-03-11 06:46:20 +0000522 def __init__(
523 self,
524 name,
525 url=None,
526 pushUrl=None,
527 review=None,
528 revision=None,
529 orig_name=None,
530 fetchUrl=None,
531 ):
532 self.name = name
533 self.url = url
534 self.pushUrl = pushUrl
535 self.review = review
536 self.revision = revision
537 self.orig_name = orig_name
538 self.fetchUrl = fetchUrl
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700539
Ian Kasprzak0286e312021-02-05 10:06:18 -0800540
Mike Frysingerd4aee652023-10-19 05:13:32 -0400541class Project:
Gavin Makea2e3302023-03-11 06:46:20 +0000542 # These objects can be shared between several working trees.
543 @property
544 def shareable_dirs(self):
545 """Return the shareable directories"""
546 if self.UseAlternates:
547 return ["hooks", "rr-cache"]
548 else:
549 return ["hooks", "objects", "rr-cache"]
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -0700550
Gavin Makea2e3302023-03-11 06:46:20 +0000551 def __init__(
552 self,
553 manifest,
554 name,
555 remote,
556 gitdir,
557 objdir,
558 worktree,
559 relpath,
560 revisionExpr,
561 revisionId,
562 rebase=True,
563 groups=None,
564 sync_c=False,
565 sync_s=False,
566 sync_tags=True,
567 clone_depth=None,
568 upstream=None,
569 parent=None,
570 use_git_worktrees=False,
571 is_derived=False,
572 dest_branch=None,
573 optimized_fetch=False,
574 retry_fetches=0,
575 old_revision=None,
576 ):
577 """Init a Project object.
Doug Anderson3ba5f952011-04-07 12:51:04 -0700578
579 Args:
Gavin Makea2e3302023-03-11 06:46:20 +0000580 manifest: The XmlManifest object.
581 name: The `name` attribute of manifest.xml's project element.
582 remote: RemoteSpec object specifying its remote's properties.
583 gitdir: Absolute path of git directory.
584 objdir: Absolute path of directory to store git objects.
585 worktree: Absolute path of git working tree.
586 relpath: Relative path of git working tree to repo's top directory.
587 revisionExpr: The `revision` attribute of manifest.xml's project
588 element.
589 revisionId: git commit id for checking out.
590 rebase: The `rebase` attribute of manifest.xml's project element.
591 groups: The `groups` attribute of manifest.xml's project element.
592 sync_c: The `sync-c` attribute of manifest.xml's project element.
593 sync_s: The `sync-s` attribute of manifest.xml's project element.
594 sync_tags: The `sync-tags` attribute of manifest.xml's project
595 element.
596 upstream: The `upstream` attribute of manifest.xml's project
597 element.
598 parent: The parent Project object.
599 use_git_worktrees: Whether to use `git worktree` for this project.
600 is_derived: False if the project was explicitly defined in the
601 manifest; True if the project is a discovered submodule.
602 dest_branch: The branch to which to push changes for review by
603 default.
604 optimized_fetch: If True, when a project is set to a sha1 revision,
605 only fetch from the remote if the sha1 is not present locally.
606 retry_fetches: Retry remote fetches n times upon receiving transient
607 error with exponential backoff and jitter.
608 old_revision: saved git commit id for open GITC projects.
609 """
610 self.client = self.manifest = manifest
611 self.name = name
612 self.remote = remote
613 self.UpdatePaths(relpath, worktree, gitdir, objdir)
614 self.SetRevision(revisionExpr, revisionId=revisionId)
615
616 self.rebase = rebase
617 self.groups = groups
618 self.sync_c = sync_c
619 self.sync_s = sync_s
620 self.sync_tags = sync_tags
621 self.clone_depth = clone_depth
622 self.upstream = upstream
623 self.parent = parent
624 # NB: Do not use this setting in __init__ to change behavior so that the
625 # manifest.git checkout can inspect & change it after instantiating.
626 # See the XmlManifest init code for more info.
627 self.use_git_worktrees = use_git_worktrees
628 self.is_derived = is_derived
629 self.optimized_fetch = optimized_fetch
630 self.retry_fetches = max(0, retry_fetches)
631 self.subprojects = []
632
633 self.snapshots = {}
634 self.copyfiles = []
635 self.linkfiles = []
636 self.annotations = []
637 self.dest_branch = dest_branch
638 self.old_revision = old_revision
639
640 # This will be filled in if a project is later identified to be the
641 # project containing repo hooks.
642 self.enabled_repo_hooks = []
643
644 def RelPath(self, local=True):
645 """Return the path for the project relative to a manifest.
646
647 Args:
648 local: a boolean, if True, the path is relative to the local
649 (sub)manifest. If false, the path is relative to the outermost
650 manifest.
651 """
652 if local:
653 return self.relpath
654 return os.path.join(self.manifest.path_prefix, self.relpath)
655
656 def SetRevision(self, revisionExpr, revisionId=None):
657 """Set revisionId based on revision expression and id"""
658 self.revisionExpr = revisionExpr
659 if revisionId is None and revisionExpr and IsId(revisionExpr):
660 self.revisionId = self.revisionExpr
661 else:
662 self.revisionId = revisionId
663
664 def UpdatePaths(self, relpath, worktree, gitdir, objdir):
665 """Update paths used by this project"""
666 self.gitdir = gitdir.replace("\\", "/")
667 self.objdir = objdir.replace("\\", "/")
668 if worktree:
669 self.worktree = os.path.normpath(worktree).replace("\\", "/")
670 else:
671 self.worktree = None
672 self.relpath = relpath
673
674 self.config = GitConfig.ForRepository(
675 gitdir=self.gitdir, defaults=self.manifest.globalConfig
676 )
677
678 if self.worktree:
679 self.work_git = self._GitGetByExec(
680 self, bare=False, gitdir=self.gitdir
681 )
682 else:
683 self.work_git = None
684 self.bare_git = self._GitGetByExec(self, bare=True, gitdir=self.gitdir)
685 self.bare_ref = GitRefs(self.gitdir)
686 self.bare_objdir = self._GitGetByExec(
687 self, bare=True, gitdir=self.objdir
688 )
689
690 @property
691 def UseAlternates(self):
692 """Whether git alternates are in use.
693
694 This will be removed once migration to alternates is complete.
695 """
696 return _ALTERNATES or self.manifest.is_multimanifest
697
698 @property
699 def Derived(self):
700 return self.is_derived
701
702 @property
703 def Exists(self):
704 return platform_utils.isdir(self.gitdir) and platform_utils.isdir(
705 self.objdir
706 )
707
708 @property
709 def CurrentBranch(self):
710 """Obtain the name of the currently checked out branch.
711
712 The branch name omits the 'refs/heads/' prefix.
713 None is returned if the project is on a detached HEAD, or if the
714 work_git is otheriwse inaccessible (e.g. an incomplete sync).
715 """
716 try:
717 b = self.work_git.GetHead()
718 except NoManifestException:
719 # If the local checkout is in a bad state, don't barf. Let the
720 # callers process this like the head is unreadable.
721 return None
722 if b.startswith(R_HEADS):
723 return b[len(R_HEADS) :]
724 return None
725
726 def IsRebaseInProgress(self):
727 return (
728 os.path.exists(self.work_git.GetDotgitPath("rebase-apply"))
729 or os.path.exists(self.work_git.GetDotgitPath("rebase-merge"))
730 or os.path.exists(os.path.join(self.worktree, ".dotest"))
731 )
732
733 def IsDirty(self, consider_untracked=True):
734 """Is the working directory modified in some way?"""
735 self.work_git.update_index(
736 "-q", "--unmerged", "--ignore-missing", "--refresh"
737 )
738 if self.work_git.DiffZ("diff-index", "-M", "--cached", HEAD):
739 return True
740 if self.work_git.DiffZ("diff-files"):
741 return True
742 if consider_untracked and self.UntrackedFiles():
743 return True
744 return False
745
746 _userident_name = None
747 _userident_email = None
748
749 @property
750 def UserName(self):
751 """Obtain the user's personal name."""
752 if self._userident_name is None:
753 self._LoadUserIdentity()
754 return self._userident_name
755
756 @property
757 def UserEmail(self):
758 """Obtain the user's email address. This is very likely
759 to be their Gerrit login.
760 """
761 if self._userident_email is None:
762 self._LoadUserIdentity()
763 return self._userident_email
764
765 def _LoadUserIdentity(self):
766 u = self.bare_git.var("GIT_COMMITTER_IDENT")
767 m = re.compile("^(.*) <([^>]*)> ").match(u)
768 if m:
769 self._userident_name = m.group(1)
770 self._userident_email = m.group(2)
771 else:
772 self._userident_name = ""
773 self._userident_email = ""
774
775 def GetRemote(self, name=None):
776 """Get the configuration for a single remote.
777
778 Defaults to the current project's remote.
779 """
780 if name is None:
781 name = self.remote.name
782 return self.config.GetRemote(name)
783
784 def GetBranch(self, name):
785 """Get the configuration for a single branch."""
786 return self.config.GetBranch(name)
787
788 def GetBranches(self):
789 """Get all existing local branches."""
790 current = self.CurrentBranch
791 all_refs = self._allrefs
792 heads = {}
793
794 for name, ref_id in all_refs.items():
795 if name.startswith(R_HEADS):
796 name = name[len(R_HEADS) :]
797 b = self.GetBranch(name)
798 b.current = name == current
799 b.published = None
800 b.revision = ref_id
801 heads[name] = b
802
803 for name, ref_id in all_refs.items():
804 if name.startswith(R_PUB):
805 name = name[len(R_PUB) :]
806 b = heads.get(name)
807 if b:
808 b.published = ref_id
809
810 return heads
811
812 def MatchesGroups(self, manifest_groups):
813 """Returns true if the manifest groups specified at init should cause
814 this project to be synced.
815 Prefixing a manifest group with "-" inverts the meaning of a group.
816 All projects are implicitly labelled with "all".
817
818 labels are resolved in order. In the example case of
819 project_groups: "all,group1,group2"
820 manifest_groups: "-group1,group2"
821 the project will be matched.
822
823 The special manifest group "default" will match any project that
824 does not have the special project group "notdefault"
825 """
826 default_groups = self.manifest.default_groups or ["default"]
827 expanded_manifest_groups = manifest_groups or default_groups
828 expanded_project_groups = ["all"] + (self.groups or [])
829 if "notdefault" not in expanded_project_groups:
830 expanded_project_groups += ["default"]
831
832 matched = False
833 for group in expanded_manifest_groups:
834 if group.startswith("-") and group[1:] in expanded_project_groups:
835 matched = False
836 elif group in expanded_project_groups:
837 matched = True
838
839 return matched
840
841 def UncommitedFiles(self, get_all=True):
842 """Returns a list of strings, uncommitted files in the git tree.
843
844 Args:
845 get_all: a boolean, if True - get information about all different
846 uncommitted files. If False - return as soon as any kind of
847 uncommitted files is detected.
848 """
849 details = []
850 self.work_git.update_index(
851 "-q", "--unmerged", "--ignore-missing", "--refresh"
852 )
853 if self.IsRebaseInProgress():
854 details.append("rebase in progress")
855 if not get_all:
856 return details
857
858 changes = self.work_git.DiffZ("diff-index", "--cached", HEAD).keys()
859 if changes:
860 details.extend(changes)
861 if not get_all:
862 return details
863
864 changes = self.work_git.DiffZ("diff-files").keys()
865 if changes:
866 details.extend(changes)
867 if not get_all:
868 return details
869
870 changes = self.UntrackedFiles()
871 if changes:
872 details.extend(changes)
873
874 return details
875
876 def UntrackedFiles(self):
877 """Returns a list of strings, untracked files in the git tree."""
878 return self.work_git.LsOthers()
879
880 def HasChanges(self):
881 """Returns true if there are uncommitted changes."""
882 return bool(self.UncommitedFiles(get_all=False))
883
884 def PrintWorkTreeStatus(self, output_redir=None, quiet=False, local=False):
885 """Prints the status of the repository to stdout.
886
887 Args:
888 output_redir: If specified, redirect the output to this object.
889 quiet: If True then only print the project name. Do not print
890 the modified files, branch name, etc.
891 local: a boolean, if True, the path is relative to the local
892 (sub)manifest. If false, the path is relative to the outermost
893 manifest.
894 """
895 if not platform_utils.isdir(self.worktree):
896 if output_redir is None:
897 output_redir = sys.stdout
898 print(file=output_redir)
899 print("project %s/" % self.RelPath(local), file=output_redir)
900 print(' missing (run "repo sync")', file=output_redir)
901 return
902
903 self.work_git.update_index(
904 "-q", "--unmerged", "--ignore-missing", "--refresh"
905 )
906 rb = self.IsRebaseInProgress()
907 di = self.work_git.DiffZ("diff-index", "-M", "--cached", HEAD)
908 df = self.work_git.DiffZ("diff-files")
909 do = self.work_git.LsOthers()
910 if not rb and not di and not df and not do and not self.CurrentBranch:
911 return "CLEAN"
912
913 out = StatusColoring(self.config)
914 if output_redir is not None:
915 out.redirect(output_redir)
916 out.project("project %-40s", self.RelPath(local) + "/ ")
917
918 if quiet:
919 out.nl()
920 return "DIRTY"
921
922 branch = self.CurrentBranch
923 if branch is None:
924 out.nobranch("(*** NO BRANCH ***)")
925 else:
926 out.branch("branch %s", branch)
927 out.nl()
928
929 if rb:
930 out.important("prior sync failed; rebase still in progress")
931 out.nl()
932
933 paths = list()
934 paths.extend(di.keys())
935 paths.extend(df.keys())
936 paths.extend(do)
937
938 for p in sorted(set(paths)):
939 try:
940 i = di[p]
941 except KeyError:
942 i = None
943
944 try:
945 f = df[p]
946 except KeyError:
947 f = None
948
949 if i:
950 i_status = i.status.upper()
951 else:
952 i_status = "-"
953
954 if f:
955 f_status = f.status.lower()
956 else:
957 f_status = "-"
958
959 if i and i.src_path:
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -0400960 line = (
961 f" {i_status}{f_status}\t{i.src_path} => {p} ({i.level}%)"
Gavin Makea2e3302023-03-11 06:46:20 +0000962 )
963 else:
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -0400964 line = f" {i_status}{f_status}\t{p}"
Gavin Makea2e3302023-03-11 06:46:20 +0000965
966 if i and not f:
967 out.added("%s", line)
968 elif (i and f) or (not i and f):
969 out.changed("%s", line)
970 elif not i and not f:
971 out.untracked("%s", line)
972 else:
973 out.write("%s", line)
974 out.nl()
975
976 return "DIRTY"
977
978 def PrintWorkTreeDiff(
979 self, absolute_paths=False, output_redir=None, local=False
980 ):
981 """Prints the status of the repository to stdout."""
982 out = DiffColoring(self.config)
983 if output_redir:
984 out.redirect(output_redir)
985 cmd = ["diff"]
986 if out.is_on:
987 cmd.append("--color")
988 cmd.append(HEAD)
989 if absolute_paths:
990 cmd.append("--src-prefix=a/%s/" % self.RelPath(local))
991 cmd.append("--dst-prefix=b/%s/" % self.RelPath(local))
992 cmd.append("--")
993 try:
994 p = GitCommand(self, cmd, capture_stdout=True, capture_stderr=True)
995 p.Wait()
996 except GitError as e:
997 out.nl()
998 out.project("project %s/" % self.RelPath(local))
999 out.nl()
1000 out.fail("%s", str(e))
1001 out.nl()
1002 return False
1003 if p.stdout:
1004 out.nl()
1005 out.project("project %s/" % self.RelPath(local))
1006 out.nl()
1007 out.write("%s", p.stdout)
1008 return p.Wait() == 0
1009
1010 def WasPublished(self, branch, all_refs=None):
1011 """Was the branch published (uploaded) for code review?
1012 If so, returns the SHA-1 hash of the last published
1013 state for the branch.
1014 """
1015 key = R_PUB + branch
1016 if all_refs is None:
1017 try:
1018 return self.bare_git.rev_parse(key)
1019 except GitError:
1020 return None
1021 else:
1022 try:
1023 return all_refs[key]
1024 except KeyError:
1025 return None
1026
1027 def CleanPublishedCache(self, all_refs=None):
1028 """Prunes any stale published refs."""
1029 if all_refs is None:
1030 all_refs = self._allrefs
1031 heads = set()
1032 canrm = {}
1033 for name, ref_id in all_refs.items():
1034 if name.startswith(R_HEADS):
1035 heads.add(name)
1036 elif name.startswith(R_PUB):
1037 canrm[name] = ref_id
1038
1039 for name, ref_id in canrm.items():
1040 n = name[len(R_PUB) :]
1041 if R_HEADS + n not in heads:
1042 self.bare_git.DeleteRef(name, ref_id)
1043
1044 def GetUploadableBranches(self, selected_branch=None):
1045 """List any branches which can be uploaded for review."""
1046 heads = {}
1047 pubed = {}
1048
1049 for name, ref_id in self._allrefs.items():
1050 if name.startswith(R_HEADS):
1051 heads[name[len(R_HEADS) :]] = ref_id
1052 elif name.startswith(R_PUB):
1053 pubed[name[len(R_PUB) :]] = ref_id
1054
1055 ready = []
1056 for branch, ref_id in heads.items():
1057 if branch in pubed and pubed[branch] == ref_id:
1058 continue
1059 if selected_branch and branch != selected_branch:
1060 continue
1061
1062 rb = self.GetUploadableBranch(branch)
1063 if rb:
1064 ready.append(rb)
1065 return ready
1066
1067 def GetUploadableBranch(self, branch_name):
1068 """Get a single uploadable branch, or None."""
1069 branch = self.GetBranch(branch_name)
1070 base = branch.LocalMerge
1071 if branch.LocalMerge:
1072 rb = ReviewableBranch(self, branch, base)
1073 if rb.commits:
1074 return rb
1075 return None
1076
1077 def UploadForReview(
1078 self,
1079 branch=None,
1080 people=([], []),
1081 dryrun=False,
1082 auto_topic=False,
1083 hashtags=(),
1084 labels=(),
1085 private=False,
1086 notify=None,
1087 wip=False,
1088 ready=False,
1089 dest_branch=None,
1090 validate_certs=True,
1091 push_options=None,
1092 ):
1093 """Uploads the named branch for code review."""
1094 if branch is None:
1095 branch = self.CurrentBranch
1096 if branch is None:
Jason Chang32b59562023-07-14 16:45:35 -07001097 raise GitError("not currently on a branch", project=self.name)
Gavin Makea2e3302023-03-11 06:46:20 +00001098
1099 branch = self.GetBranch(branch)
1100 if not branch.LocalMerge:
Jason Chang32b59562023-07-14 16:45:35 -07001101 raise GitError(
1102 "branch %s does not track a remote" % branch.name,
1103 project=self.name,
1104 )
Gavin Makea2e3302023-03-11 06:46:20 +00001105 if not branch.remote.review:
Jason Chang32b59562023-07-14 16:45:35 -07001106 raise GitError(
1107 "remote %s has no review url" % branch.remote.name,
1108 project=self.name,
1109 )
Gavin Makea2e3302023-03-11 06:46:20 +00001110
1111 # Basic validity check on label syntax.
1112 for label in labels:
1113 if not re.match(r"^.+[+-][0-9]+$", label):
1114 raise UploadError(
1115 f'invalid label syntax "{label}": labels use forms like '
Jason Chang5a3a5f72023-08-17 11:36:41 -07001116 "CodeReview+1 or Verified-1",
1117 project=self.name,
Gavin Makea2e3302023-03-11 06:46:20 +00001118 )
1119
1120 if dest_branch is None:
1121 dest_branch = self.dest_branch
1122 if dest_branch is None:
1123 dest_branch = branch.merge
1124 if not dest_branch.startswith(R_HEADS):
1125 dest_branch = R_HEADS + dest_branch
1126
1127 if not branch.remote.projectname:
1128 branch.remote.projectname = self.name
1129 branch.remote.Save()
1130
1131 url = branch.remote.ReviewUrl(self.UserEmail, validate_certs)
1132 if url is None:
Jason Chang5a3a5f72023-08-17 11:36:41 -07001133 raise UploadError("review not configured", project=self.name)
Aravind Vasudevan2844a5f2023-10-06 00:40:25 +00001134 cmd = ["push", "--progress"]
Gavin Makea2e3302023-03-11 06:46:20 +00001135 if dryrun:
1136 cmd.append("-n")
1137
1138 if url.startswith("ssh://"):
1139 cmd.append("--receive-pack=gerrit receive-pack")
1140
Aravind Vasudevan99ebf622023-04-04 23:44:37 +00001141 # This stops git from pushing all reachable annotated tags when
1142 # push.followTags is configured. Gerrit does not accept any tags
1143 # pushed to a CL.
1144 if git_require((1, 8, 3)):
1145 cmd.append("--no-follow-tags")
1146
Gavin Makea2e3302023-03-11 06:46:20 +00001147 for push_option in push_options or []:
1148 cmd.append("-o")
1149 cmd.append(push_option)
1150
1151 cmd.append(url)
1152
1153 if dest_branch.startswith(R_HEADS):
1154 dest_branch = dest_branch[len(R_HEADS) :]
1155
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04001156 ref_spec = f"{R_HEADS + branch.name}:refs/for/{dest_branch}"
Gavin Makea2e3302023-03-11 06:46:20 +00001157 opts = []
1158 if auto_topic:
1159 opts += ["topic=" + branch.name]
1160 opts += ["t=%s" % p for p in hashtags]
1161 # NB: No need to encode labels as they've been validated above.
1162 opts += ["l=%s" % p for p in labels]
1163
1164 opts += ["r=%s" % p for p in people[0]]
1165 opts += ["cc=%s" % p for p in people[1]]
1166 if notify:
1167 opts += ["notify=" + notify]
1168 if private:
1169 opts += ["private"]
1170 if wip:
1171 opts += ["wip"]
1172 if ready:
1173 opts += ["ready"]
1174 if opts:
1175 ref_spec = ref_spec + "%" + ",".join(opts)
1176 cmd.append(ref_spec)
1177
Jason Chang1e9f7b92023-08-25 10:31:04 -07001178 GitCommand(self, cmd, bare=True, verify_command=True).Wait()
Gavin Makea2e3302023-03-11 06:46:20 +00001179
1180 if not dryrun:
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04001181 msg = f"posted to {branch.remote.review} for {dest_branch}"
Gavin Makea2e3302023-03-11 06:46:20 +00001182 self.bare_git.UpdateRef(
1183 R_PUB + branch.name, R_HEADS + branch.name, message=msg
1184 )
1185
1186 def _ExtractArchive(self, tarpath, path=None):
1187 """Extract the given tar on its current location
1188
1189 Args:
1190 tarpath: The path to the actual tar file
1191
1192 """
1193 try:
1194 with tarfile.open(tarpath, "r") as tar:
1195 tar.extractall(path=path)
1196 return True
Jason R. Coombsae824fb2023-10-20 23:32:40 +05451197 except (OSError, tarfile.TarError) as e:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00001198 logger.error("error: Cannot extract archive %s: %s", tarpath, e)
Gavin Makea2e3302023-03-11 06:46:20 +00001199 return False
1200
1201 def Sync_NetworkHalf(
1202 self,
1203 quiet=False,
1204 verbose=False,
1205 output_redir=None,
1206 is_new=None,
1207 current_branch_only=None,
1208 force_sync=False,
1209 clone_bundle=True,
1210 tags=None,
1211 archive=False,
1212 optimized_fetch=False,
1213 retry_fetches=0,
1214 prune=False,
1215 submodules=False,
1216 ssh_proxy=None,
1217 clone_filter=None,
1218 partial_clone_exclude=set(),
Jason Chang17833322023-05-23 13:06:55 -07001219 clone_filter_for_depth=None,
Gavin Makea2e3302023-03-11 06:46:20 +00001220 ):
1221 """Perform only the network IO portion of the sync process.
1222 Local working directory/branch state is not affected.
1223 """
1224 if archive and not isinstance(self, MetaProject):
1225 if self.remote.url.startswith(("http://", "https://")):
Jason Chang32b59562023-07-14 16:45:35 -07001226 msg_template = (
1227 "%s: Cannot fetch archives from http/https remotes."
Gavin Makea2e3302023-03-11 06:46:20 +00001228 )
Jason Chang32b59562023-07-14 16:45:35 -07001229 msg_args = self.name
1230 msg = msg_template % msg_args
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00001231 logger.error(msg_template, msg_args)
Jason Chang32b59562023-07-14 16:45:35 -07001232 return SyncNetworkHalfResult(
1233 False, SyncNetworkHalfError(msg, project=self.name)
1234 )
Gavin Makea2e3302023-03-11 06:46:20 +00001235
1236 name = self.relpath.replace("\\", "/")
1237 name = name.replace("/", "_")
1238 tarpath = "%s.tar" % name
1239 topdir = self.manifest.topdir
1240
1241 try:
1242 self._FetchArchive(tarpath, cwd=topdir)
1243 except GitError as e:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00001244 logger.error("error: %s", e)
Jason Chang32b59562023-07-14 16:45:35 -07001245 return SyncNetworkHalfResult(False, e)
Gavin Makea2e3302023-03-11 06:46:20 +00001246
1247 # From now on, we only need absolute tarpath.
1248 tarpath = os.path.join(topdir, tarpath)
1249
1250 if not self._ExtractArchive(tarpath, path=topdir):
Jason Chang32b59562023-07-14 16:45:35 -07001251 return SyncNetworkHalfResult(
1252 True,
1253 SyncNetworkHalfError(
1254 f"Unable to Extract Archive {tarpath}",
1255 project=self.name,
1256 ),
1257 )
Gavin Makea2e3302023-03-11 06:46:20 +00001258 try:
1259 platform_utils.remove(tarpath)
1260 except OSError as e:
Aravind Vasudevan8bc50002023-10-13 19:22:47 +00001261 logger.warning("warn: Cannot remove archive %s: %s", tarpath, e)
Gavin Makea2e3302023-03-11 06:46:20 +00001262 self._CopyAndLinkFiles()
Jason Chang32b59562023-07-14 16:45:35 -07001263 return SyncNetworkHalfResult(True)
Gavin Makea2e3302023-03-11 06:46:20 +00001264
1265 # If the shared object dir already exists, don't try to rebootstrap with
1266 # a clone bundle download. We should have the majority of objects
1267 # already.
1268 if clone_bundle and os.path.exists(self.objdir):
1269 clone_bundle = False
1270
1271 if self.name in partial_clone_exclude:
1272 clone_bundle = True
1273 clone_filter = None
1274
1275 if is_new is None:
1276 is_new = not self.Exists
1277 if is_new:
1278 self._InitGitDir(force_sync=force_sync, quiet=quiet)
1279 else:
Josip Sokcevic9b57aa02023-12-01 23:01:52 +00001280 try:
1281 # At this point, it's possible that gitdir points to an old
1282 # objdir (e.g. name changed, but objdir exists). Check
1283 # references to ensure that's not the case. See
1284 # https://issues.gerritcodereview.com/40013418 for more
1285 # details.
1286 self._CheckDirReference(self.objdir, self.gitdir)
1287
1288 self._UpdateHooks(quiet=quiet)
1289 except GitError as e:
1290 if not force_sync:
1291 raise e
1292 # Let _InitGitDir fix the issue, force_sync is always True here.
1293 self._InitGitDir(force_sync=True, quiet=quiet)
Gavin Makea2e3302023-03-11 06:46:20 +00001294 self._InitRemote()
1295
1296 if self.UseAlternates:
1297 # If gitdir/objects is a symlink, migrate it from the old layout.
1298 gitdir_objects = os.path.join(self.gitdir, "objects")
1299 if platform_utils.islink(gitdir_objects):
1300 platform_utils.remove(gitdir_objects, missing_ok=True)
1301 gitdir_alt = os.path.join(self.gitdir, "objects/info/alternates")
1302 if not os.path.exists(gitdir_alt):
1303 os.makedirs(os.path.dirname(gitdir_alt), exist_ok=True)
1304 _lwrite(
1305 gitdir_alt,
1306 os.path.join(
1307 os.path.relpath(self.objdir, gitdir_objects), "objects"
1308 )
1309 + "\n",
1310 )
1311
1312 if is_new:
1313 alt = os.path.join(self.objdir, "objects/info/alternates")
1314 try:
1315 with open(alt) as fd:
1316 # This works for both absolute and relative alternate
1317 # directories.
1318 alt_dir = os.path.join(
1319 self.objdir, "objects", fd.readline().rstrip()
1320 )
Jason R. Coombsae824fb2023-10-20 23:32:40 +05451321 except OSError:
Gavin Makea2e3302023-03-11 06:46:20 +00001322 alt_dir = None
1323 else:
1324 alt_dir = None
1325
1326 if (
1327 clone_bundle
1328 and alt_dir is None
1329 and self._ApplyCloneBundle(
1330 initial=is_new, quiet=quiet, verbose=verbose
1331 )
1332 ):
1333 is_new = False
1334
1335 if current_branch_only is None:
1336 if self.sync_c:
1337 current_branch_only = True
1338 elif not self.manifest._loaded:
1339 # Manifest cannot check defaults until it syncs.
1340 current_branch_only = False
1341 elif self.manifest.default.sync_c:
1342 current_branch_only = True
1343
1344 if tags is None:
1345 tags = self.sync_tags
1346
1347 if self.clone_depth:
1348 depth = self.clone_depth
1349 else:
1350 depth = self.manifest.manifestProject.depth
1351
Jason Chang17833322023-05-23 13:06:55 -07001352 if depth and clone_filter_for_depth:
1353 depth = None
1354 clone_filter = clone_filter_for_depth
1355
Gavin Makea2e3302023-03-11 06:46:20 +00001356 # See if we can skip the network fetch entirely.
1357 remote_fetched = False
1358 if not (
1359 optimized_fetch
Sylvain56a5a012023-09-11 13:38:00 +02001360 and IsId(self.revisionExpr)
1361 and self._CheckForImmutableRevision()
Gavin Makea2e3302023-03-11 06:46:20 +00001362 ):
1363 remote_fetched = True
Jason Chang32b59562023-07-14 16:45:35 -07001364 try:
1365 if not self._RemoteFetch(
1366 initial=is_new,
1367 quiet=quiet,
1368 verbose=verbose,
1369 output_redir=output_redir,
1370 alt_dir=alt_dir,
1371 current_branch_only=current_branch_only,
1372 tags=tags,
1373 prune=prune,
1374 depth=depth,
1375 submodules=submodules,
1376 force_sync=force_sync,
1377 ssh_proxy=ssh_proxy,
1378 clone_filter=clone_filter,
1379 retry_fetches=retry_fetches,
1380 ):
1381 return SyncNetworkHalfResult(
1382 remote_fetched,
1383 SyncNetworkHalfError(
1384 f"Unable to remote fetch project {self.name}",
1385 project=self.name,
1386 ),
1387 )
1388 except RepoError as e:
1389 return SyncNetworkHalfResult(
1390 remote_fetched,
1391 e,
1392 )
Gavin Makea2e3302023-03-11 06:46:20 +00001393
1394 mp = self.manifest.manifestProject
1395 dissociate = mp.dissociate
1396 if dissociate:
1397 alternates_file = os.path.join(
1398 self.objdir, "objects/info/alternates"
1399 )
1400 if os.path.exists(alternates_file):
1401 cmd = ["repack", "-a", "-d"]
1402 p = GitCommand(
1403 self,
1404 cmd,
1405 bare=True,
1406 capture_stdout=bool(output_redir),
1407 merge_output=bool(output_redir),
1408 )
1409 if p.stdout and output_redir:
1410 output_redir.write(p.stdout)
1411 if p.Wait() != 0:
Jason Chang32b59562023-07-14 16:45:35 -07001412 return SyncNetworkHalfResult(
1413 remote_fetched,
1414 GitError(
1415 "Unable to repack alternates", project=self.name
1416 ),
1417 )
Gavin Makea2e3302023-03-11 06:46:20 +00001418 platform_utils.remove(alternates_file)
1419
1420 if self.worktree:
1421 self._InitMRef()
1422 else:
1423 self._InitMirrorHead()
1424 platform_utils.remove(
1425 os.path.join(self.gitdir, "FETCH_HEAD"), missing_ok=True
1426 )
Jason Chang32b59562023-07-14 16:45:35 -07001427 return SyncNetworkHalfResult(remote_fetched)
Gavin Makea2e3302023-03-11 06:46:20 +00001428
1429 def PostRepoUpgrade(self):
1430 self._InitHooks()
1431
1432 def _CopyAndLinkFiles(self):
1433 if self.client.isGitcClient:
1434 return
1435 for copyfile in self.copyfiles:
1436 copyfile._Copy()
1437 for linkfile in self.linkfiles:
1438 linkfile._Link()
1439
1440 def GetCommitRevisionId(self):
1441 """Get revisionId of a commit.
1442
1443 Use this method instead of GetRevisionId to get the id of the commit
1444 rather than the id of the current git object (for example, a tag)
1445
1446 """
Sylvaine9cb3912023-09-10 23:35:01 +02001447 if self.revisionId:
1448 return self.revisionId
Gavin Makea2e3302023-03-11 06:46:20 +00001449 if not self.revisionExpr.startswith(R_TAGS):
1450 return self.GetRevisionId(self._allrefs)
1451
1452 try:
1453 return self.bare_git.rev_list(self.revisionExpr, "-1")[0]
1454 except GitError:
1455 raise ManifestInvalidRevisionError(
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04001456 f"revision {self.revisionExpr} in {self.name} not found"
Gavin Makea2e3302023-03-11 06:46:20 +00001457 )
1458
1459 def GetRevisionId(self, all_refs=None):
1460 if self.revisionId:
1461 return self.revisionId
1462
1463 rem = self.GetRemote()
1464 rev = rem.ToLocal(self.revisionExpr)
1465
1466 if all_refs is not None and rev in all_refs:
1467 return all_refs[rev]
1468
1469 try:
1470 return self.bare_git.rev_parse("--verify", "%s^0" % rev)
1471 except GitError:
1472 raise ManifestInvalidRevisionError(
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04001473 f"revision {self.revisionExpr} in {self.name} not found"
Gavin Makea2e3302023-03-11 06:46:20 +00001474 )
1475
1476 def SetRevisionId(self, revisionId):
1477 if self.revisionExpr:
1478 self.upstream = self.revisionExpr
1479
1480 self.revisionId = revisionId
1481
Jason Chang32b59562023-07-14 16:45:35 -07001482 def Sync_LocalHalf(
Tomasz Wasilczyk4c809212023-12-08 13:42:17 -08001483 self,
1484 syncbuf,
1485 force_sync=False,
1486 submodules=False,
1487 errors=None,
1488 verbose=False,
Jason Chang32b59562023-07-14 16:45:35 -07001489 ):
Gavin Makea2e3302023-03-11 06:46:20 +00001490 """Perform only the local IO portion of the sync process.
1491
1492 Network access is not required.
1493 """
Jason Chang32b59562023-07-14 16:45:35 -07001494 if errors is None:
1495 errors = []
1496
1497 def fail(error: Exception):
1498 errors.append(error)
1499 syncbuf.fail(self, error)
1500
Gavin Makea2e3302023-03-11 06:46:20 +00001501 if not os.path.exists(self.gitdir):
Jason Chang32b59562023-07-14 16:45:35 -07001502 fail(
1503 LocalSyncFail(
1504 "Cannot checkout %s due to missing network sync; Run "
1505 "`repo sync -n %s` first." % (self.name, self.name),
1506 project=self.name,
1507 )
Gavin Makea2e3302023-03-11 06:46:20 +00001508 )
1509 return
1510
1511 self._InitWorkTree(force_sync=force_sync, submodules=submodules)
1512 all_refs = self.bare_ref.all
1513 self.CleanPublishedCache(all_refs)
1514 revid = self.GetRevisionId(all_refs)
1515
1516 # Special case the root of the repo client checkout. Make sure it
1517 # doesn't contain files being checked out to dirs we don't allow.
1518 if self.relpath == ".":
1519 PROTECTED_PATHS = {".repo"}
1520 paths = set(
1521 self.work_git.ls_tree("-z", "--name-only", "--", revid).split(
1522 "\0"
1523 )
1524 )
1525 bad_paths = paths & PROTECTED_PATHS
1526 if bad_paths:
Jason Chang32b59562023-07-14 16:45:35 -07001527 fail(
1528 LocalSyncFail(
1529 "Refusing to checkout project that writes to protected "
1530 "paths: %s" % (", ".join(bad_paths),),
1531 project=self.name,
1532 )
Gavin Makea2e3302023-03-11 06:46:20 +00001533 )
1534 return
1535
1536 def _doff():
1537 self._FastForward(revid)
1538 self._CopyAndLinkFiles()
1539
1540 def _dosubmodules():
1541 self._SyncSubmodules(quiet=True)
1542
1543 head = self.work_git.GetHead()
1544 if head.startswith(R_HEADS):
1545 branch = head[len(R_HEADS) :]
1546 try:
1547 head = all_refs[head]
1548 except KeyError:
1549 head = None
1550 else:
1551 branch = None
1552
1553 if branch is None or syncbuf.detach_head:
1554 # Currently on a detached HEAD. The user is assumed to
1555 # not have any local modifications worth worrying about.
1556 if self.IsRebaseInProgress():
Jason Chang32b59562023-07-14 16:45:35 -07001557 fail(_PriorSyncFailedError(project=self.name))
Gavin Makea2e3302023-03-11 06:46:20 +00001558 return
1559
1560 if head == revid:
1561 # No changes; don't do anything further.
1562 # Except if the head needs to be detached.
1563 if not syncbuf.detach_head:
1564 # The copy/linkfile config may have changed.
1565 self._CopyAndLinkFiles()
1566 return
1567 else:
1568 lost = self._revlist(not_rev(revid), HEAD)
Tomasz Wasilczyk4c809212023-12-08 13:42:17 -08001569 if lost and verbose:
Gavin Makea2e3302023-03-11 06:46:20 +00001570 syncbuf.info(self, "discarding %d commits", len(lost))
1571
1572 try:
1573 self._Checkout(revid, quiet=True)
1574 if submodules:
1575 self._SyncSubmodules(quiet=True)
1576 except GitError as e:
Jason Chang32b59562023-07-14 16:45:35 -07001577 fail(e)
Gavin Makea2e3302023-03-11 06:46:20 +00001578 return
1579 self._CopyAndLinkFiles()
1580 return
1581
1582 if head == revid:
1583 # No changes; don't do anything further.
1584 #
1585 # The copy/linkfile config may have changed.
1586 self._CopyAndLinkFiles()
1587 return
1588
1589 branch = self.GetBranch(branch)
1590
1591 if not branch.LocalMerge:
1592 # The current branch has no tracking configuration.
1593 # Jump off it to a detached HEAD.
1594 syncbuf.info(
1595 self, "leaving %s; does not track upstream", branch.name
1596 )
1597 try:
1598 self._Checkout(revid, quiet=True)
1599 if submodules:
1600 self._SyncSubmodules(quiet=True)
1601 except GitError as e:
Jason Chang32b59562023-07-14 16:45:35 -07001602 fail(e)
Gavin Makea2e3302023-03-11 06:46:20 +00001603 return
1604 self._CopyAndLinkFiles()
1605 return
1606
1607 upstream_gain = self._revlist(not_rev(HEAD), revid)
1608
1609 # See if we can perform a fast forward merge. This can happen if our
1610 # branch isn't in the exact same state as we last published.
1611 try:
Jason Chang87058c62023-09-27 11:34:43 -07001612 self.work_git.merge_base(
1613 "--is-ancestor", HEAD, revid, log_as_error=False
1614 )
Gavin Makea2e3302023-03-11 06:46:20 +00001615 # Skip the published logic.
1616 pub = False
1617 except GitError:
1618 pub = self.WasPublished(branch.name, all_refs)
1619
1620 if pub:
1621 not_merged = self._revlist(not_rev(revid), pub)
1622 if not_merged:
1623 if upstream_gain:
1624 # The user has published this branch and some of those
1625 # commits are not yet merged upstream. We do not want
1626 # to rewrite the published commits so we punt.
Jason Chang32b59562023-07-14 16:45:35 -07001627 fail(
1628 LocalSyncFail(
1629 "branch %s is published (but not merged) and is "
1630 "now %d commits behind"
1631 % (branch.name, len(upstream_gain)),
1632 project=self.name,
1633 )
Gavin Makea2e3302023-03-11 06:46:20 +00001634 )
1635 return
1636 elif pub == head:
1637 # All published commits are merged, and thus we are a
1638 # strict subset. We can fast-forward safely.
1639 syncbuf.later1(self, _doff)
1640 if submodules:
1641 syncbuf.later1(self, _dosubmodules)
1642 return
1643
1644 # Examine the local commits not in the remote. Find the
1645 # last one attributed to this user, if any.
1646 local_changes = self._revlist(not_rev(revid), HEAD, format="%H %ce")
1647 last_mine = None
1648 cnt_mine = 0
1649 for commit in local_changes:
1650 commit_id, committer_email = commit.split(" ", 1)
1651 if committer_email == self.UserEmail:
1652 last_mine = commit_id
1653 cnt_mine += 1
1654
1655 if not upstream_gain and cnt_mine == len(local_changes):
1656 # The copy/linkfile config may have changed.
1657 self._CopyAndLinkFiles()
1658 return
1659
1660 if self.IsDirty(consider_untracked=False):
Jason Chang32b59562023-07-14 16:45:35 -07001661 fail(_DirtyError(project=self.name))
Gavin Makea2e3302023-03-11 06:46:20 +00001662 return
1663
1664 # If the upstream switched on us, warn the user.
1665 if branch.merge != self.revisionExpr:
1666 if branch.merge and self.revisionExpr:
1667 syncbuf.info(
1668 self,
1669 "manifest switched %s...%s",
1670 branch.merge,
1671 self.revisionExpr,
1672 )
1673 elif branch.merge:
1674 syncbuf.info(self, "manifest no longer tracks %s", branch.merge)
1675
1676 if cnt_mine < len(local_changes):
1677 # Upstream rebased. Not everything in HEAD was created by this user.
1678 syncbuf.info(
1679 self,
1680 "discarding %d commits removed from upstream",
1681 len(local_changes) - cnt_mine,
1682 )
1683
1684 branch.remote = self.GetRemote()
Sylvain56a5a012023-09-11 13:38:00 +02001685 if not IsId(self.revisionExpr):
Gavin Makea2e3302023-03-11 06:46:20 +00001686 # In case of manifest sync the revisionExpr might be a SHA1.
1687 branch.merge = self.revisionExpr
1688 if not branch.merge.startswith("refs/"):
1689 branch.merge = R_HEADS + branch.merge
1690 branch.Save()
1691
1692 if cnt_mine > 0 and self.rebase:
1693
1694 def _docopyandlink():
1695 self._CopyAndLinkFiles()
1696
1697 def _dorebase():
1698 self._Rebase(upstream="%s^1" % last_mine, onto=revid)
1699
1700 syncbuf.later2(self, _dorebase)
1701 if submodules:
1702 syncbuf.later2(self, _dosubmodules)
1703 syncbuf.later2(self, _docopyandlink)
1704 elif local_changes:
1705 try:
1706 self._ResetHard(revid)
1707 if submodules:
1708 self._SyncSubmodules(quiet=True)
1709 self._CopyAndLinkFiles()
1710 except GitError as e:
Jason Chang32b59562023-07-14 16:45:35 -07001711 fail(e)
Gavin Makea2e3302023-03-11 06:46:20 +00001712 return
1713 else:
1714 syncbuf.later1(self, _doff)
1715 if submodules:
1716 syncbuf.later1(self, _dosubmodules)
1717
1718 def AddCopyFile(self, src, dest, topdir):
1719 """Mark |src| for copying to |dest| (relative to |topdir|).
1720
1721 No filesystem changes occur here. Actual copying happens later on.
1722
1723 Paths should have basic validation run on them before being queued.
1724 Further checking will be handled when the actual copy happens.
1725 """
1726 self.copyfiles.append(_CopyFile(self.worktree, src, topdir, dest))
1727
1728 def AddLinkFile(self, src, dest, topdir):
1729 """Mark |dest| to create a symlink (relative to |topdir|) pointing to
1730 |src|.
1731
1732 No filesystem changes occur here. Actual linking happens later on.
1733
1734 Paths should have basic validation run on them before being queued.
1735 Further checking will be handled when the actual link happens.
1736 """
1737 self.linkfiles.append(_LinkFile(self.worktree, src, topdir, dest))
1738
1739 def AddAnnotation(self, name, value, keep):
1740 self.annotations.append(Annotation(name, value, keep))
1741
1742 def DownloadPatchSet(self, change_id, patch_id):
1743 """Download a single patch set of a single change to FETCH_HEAD."""
1744 remote = self.GetRemote()
1745
1746 cmd = ["fetch", remote.name]
1747 cmd.append(
1748 "refs/changes/%2.2d/%d/%d" % (change_id % 100, change_id, patch_id)
1749 )
Jason Chang1a3612f2023-08-08 14:12:53 -07001750 GitCommand(self, cmd, bare=True, verify_command=True).Wait()
Gavin Makea2e3302023-03-11 06:46:20 +00001751 return DownloadedChange(
1752 self,
1753 self.GetRevisionId(),
1754 change_id,
1755 patch_id,
1756 self.bare_git.rev_parse("FETCH_HEAD"),
1757 )
1758
Tomasz Wasilczyk4c809212023-12-08 13:42:17 -08001759 def DeleteWorktree(self, verbose=False, force=False):
Gavin Makea2e3302023-03-11 06:46:20 +00001760 """Delete the source checkout and any other housekeeping tasks.
1761
1762 This currently leaves behind the internal .repo/ cache state. This
1763 helps when switching branches or manifest changes get reverted as we
1764 don't have to redownload all the git objects. But we should do some GC
1765 at some point.
1766
1767 Args:
Tomasz Wasilczyk4c809212023-12-08 13:42:17 -08001768 verbose: Whether to show verbose messages.
Gavin Makea2e3302023-03-11 06:46:20 +00001769 force: Always delete tree even if dirty.
Doug Anderson3ba5f952011-04-07 12:51:04 -07001770
1771 Returns:
Gavin Makea2e3302023-03-11 06:46:20 +00001772 True if the worktree was completely cleaned out.
1773 """
1774 if self.IsDirty():
1775 if force:
Aravind Vasudevan8bc50002023-10-13 19:22:47 +00001776 logger.warning(
Gavin Makea2e3302023-03-11 06:46:20 +00001777 "warning: %s: Removing dirty project: uncommitted changes "
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00001778 "lost.",
1779 self.RelPath(local=False),
Gavin Makea2e3302023-03-11 06:46:20 +00001780 )
1781 else:
Jason Chang32b59562023-07-14 16:45:35 -07001782 msg = (
1783 "error: %s: Cannot remove project: uncommitted"
1784 "changes are present.\n" % self.RelPath(local=False)
Gavin Makea2e3302023-03-11 06:46:20 +00001785 )
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00001786 logger.error(msg)
Jason Chang32b59562023-07-14 16:45:35 -07001787 raise DeleteDirtyWorktreeError(msg, project=self)
Wink Saville02d79452009-04-10 13:01:24 -07001788
Tomasz Wasilczyk4c809212023-12-08 13:42:17 -08001789 if verbose:
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04001790 print(f"{self.RelPath(local=False)}: Deleting obsolete checkout.")
Wink Saville02d79452009-04-10 13:01:24 -07001791
Gavin Makea2e3302023-03-11 06:46:20 +00001792 # Unlock and delink from the main worktree. We don't use git's worktree
1793 # remove because it will recursively delete projects -- we handle that
1794 # ourselves below. https://crbug.com/git/48
1795 if self.use_git_worktrees:
1796 needle = platform_utils.realpath(self.gitdir)
1797 # Find the git worktree commondir under .repo/worktrees/.
1798 output = self.bare_git.worktree("list", "--porcelain").splitlines()[
1799 0
1800 ]
1801 assert output.startswith("worktree "), output
1802 commondir = output[9:]
1803 # Walk each of the git worktrees to see where they point.
1804 configs = os.path.join(commondir, "worktrees")
1805 for name in os.listdir(configs):
1806 gitdir = os.path.join(configs, name, "gitdir")
1807 with open(gitdir) as fp:
1808 relpath = fp.read().strip()
1809 # Resolve the checkout path and see if it matches this project.
1810 fullpath = platform_utils.realpath(
1811 os.path.join(configs, name, relpath)
1812 )
1813 if fullpath == needle:
1814 platform_utils.rmtree(os.path.join(configs, name))
Shawn O. Pearce89e717d2009-04-18 15:04:41 -07001815
Gavin Makea2e3302023-03-11 06:46:20 +00001816 # Delete the .git directory first, so we're less likely to have a
1817 # partially working git repository around. There shouldn't be any git
1818 # projects here, so rmtree works.
Shawn O. Pearce89e717d2009-04-18 15:04:41 -07001819
Gavin Makea2e3302023-03-11 06:46:20 +00001820 # Try to remove plain files first in case of git worktrees. If this
1821 # fails for any reason, we'll fall back to rmtree, and that'll display
1822 # errors if it can't remove things either.
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001823 try:
Gavin Makea2e3302023-03-11 06:46:20 +00001824 platform_utils.remove(self.gitdir)
1825 except OSError:
1826 pass
1827 try:
1828 platform_utils.rmtree(self.gitdir)
1829 except OSError as e:
1830 if e.errno != errno.ENOENT:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00001831 logger.error("error: %s: %s", self.gitdir, e)
1832 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +00001833 "error: %s: Failed to delete obsolete checkout; remove "
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00001834 "manually, then run `repo sync -l`.",
1835 self.RelPath(local=False),
Gavin Makea2e3302023-03-11 06:46:20 +00001836 )
Jason Chang32b59562023-07-14 16:45:35 -07001837 raise DeleteWorktreeError(aggregate_errors=[e])
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001838
Gavin Makea2e3302023-03-11 06:46:20 +00001839 # Delete everything under the worktree, except for directories that
1840 # contain another git project.
1841 dirs_to_remove = []
1842 failed = False
Jason Chang32b59562023-07-14 16:45:35 -07001843 errors = []
Gavin Makea2e3302023-03-11 06:46:20 +00001844 for root, dirs, files in platform_utils.walk(self.worktree):
1845 for f in files:
1846 path = os.path.join(root, f)
1847 try:
1848 platform_utils.remove(path)
1849 except OSError as e:
1850 if e.errno != errno.ENOENT:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00001851 logger.error("error: %s: Failed to remove: %s", path, e)
Gavin Makea2e3302023-03-11 06:46:20 +00001852 failed = True
Jason Chang32b59562023-07-14 16:45:35 -07001853 errors.append(e)
Gavin Makea2e3302023-03-11 06:46:20 +00001854 dirs[:] = [
1855 d
1856 for d in dirs
1857 if not os.path.lexists(os.path.join(root, d, ".git"))
1858 ]
1859 dirs_to_remove += [
1860 os.path.join(root, d)
1861 for d in dirs
1862 if os.path.join(root, d) not in dirs_to_remove
1863 ]
1864 for d in reversed(dirs_to_remove):
1865 if platform_utils.islink(d):
1866 try:
1867 platform_utils.remove(d)
1868 except OSError as e:
1869 if e.errno != errno.ENOENT:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00001870 logger.error("error: %s: Failed to remove: %s", d, e)
Gavin Makea2e3302023-03-11 06:46:20 +00001871 failed = True
Jason Chang32b59562023-07-14 16:45:35 -07001872 errors.append(e)
Gavin Makea2e3302023-03-11 06:46:20 +00001873 elif not platform_utils.listdir(d):
1874 try:
1875 platform_utils.rmdir(d)
1876 except OSError as e:
1877 if e.errno != errno.ENOENT:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00001878 logger.error("error: %s: Failed to remove: %s", d, e)
Gavin Makea2e3302023-03-11 06:46:20 +00001879 failed = True
Jason Chang32b59562023-07-14 16:45:35 -07001880 errors.append(e)
Gavin Makea2e3302023-03-11 06:46:20 +00001881 if failed:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00001882 logger.error(
1883 "error: %s: Failed to delete obsolete checkout.",
1884 self.RelPath(local=False),
Gavin Makea2e3302023-03-11 06:46:20 +00001885 )
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00001886 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +00001887 " Remove manually, then run `repo sync -l`.",
Gavin Makea2e3302023-03-11 06:46:20 +00001888 )
Jason Chang32b59562023-07-14 16:45:35 -07001889 raise DeleteWorktreeError(aggregate_errors=errors)
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07001890
Gavin Makea2e3302023-03-11 06:46:20 +00001891 # Try deleting parent dirs if they are empty.
1892 path = self.worktree
1893 while path != self.manifest.topdir:
1894 try:
1895 platform_utils.rmdir(path)
1896 except OSError as e:
1897 if e.errno != errno.ENOENT:
1898 break
1899 path = os.path.dirname(path)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001900
Gavin Makea2e3302023-03-11 06:46:20 +00001901 return True
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001902
Gavin Makea2e3302023-03-11 06:46:20 +00001903 def StartBranch(self, name, branch_merge="", revision=None):
1904 """Create a new branch off the manifest's revision."""
1905 if not branch_merge:
1906 branch_merge = self.revisionExpr
1907 head = self.work_git.GetHead()
1908 if head == (R_HEADS + name):
1909 return True
Shawn O. Pearce88443382010-10-08 10:02:09 +02001910
David Pursehouse8a68ff92012-09-24 12:15:13 +09001911 all_refs = self.bare_ref.all
Gavin Makea2e3302023-03-11 06:46:20 +00001912 if R_HEADS + name in all_refs:
Jason Chang1a3612f2023-08-08 14:12:53 -07001913 GitCommand(
1914 self, ["checkout", "-q", name, "--"], verify_command=True
1915 ).Wait()
1916 return True
Shawn O. Pearce88443382010-10-08 10:02:09 +02001917
Gavin Makea2e3302023-03-11 06:46:20 +00001918 branch = self.GetBranch(name)
1919 branch.remote = self.GetRemote()
1920 branch.merge = branch_merge
Sylvain56a5a012023-09-11 13:38:00 +02001921 if not branch.merge.startswith("refs/") and not IsId(branch_merge):
Gavin Makea2e3302023-03-11 06:46:20 +00001922 branch.merge = R_HEADS + branch_merge
Shawn O. Pearce88443382010-10-08 10:02:09 +02001923
Gavin Makea2e3302023-03-11 06:46:20 +00001924 if revision is None:
1925 revid = self.GetRevisionId(all_refs)
Shawn O. Pearce88443382010-10-08 10:02:09 +02001926 else:
Gavin Makea2e3302023-03-11 06:46:20 +00001927 revid = self.work_git.rev_parse(revision)
Brian Harring14a66742012-09-28 20:21:57 -07001928
Gavin Makea2e3302023-03-11 06:46:20 +00001929 if head.startswith(R_HEADS):
Kevin Degiabaa7f32014-11-12 11:27:45 -07001930 try:
Gavin Makea2e3302023-03-11 06:46:20 +00001931 head = all_refs[head]
1932 except KeyError:
1933 head = None
1934 if revid and head and revid == head:
1935 ref = R_HEADS + name
1936 self.work_git.update_ref(ref, revid)
1937 self.work_git.symbolic_ref(HEAD, ref)
1938 branch.Save()
1939 return True
Kevin Degib1a07b82015-07-27 13:33:43 -06001940
Jason Chang1a3612f2023-08-08 14:12:53 -07001941 GitCommand(
1942 self,
1943 ["checkout", "-q", "-b", branch.name, revid],
1944 verify_command=True,
1945 ).Wait()
1946 branch.Save()
1947 return True
Kevin Degi384b3c52014-10-16 16:02:58 -06001948
Gavin Makea2e3302023-03-11 06:46:20 +00001949 def CheckoutBranch(self, name):
1950 """Checkout a local topic branch.
Shawn O. Pearce2816d4f2009-03-03 17:53:18 -08001951
Gavin Makea2e3302023-03-11 06:46:20 +00001952 Args:
1953 name: The name of the branch to checkout.
Shawn O. Pearce88443382010-10-08 10:02:09 +02001954
Gavin Makea2e3302023-03-11 06:46:20 +00001955 Returns:
Jason Chang1a3612f2023-08-08 14:12:53 -07001956 True if the checkout succeeded; False if the
1957 branch doesn't exist.
Gavin Makea2e3302023-03-11 06:46:20 +00001958 """
1959 rev = R_HEADS + name
1960 head = self.work_git.GetHead()
1961 if head == rev:
1962 # Already on the branch.
1963 return True
Shawn O. Pearce88443382010-10-08 10:02:09 +02001964
Gavin Makea2e3302023-03-11 06:46:20 +00001965 all_refs = self.bare_ref.all
1966 try:
1967 revid = all_refs[rev]
1968 except KeyError:
1969 # Branch does not exist in this project.
Jason Chang1a3612f2023-08-08 14:12:53 -07001970 return False
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001971
Gavin Makea2e3302023-03-11 06:46:20 +00001972 if head.startswith(R_HEADS):
1973 try:
1974 head = all_refs[head]
1975 except KeyError:
1976 head = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001977
Gavin Makea2e3302023-03-11 06:46:20 +00001978 if head == revid:
1979 # Same revision; just update HEAD to point to the new
1980 # target branch, but otherwise take no other action.
1981 _lwrite(
1982 self.work_git.GetDotgitPath(subpath=HEAD),
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04001983 f"ref: {R_HEADS}{name}\n",
Gavin Makea2e3302023-03-11 06:46:20 +00001984 )
1985 return True
Mike Frysinger98bb7652021-12-20 21:15:59 -05001986
Jason Chang1a3612f2023-08-08 14:12:53 -07001987 GitCommand(
1988 self,
1989 ["checkout", name, "--"],
1990 capture_stdout=True,
1991 capture_stderr=True,
1992 verify_command=True,
1993 ).Wait()
1994 return True
Mike Frysinger98bb7652021-12-20 21:15:59 -05001995
Gavin Makea2e3302023-03-11 06:46:20 +00001996 def AbandonBranch(self, name):
1997 """Destroy a local topic branch.
Shawn O. Pearce9452e4e2009-08-22 18:17:46 -07001998
Gavin Makea2e3302023-03-11 06:46:20 +00001999 Args:
2000 name: The name of the branch to abandon.
Shawn O. Pearce9452e4e2009-08-22 18:17:46 -07002001
Gavin Makea2e3302023-03-11 06:46:20 +00002002 Returns:
Jason Changf9aacd42023-08-03 14:38:00 -07002003 True if the abandon succeeded; Raises GitCommandError if it didn't;
2004 None if the branch didn't exist.
Gavin Makea2e3302023-03-11 06:46:20 +00002005 """
2006 rev = R_HEADS + name
2007 all_refs = self.bare_ref.all
2008 if rev not in all_refs:
2009 # Doesn't exist
2010 return None
2011
2012 head = self.work_git.GetHead()
2013 if head == rev:
2014 # We can't destroy the branch while we are sitting
2015 # on it. Switch to a detached HEAD.
2016 head = all_refs[head]
2017
2018 revid = self.GetRevisionId(all_refs)
2019 if head == revid:
2020 _lwrite(
2021 self.work_git.GetDotgitPath(subpath=HEAD), "%s\n" % revid
2022 )
2023 else:
2024 self._Checkout(revid, quiet=True)
Jason Changf9aacd42023-08-03 14:38:00 -07002025 GitCommand(
2026 self,
2027 ["branch", "-D", name],
2028 capture_stdout=True,
2029 capture_stderr=True,
2030 verify_command=True,
2031 ).Wait()
2032 return True
Gavin Makea2e3302023-03-11 06:46:20 +00002033
2034 def PruneHeads(self):
2035 """Prune any topic branches already merged into upstream."""
2036 cb = self.CurrentBranch
2037 kill = []
2038 left = self._allrefs
2039 for name in left.keys():
2040 if name.startswith(R_HEADS):
2041 name = name[len(R_HEADS) :]
2042 if cb is None or name != cb:
2043 kill.append(name)
2044
2045 # Minor optimization: If there's nothing to prune, then don't try to
2046 # read any project state.
2047 if not kill and not cb:
2048 return []
2049
2050 rev = self.GetRevisionId(left)
2051 if (
2052 cb is not None
2053 and not self._revlist(HEAD + "..." + rev)
2054 and not self.IsDirty(consider_untracked=False)
2055 ):
2056 self.work_git.DetachHead(HEAD)
2057 kill.append(cb)
2058
2059 if kill:
2060 old = self.bare_git.GetHead()
2061
2062 try:
2063 self.bare_git.DetachHead(rev)
2064
2065 b = ["branch", "-d"]
2066 b.extend(kill)
2067 b = GitCommand(
2068 self, b, bare=True, capture_stdout=True, capture_stderr=True
2069 )
2070 b.Wait()
2071 finally:
Sylvain56a5a012023-09-11 13:38:00 +02002072 if IsId(old):
Gavin Makea2e3302023-03-11 06:46:20 +00002073 self.bare_git.DetachHead(old)
2074 else:
2075 self.bare_git.SetHead(old)
2076 left = self._allrefs
2077
2078 for branch in kill:
2079 if (R_HEADS + branch) not in left:
2080 self.CleanPublishedCache()
2081 break
2082
2083 if cb and cb not in kill:
2084 kill.append(cb)
2085 kill.sort()
2086
2087 kept = []
2088 for branch in kill:
2089 if R_HEADS + branch in left:
2090 branch = self.GetBranch(branch)
2091 base = branch.LocalMerge
2092 if not base:
2093 base = rev
2094 kept.append(ReviewableBranch(self, branch, base))
2095 return kept
2096
2097 def GetRegisteredSubprojects(self):
2098 result = []
2099
2100 def rec(subprojects):
2101 if not subprojects:
2102 return
2103 result.extend(subprojects)
2104 for p in subprojects:
2105 rec(p.subprojects)
2106
2107 rec(self.subprojects)
2108 return result
2109
2110 def _GetSubmodules(self):
2111 # Unfortunately we cannot call `git submodule status --recursive` here
2112 # because the working tree might not exist yet, and it cannot be used
2113 # without a working tree in its current implementation.
2114
2115 def get_submodules(gitdir, rev):
2116 # Parse .gitmodules for submodule sub_paths and sub_urls.
2117 sub_paths, sub_urls = parse_gitmodules(gitdir, rev)
2118 if not sub_paths:
2119 return []
2120 # Run `git ls-tree` to read SHAs of submodule object, which happen
2121 # to be revision of submodule repository.
2122 sub_revs = git_ls_tree(gitdir, rev, sub_paths)
2123 submodules = []
2124 for sub_path, sub_url in zip(sub_paths, sub_urls):
2125 try:
2126 sub_rev = sub_revs[sub_path]
2127 except KeyError:
2128 # Ignore non-exist submodules.
2129 continue
2130 submodules.append((sub_rev, sub_path, sub_url))
2131 return submodules
2132
2133 re_path = re.compile(r"^submodule\.(.+)\.path=(.*)$")
2134 re_url = re.compile(r"^submodule\.(.+)\.url=(.*)$")
2135
2136 def parse_gitmodules(gitdir, rev):
2137 cmd = ["cat-file", "blob", "%s:.gitmodules" % rev]
2138 try:
2139 p = GitCommand(
2140 None,
2141 cmd,
2142 capture_stdout=True,
2143 capture_stderr=True,
2144 bare=True,
2145 gitdir=gitdir,
2146 )
2147 except GitError:
2148 return [], []
2149 if p.Wait() != 0:
2150 return [], []
2151
2152 gitmodules_lines = []
2153 fd, temp_gitmodules_path = tempfile.mkstemp()
2154 try:
2155 os.write(fd, p.stdout.encode("utf-8"))
2156 os.close(fd)
2157 cmd = ["config", "--file", temp_gitmodules_path, "--list"]
2158 p = GitCommand(
2159 None,
2160 cmd,
2161 capture_stdout=True,
2162 capture_stderr=True,
2163 bare=True,
2164 gitdir=gitdir,
2165 )
2166 if p.Wait() != 0:
2167 return [], []
2168 gitmodules_lines = p.stdout.split("\n")
2169 except GitError:
2170 return [], []
2171 finally:
2172 platform_utils.remove(temp_gitmodules_path)
2173
2174 names = set()
2175 paths = {}
2176 urls = {}
2177 for line in gitmodules_lines:
2178 if not line:
2179 continue
2180 m = re_path.match(line)
2181 if m:
2182 names.add(m.group(1))
2183 paths[m.group(1)] = m.group(2)
2184 continue
2185 m = re_url.match(line)
2186 if m:
2187 names.add(m.group(1))
2188 urls[m.group(1)] = m.group(2)
2189 continue
2190 names = sorted(names)
2191 return (
2192 [paths.get(name, "") for name in names],
2193 [urls.get(name, "") for name in names],
2194 )
2195
2196 def git_ls_tree(gitdir, rev, paths):
2197 cmd = ["ls-tree", rev, "--"]
2198 cmd.extend(paths)
2199 try:
2200 p = GitCommand(
2201 None,
2202 cmd,
2203 capture_stdout=True,
2204 capture_stderr=True,
2205 bare=True,
2206 gitdir=gitdir,
2207 )
2208 except GitError:
2209 return []
2210 if p.Wait() != 0:
2211 return []
2212 objects = {}
2213 for line in p.stdout.split("\n"):
2214 if not line.strip():
2215 continue
2216 object_rev, object_path = line.split()[2:4]
2217 objects[object_path] = object_rev
2218 return objects
2219
2220 try:
2221 rev = self.GetRevisionId()
2222 except GitError:
2223 return []
2224 return get_submodules(self.gitdir, rev)
2225
2226 def GetDerivedSubprojects(self):
2227 result = []
2228 if not self.Exists:
2229 # If git repo does not exist yet, querying its submodules will
2230 # mess up its states; so return here.
2231 return result
2232 for rev, path, url in self._GetSubmodules():
2233 name = self.manifest.GetSubprojectName(self, path)
2234 (
2235 relpath,
2236 worktree,
2237 gitdir,
2238 objdir,
2239 ) = self.manifest.GetSubprojectPaths(self, name, path)
2240 project = self.manifest.paths.get(relpath)
2241 if project:
2242 result.extend(project.GetDerivedSubprojects())
2243 continue
2244
2245 if url.startswith(".."):
2246 url = urllib.parse.urljoin("%s/" % self.remote.url, url)
2247 remote = RemoteSpec(
2248 self.remote.name,
2249 url=url,
2250 pushUrl=self.remote.pushUrl,
2251 review=self.remote.review,
2252 revision=self.remote.revision,
2253 )
2254 subproject = Project(
2255 manifest=self.manifest,
2256 name=name,
2257 remote=remote,
2258 gitdir=gitdir,
2259 objdir=objdir,
2260 worktree=worktree,
2261 relpath=relpath,
2262 revisionExpr=rev,
2263 revisionId=rev,
2264 rebase=self.rebase,
2265 groups=self.groups,
2266 sync_c=self.sync_c,
2267 sync_s=self.sync_s,
2268 sync_tags=self.sync_tags,
2269 parent=self,
2270 is_derived=True,
2271 )
2272 result.append(subproject)
2273 result.extend(subproject.GetDerivedSubprojects())
2274 return result
2275
2276 def EnableRepositoryExtension(self, key, value="true", version=1):
2277 """Enable git repository extension |key| with |value|.
2278
2279 Args:
2280 key: The extension to enabled. Omit the "extensions." prefix.
2281 value: The value to use for the extension.
2282 version: The minimum git repository version needed.
2283 """
2284 # Make sure the git repo version is new enough already.
2285 found_version = self.config.GetInt("core.repositoryFormatVersion")
2286 if found_version is None:
2287 found_version = 0
2288 if found_version < version:
2289 self.config.SetString("core.repositoryFormatVersion", str(version))
2290
2291 # Enable the extension!
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04002292 self.config.SetString(f"extensions.{key}", value)
Gavin Makea2e3302023-03-11 06:46:20 +00002293
2294 def ResolveRemoteHead(self, name=None):
2295 """Find out what the default branch (HEAD) points to.
2296
2297 Normally this points to refs/heads/master, but projects are moving to
2298 main. Support whatever the server uses rather than hardcoding "master"
2299 ourselves.
2300 """
2301 if name is None:
2302 name = self.remote.name
2303
2304 # The output will look like (NB: tabs are separators):
2305 # ref: refs/heads/master HEAD
2306 # 5f6803b100bb3cd0f534e96e88c91373e8ed1c44 HEAD
2307 output = self.bare_git.ls_remote(
2308 "-q", "--symref", "--exit-code", name, "HEAD"
2309 )
2310
2311 for line in output.splitlines():
2312 lhs, rhs = line.split("\t", 1)
2313 if rhs == "HEAD" and lhs.startswith("ref:"):
2314 return lhs[4:].strip()
2315
2316 return None
2317
2318 def _CheckForImmutableRevision(self):
2319 try:
2320 # if revision (sha or tag) is not present then following function
2321 # throws an error.
2322 self.bare_git.rev_list(
Jason Chang87058c62023-09-27 11:34:43 -07002323 "-1",
2324 "--missing=allow-any",
2325 "%s^0" % self.revisionExpr,
2326 "--",
2327 log_as_error=False,
Gavin Makea2e3302023-03-11 06:46:20 +00002328 )
2329 if self.upstream:
2330 rev = self.GetRemote().ToLocal(self.upstream)
2331 self.bare_git.rev_list(
Jason Chang87058c62023-09-27 11:34:43 -07002332 "-1",
2333 "--missing=allow-any",
2334 "%s^0" % rev,
2335 "--",
2336 log_as_error=False,
Gavin Makea2e3302023-03-11 06:46:20 +00002337 )
2338 self.bare_git.merge_base(
Jason Chang87058c62023-09-27 11:34:43 -07002339 "--is-ancestor",
2340 self.revisionExpr,
2341 rev,
2342 log_as_error=False,
Gavin Makea2e3302023-03-11 06:46:20 +00002343 )
2344 return True
2345 except GitError:
2346 # There is no such persistent revision. We have to fetch it.
2347 return False
2348
2349 def _FetchArchive(self, tarpath, cwd=None):
2350 cmd = ["archive", "-v", "-o", tarpath]
2351 cmd.append("--remote=%s" % self.remote.url)
2352 cmd.append("--prefix=%s/" % self.RelPath(local=False))
2353 cmd.append(self.revisionExpr)
2354
2355 command = GitCommand(
Jason Chang32b59562023-07-14 16:45:35 -07002356 self,
2357 cmd,
2358 cwd=cwd,
2359 capture_stdout=True,
2360 capture_stderr=True,
2361 verify_command=True,
Gavin Makea2e3302023-03-11 06:46:20 +00002362 )
Jason Chang32b59562023-07-14 16:45:35 -07002363 command.Wait()
Gavin Makea2e3302023-03-11 06:46:20 +00002364
2365 def _RemoteFetch(
2366 self,
2367 name=None,
2368 current_branch_only=False,
2369 initial=False,
2370 quiet=False,
2371 verbose=False,
2372 output_redir=None,
2373 alt_dir=None,
2374 tags=True,
2375 prune=False,
2376 depth=None,
2377 submodules=False,
2378 ssh_proxy=None,
2379 force_sync=False,
2380 clone_filter=None,
2381 retry_fetches=2,
2382 retry_sleep_initial_sec=4.0,
2383 retry_exp_factor=2.0,
Jason Chang32b59562023-07-14 16:45:35 -07002384 ) -> bool:
Gavin Makea2e3302023-03-11 06:46:20 +00002385 tag_name = None
2386 # The depth should not be used when fetching to a mirror because
2387 # it will result in a shallow repository that cannot be cloned or
2388 # fetched from.
2389 # The repo project should also never be synced with partial depth.
2390 if self.manifest.IsMirror or self.relpath == ".repo/repo":
2391 depth = None
2392
2393 if depth:
2394 current_branch_only = True
2395
Sylvain56a5a012023-09-11 13:38:00 +02002396 is_sha1 = bool(IsId(self.revisionExpr))
Gavin Makea2e3302023-03-11 06:46:20 +00002397
2398 if current_branch_only:
2399 if self.revisionExpr.startswith(R_TAGS):
2400 # This is a tag and its commit id should never change.
2401 tag_name = self.revisionExpr[len(R_TAGS) :]
2402 elif self.upstream and self.upstream.startswith(R_TAGS):
2403 # This is a tag and its commit id should never change.
2404 tag_name = self.upstream[len(R_TAGS) :]
2405
2406 if is_sha1 or tag_name is not None:
2407 if self._CheckForImmutableRevision():
2408 if verbose:
2409 print(
2410 "Skipped fetching project %s (already have "
2411 "persistent ref)" % self.name
2412 )
2413 return True
2414 if is_sha1 and not depth:
2415 # When syncing a specific commit and --depth is not set:
2416 # * if upstream is explicitly specified and is not a sha1, fetch
2417 # only upstream as users expect only upstream to be fetch.
2418 # Note: The commit might not be in upstream in which case the
2419 # sync will fail.
2420 # * otherwise, fetch all branches to make sure we end up with
2421 # the specific commit.
2422 if self.upstream:
Sylvain56a5a012023-09-11 13:38:00 +02002423 current_branch_only = not IsId(self.upstream)
Gavin Makea2e3302023-03-11 06:46:20 +00002424 else:
2425 current_branch_only = False
2426
2427 if not name:
2428 name = self.remote.name
2429
2430 remote = self.GetRemote(name)
2431 if not remote.PreConnectFetch(ssh_proxy):
2432 ssh_proxy = None
2433
2434 if initial:
2435 if alt_dir and "objects" == os.path.basename(alt_dir):
2436 ref_dir = os.path.dirname(alt_dir)
2437 packed_refs = os.path.join(self.gitdir, "packed-refs")
2438
2439 all_refs = self.bare_ref.all
2440 ids = set(all_refs.values())
2441 tmp = set()
2442
2443 for r, ref_id in GitRefs(ref_dir).all.items():
2444 if r not in all_refs:
2445 if r.startswith(R_TAGS) or remote.WritesTo(r):
2446 all_refs[r] = ref_id
2447 ids.add(ref_id)
2448 continue
2449
2450 if ref_id in ids:
2451 continue
2452
2453 r = "refs/_alt/%s" % ref_id
2454 all_refs[r] = ref_id
2455 ids.add(ref_id)
2456 tmp.add(r)
2457
2458 tmp_packed_lines = []
2459 old_packed_lines = []
2460
2461 for r in sorted(all_refs):
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04002462 line = f"{all_refs[r]} {r}\n"
Gavin Makea2e3302023-03-11 06:46:20 +00002463 tmp_packed_lines.append(line)
2464 if r not in tmp:
2465 old_packed_lines.append(line)
2466
2467 tmp_packed = "".join(tmp_packed_lines)
2468 old_packed = "".join(old_packed_lines)
2469 _lwrite(packed_refs, tmp_packed)
2470 else:
2471 alt_dir = None
2472
2473 cmd = ["fetch"]
2474
2475 if clone_filter:
2476 git_require((2, 19, 0), fail=True, msg="partial clones")
2477 cmd.append("--filter=%s" % clone_filter)
2478 self.EnableRepositoryExtension("partialclone", self.remote.name)
2479
2480 if depth:
2481 cmd.append("--depth=%s" % depth)
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08002482 else:
Gavin Makea2e3302023-03-11 06:46:20 +00002483 # If this repo has shallow objects, then we don't know which refs
2484 # have shallow objects or not. Tell git to unshallow all fetched
2485 # refs. Don't do this with projects that don't have shallow
2486 # objects, since it is less efficient.
2487 if os.path.exists(os.path.join(self.gitdir, "shallow")):
2488 cmd.append("--depth=2147483647")
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -08002489
Gavin Makea2e3302023-03-11 06:46:20 +00002490 if not verbose:
2491 cmd.append("--quiet")
2492 if not quiet and sys.stdout.isatty():
2493 cmd.append("--progress")
2494 if not self.worktree:
2495 cmd.append("--update-head-ok")
2496 cmd.append(name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002497
Gavin Makea2e3302023-03-11 06:46:20 +00002498 if force_sync:
2499 cmd.append("--force")
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002500
Gavin Makea2e3302023-03-11 06:46:20 +00002501 if prune:
2502 cmd.append("--prune")
Mike Frysinger29626b42021-05-01 09:37:13 -04002503
Gavin Makea2e3302023-03-11 06:46:20 +00002504 # Always pass something for --recurse-submodules, git with GIT_DIR
2505 # behaves incorrectly when not given `--recurse-submodules=no`.
2506 # (b/218891912)
2507 cmd.append(
2508 f'--recurse-submodules={"on-demand" if submodules else "no"}'
2509 )
Mike Frysinger21b7fbe2020-02-26 23:53:36 -05002510
Gavin Makea2e3302023-03-11 06:46:20 +00002511 spec = []
2512 if not current_branch_only:
2513 # Fetch whole repo.
2514 spec.append(
2515 str(("+refs/heads/*:") + remote.ToLocal("refs/heads/*"))
2516 )
2517 elif tag_name is not None:
2518 spec.append("tag")
2519 spec.append(tag_name)
Remy Böhmer1469c282020-12-15 18:49:02 +01002520
Gavin Makea2e3302023-03-11 06:46:20 +00002521 if self.manifest.IsMirror and not current_branch_only:
2522 branch = None
Remy Böhmer1469c282020-12-15 18:49:02 +01002523 else:
Gavin Makea2e3302023-03-11 06:46:20 +00002524 branch = self.revisionExpr
2525 if (
2526 not self.manifest.IsMirror
2527 and is_sha1
2528 and depth
2529 and git_require((1, 8, 3))
2530 ):
2531 # Shallow checkout of a specific commit, fetch from that commit and
2532 # not the heads only as the commit might be deeper in the history.
2533 spec.append(branch)
2534 if self.upstream:
2535 spec.append(self.upstream)
David James8d201162013-10-11 17:03:19 -07002536 else:
Gavin Makea2e3302023-03-11 06:46:20 +00002537 if is_sha1:
2538 branch = self.upstream
2539 if branch is not None and branch.strip():
2540 if not branch.startswith("refs/"):
2541 branch = R_HEADS + branch
2542 spec.append(str(("+%s:" % branch) + remote.ToLocal(branch)))
David James8d201162013-10-11 17:03:19 -07002543
Gavin Makea2e3302023-03-11 06:46:20 +00002544 # If mirroring repo and we cannot deduce the tag or branch to fetch,
2545 # fetch whole repo.
2546 if self.manifest.IsMirror and not spec:
2547 spec.append(
2548 str(("+refs/heads/*:") + remote.ToLocal("refs/heads/*"))
2549 )
Mike Frysinger979d5bd2020-02-09 02:28:34 -05002550
Gavin Makea2e3302023-03-11 06:46:20 +00002551 # If using depth then we should not get all the tags since they may
2552 # be outside of the depth.
2553 if not tags or depth:
2554 cmd.append("--no-tags")
2555 else:
2556 cmd.append("--tags")
2557 spec.append(str(("+refs/tags/*:") + remote.ToLocal("refs/tags/*")))
Mike Frysinger979d5bd2020-02-09 02:28:34 -05002558
Gavin Makea2e3302023-03-11 06:46:20 +00002559 cmd.extend(spec)
Mike Frysinger21b7fbe2020-02-26 23:53:36 -05002560
Gavin Makea2e3302023-03-11 06:46:20 +00002561 # At least one retry minimum due to git remote prune.
2562 retry_fetches = max(retry_fetches, 2)
2563 retry_cur_sleep = retry_sleep_initial_sec
2564 ok = prune_tried = False
2565 for try_n in range(retry_fetches):
Jason Chang32b59562023-07-14 16:45:35 -07002566 verify_command = try_n == retry_fetches - 1
Gavin Makea2e3302023-03-11 06:46:20 +00002567 gitcmd = GitCommand(
2568 self,
2569 cmd,
2570 bare=True,
2571 objdir=os.path.join(self.objdir, "objects"),
2572 ssh_proxy=ssh_proxy,
2573 merge_output=True,
2574 capture_stdout=quiet or bool(output_redir),
Jason Chang32b59562023-07-14 16:45:35 -07002575 verify_command=verify_command,
Gavin Makea2e3302023-03-11 06:46:20 +00002576 )
2577 if gitcmd.stdout and not quiet and output_redir:
2578 output_redir.write(gitcmd.stdout)
2579 ret = gitcmd.Wait()
2580 if ret == 0:
2581 ok = True
2582 break
Mike Frysinger2a089cf2021-11-13 23:29:42 -05002583
Gavin Makea2e3302023-03-11 06:46:20 +00002584 # Retry later due to HTTP 429 Too Many Requests.
2585 elif (
2586 gitcmd.stdout
2587 and "error:" in gitcmd.stdout
2588 and "HTTP 429" in gitcmd.stdout
2589 ):
2590 # Fallthru to sleep+retry logic at the bottom.
2591 pass
Mike Frysinger2a089cf2021-11-13 23:29:42 -05002592
Gavin Makea2e3302023-03-11 06:46:20 +00002593 # Try to prune remote branches once in case there are conflicts.
2594 # For example, if the remote had refs/heads/upstream, but deleted
2595 # that and now has refs/heads/upstream/foo.
2596 elif (
2597 gitcmd.stdout
2598 and "error:" in gitcmd.stdout
2599 and "git remote prune" in gitcmd.stdout
2600 and not prune_tried
2601 ):
2602 prune_tried = True
2603 prunecmd = GitCommand(
2604 self,
2605 ["remote", "prune", name],
2606 bare=True,
2607 ssh_proxy=ssh_proxy,
2608 )
2609 ret = prunecmd.Wait()
2610 if ret:
2611 break
2612 print(
2613 "retrying fetch after pruning remote branches",
2614 file=output_redir,
2615 )
2616 # Continue right away so we don't sleep as we shouldn't need to.
2617 continue
2618 elif current_branch_only and is_sha1 and ret == 128:
2619 # Exit code 128 means "couldn't find the ref you asked for"; if
2620 # we're in sha1 mode, we just tried sync'ing from the upstream
2621 # field; it doesn't exist, thus abort the optimization attempt
2622 # and do a full sync.
2623 break
2624 elif ret < 0:
2625 # Git died with a signal, exit immediately.
2626 break
Mike Frysinger2a089cf2021-11-13 23:29:42 -05002627
Gavin Makea2e3302023-03-11 06:46:20 +00002628 # Figure out how long to sleep before the next attempt, if there is
2629 # one.
2630 if not verbose and gitcmd.stdout:
2631 print(
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04002632 f"\n{self.name}:\n{gitcmd.stdout}",
Gavin Makea2e3302023-03-11 06:46:20 +00002633 end="",
2634 file=output_redir,
2635 )
2636 if try_n < retry_fetches - 1:
2637 print(
2638 "%s: sleeping %s seconds before retrying"
2639 % (self.name, retry_cur_sleep),
2640 file=output_redir,
2641 )
2642 time.sleep(retry_cur_sleep)
2643 retry_cur_sleep = min(
2644 retry_exp_factor * retry_cur_sleep, MAXIMUM_RETRY_SLEEP_SEC
2645 )
2646 retry_cur_sleep *= 1 - random.uniform(
2647 -RETRY_JITTER_PERCENT, RETRY_JITTER_PERCENT
2648 )
Mike Frysinger2a089cf2021-11-13 23:29:42 -05002649
Gavin Makea2e3302023-03-11 06:46:20 +00002650 if initial:
2651 if alt_dir:
2652 if old_packed != "":
2653 _lwrite(packed_refs, old_packed)
2654 else:
2655 platform_utils.remove(packed_refs)
2656 self.bare_git.pack_refs("--all", "--prune")
Mike Frysinger2a089cf2021-11-13 23:29:42 -05002657
Gavin Makea2e3302023-03-11 06:46:20 +00002658 if is_sha1 and current_branch_only:
2659 # We just synced the upstream given branch; verify we
2660 # got what we wanted, else trigger a second run of all
2661 # refs.
2662 if not self._CheckForImmutableRevision():
2663 # Sync the current branch only with depth set to None.
2664 # We always pass depth=None down to avoid infinite recursion.
2665 return self._RemoteFetch(
2666 name=name,
2667 quiet=quiet,
2668 verbose=verbose,
2669 output_redir=output_redir,
2670 current_branch_only=current_branch_only and depth,
2671 initial=False,
2672 alt_dir=alt_dir,
Nasser Grainawiaafed292023-05-24 12:51:03 -06002673 tags=tags,
Gavin Makea2e3302023-03-11 06:46:20 +00002674 depth=None,
2675 ssh_proxy=ssh_proxy,
2676 clone_filter=clone_filter,
2677 )
Mike Frysinger2a089cf2021-11-13 23:29:42 -05002678
Gavin Makea2e3302023-03-11 06:46:20 +00002679 return ok
Mike Frysingerf4545122019-11-11 04:34:16 -05002680
Gavin Makea2e3302023-03-11 06:46:20 +00002681 def _ApplyCloneBundle(self, initial=False, quiet=False, verbose=False):
2682 if initial and (
2683 self.manifest.manifestProject.depth or self.clone_depth
2684 ):
2685 return False
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002686
Gavin Makea2e3302023-03-11 06:46:20 +00002687 remote = self.GetRemote()
2688 bundle_url = remote.url + "/clone.bundle"
2689 bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
2690 if GetSchemeFromUrl(bundle_url) not in (
2691 "http",
2692 "https",
2693 "persistent-http",
2694 "persistent-https",
2695 ):
2696 return False
Kevin Degi384b3c52014-10-16 16:02:58 -06002697
Gavin Makea2e3302023-03-11 06:46:20 +00002698 bundle_dst = os.path.join(self.gitdir, "clone.bundle")
2699 bundle_tmp = os.path.join(self.gitdir, "clone.bundle.tmp")
2700
2701 exist_dst = os.path.exists(bundle_dst)
2702 exist_tmp = os.path.exists(bundle_tmp)
2703
2704 if not initial and not exist_dst and not exist_tmp:
2705 return False
2706
2707 if not exist_dst:
2708 exist_dst = self._FetchBundle(
2709 bundle_url, bundle_tmp, bundle_dst, quiet, verbose
2710 )
2711 if not exist_dst:
2712 return False
2713
2714 cmd = ["fetch"]
2715 if not verbose:
2716 cmd.append("--quiet")
2717 if not quiet and sys.stdout.isatty():
2718 cmd.append("--progress")
2719 if not self.worktree:
2720 cmd.append("--update-head-ok")
2721 cmd.append(bundle_dst)
2722 for f in remote.fetch:
2723 cmd.append(str(f))
2724 cmd.append("+refs/tags/*:refs/tags/*")
2725
2726 ok = (
2727 GitCommand(
2728 self,
2729 cmd,
2730 bare=True,
2731 objdir=os.path.join(self.objdir, "objects"),
2732 ).Wait()
2733 == 0
2734 )
2735 platform_utils.remove(bundle_dst, missing_ok=True)
2736 platform_utils.remove(bundle_tmp, missing_ok=True)
2737 return ok
2738
2739 def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet, verbose):
2740 platform_utils.remove(dstPath, missing_ok=True)
2741
2742 cmd = ["curl", "--fail", "--output", tmpPath, "--netrc", "--location"]
2743 if quiet:
2744 cmd += ["--silent", "--show-error"]
2745 if os.path.exists(tmpPath):
2746 size = os.stat(tmpPath).st_size
2747 if size >= 1024:
2748 cmd += ["--continue-at", "%d" % (size,)]
2749 else:
2750 platform_utils.remove(tmpPath)
2751 with GetUrlCookieFile(srcUrl, quiet) as (cookiefile, proxy):
2752 if cookiefile:
2753 cmd += ["--cookie", cookiefile]
2754 if proxy:
2755 cmd += ["--proxy", proxy]
2756 elif "http_proxy" in os.environ and "darwin" == sys.platform:
2757 cmd += ["--proxy", os.environ["http_proxy"]]
2758 if srcUrl.startswith("persistent-https"):
2759 srcUrl = "http" + srcUrl[len("persistent-https") :]
2760 elif srcUrl.startswith("persistent-http"):
2761 srcUrl = "http" + srcUrl[len("persistent-http") :]
2762 cmd += [srcUrl]
2763
2764 proc = None
2765 with Trace("Fetching bundle: %s", " ".join(cmd)):
2766 if verbose:
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04002767 print(f"{self.name}: Downloading bundle: {srcUrl}")
Gavin Makea2e3302023-03-11 06:46:20 +00002768 stdout = None if verbose else subprocess.PIPE
2769 stderr = None if verbose else subprocess.STDOUT
2770 try:
2771 proc = subprocess.Popen(cmd, stdout=stdout, stderr=stderr)
2772 except OSError:
2773 return False
2774
2775 (output, _) = proc.communicate()
2776 curlret = proc.returncode
2777
2778 if curlret == 22:
2779 # From curl man page:
2780 # 22: HTTP page not retrieved. The requested url was not found
2781 # or returned another error with the HTTP error code being 400
2782 # or above. This return code only appears if -f, --fail is used.
2783 if verbose:
2784 print(
2785 "%s: Unable to retrieve clone.bundle; ignoring."
2786 % self.name
2787 )
2788 if output:
2789 print("Curl output:\n%s" % output)
2790 return False
2791 elif curlret and not verbose and output:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00002792 logger.error("%s", output)
Gavin Makea2e3302023-03-11 06:46:20 +00002793
2794 if os.path.exists(tmpPath):
2795 if curlret == 0 and self._IsValidBundle(tmpPath, quiet):
2796 platform_utils.rename(tmpPath, dstPath)
2797 return True
2798 else:
2799 platform_utils.remove(tmpPath)
2800 return False
2801 else:
2802 return False
2803
2804 def _IsValidBundle(self, path, quiet):
2805 try:
2806 with open(path, "rb") as f:
2807 if f.read(16) == b"# v2 git bundle\n":
2808 return True
2809 else:
2810 if not quiet:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00002811 logger.error("Invalid clone.bundle file; ignoring.")
Gavin Makea2e3302023-03-11 06:46:20 +00002812 return False
2813 except OSError:
2814 return False
2815
2816 def _Checkout(self, rev, quiet=False):
2817 cmd = ["checkout"]
2818 if quiet:
2819 cmd.append("-q")
2820 cmd.append(rev)
2821 cmd.append("--")
Mike Frysinger2a089cf2021-11-13 23:29:42 -05002822 if GitCommand(self, cmd).Wait() != 0:
Gavin Makea2e3302023-03-11 06:46:20 +00002823 if self._allrefs:
Jason Chang32b59562023-07-14 16:45:35 -07002824 raise GitError(
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04002825 f"{self.name} checkout {rev} ", project=self.name
Jason Chang32b59562023-07-14 16:45:35 -07002826 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002827
Gavin Makea2e3302023-03-11 06:46:20 +00002828 def _CherryPick(self, rev, ffonly=False, record_origin=False):
2829 cmd = ["cherry-pick"]
2830 if ffonly:
2831 cmd.append("--ff")
2832 if record_origin:
2833 cmd.append("-x")
2834 cmd.append(rev)
2835 cmd.append("--")
2836 if GitCommand(self, cmd).Wait() != 0:
2837 if self._allrefs:
Jason Chang32b59562023-07-14 16:45:35 -07002838 raise GitError(
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04002839 f"{self.name} cherry-pick {rev} ", project=self.name
Jason Chang32b59562023-07-14 16:45:35 -07002840 )
Victor Boivie0960b5b2010-11-26 13:42:13 +01002841
Gavin Makea2e3302023-03-11 06:46:20 +00002842 def _LsRemote(self, refs):
2843 cmd = ["ls-remote", self.remote.name, refs]
2844 p = GitCommand(self, cmd, capture_stdout=True)
2845 if p.Wait() == 0:
2846 return p.stdout
2847 return None
Mike Frysinger2a089cf2021-11-13 23:29:42 -05002848
Gavin Makea2e3302023-03-11 06:46:20 +00002849 def _Revert(self, rev):
2850 cmd = ["revert"]
2851 cmd.append("--no-edit")
2852 cmd.append(rev)
2853 cmd.append("--")
2854 if GitCommand(self, cmd).Wait() != 0:
2855 if self._allrefs:
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04002856 raise GitError(f"{self.name} revert {rev} ", project=self.name)
Mike Frysinger2a089cf2021-11-13 23:29:42 -05002857
Gavin Makea2e3302023-03-11 06:46:20 +00002858 def _ResetHard(self, rev, quiet=True):
2859 cmd = ["reset", "--hard"]
2860 if quiet:
2861 cmd.append("-q")
2862 cmd.append(rev)
2863 if GitCommand(self, cmd).Wait() != 0:
Jason Chang32b59562023-07-14 16:45:35 -07002864 raise GitError(
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04002865 f"{self.name} reset --hard {rev} ", project=self.name
Jason Chang32b59562023-07-14 16:45:35 -07002866 )
Mike Frysinger2a089cf2021-11-13 23:29:42 -05002867
Gavin Makea2e3302023-03-11 06:46:20 +00002868 def _SyncSubmodules(self, quiet=True):
2869 cmd = ["submodule", "update", "--init", "--recursive"]
2870 if quiet:
2871 cmd.append("-q")
2872 if GitCommand(self, cmd).Wait() != 0:
2873 raise GitError(
Jason Chang32b59562023-07-14 16:45:35 -07002874 "%s submodule update --init --recursive " % self.name,
2875 project=self.name,
Gavin Makea2e3302023-03-11 06:46:20 +00002876 )
Mike Frysinger89ed8ac2022-01-06 05:42:24 -05002877
Gavin Makea2e3302023-03-11 06:46:20 +00002878 def _Rebase(self, upstream, onto=None):
2879 cmd = ["rebase"]
2880 if onto is not None:
2881 cmd.extend(["--onto", onto])
2882 cmd.append(upstream)
2883 if GitCommand(self, cmd).Wait() != 0:
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04002884 raise GitError(f"{self.name} rebase {upstream} ", project=self.name)
Mike Frysinger89ed8ac2022-01-06 05:42:24 -05002885
Gavin Makea2e3302023-03-11 06:46:20 +00002886 def _FastForward(self, head, ffonly=False):
2887 cmd = ["merge", "--no-stat", head]
2888 if ffonly:
2889 cmd.append("--ff-only")
2890 if GitCommand(self, cmd).Wait() != 0:
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04002891 raise GitError(f"{self.name} merge {head} ", project=self.name)
Mike Frysinger89ed8ac2022-01-06 05:42:24 -05002892
Gavin Makea2e3302023-03-11 06:46:20 +00002893 def _InitGitDir(self, mirror_git=None, force_sync=False, quiet=False):
2894 init_git_dir = not os.path.exists(self.gitdir)
2895 init_obj_dir = not os.path.exists(self.objdir)
2896 try:
2897 # Initialize the bare repository, which contains all of the objects.
2898 if init_obj_dir:
2899 os.makedirs(self.objdir)
2900 self.bare_objdir.init()
Mike Frysinger2a089cf2021-11-13 23:29:42 -05002901
Gavin Makea2e3302023-03-11 06:46:20 +00002902 self._UpdateHooks(quiet=quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002903
Gavin Makea2e3302023-03-11 06:46:20 +00002904 if self.use_git_worktrees:
2905 # Enable per-worktree config file support if possible. This
2906 # is more a nice-to-have feature for users rather than a
2907 # hard requirement.
2908 if git_require((2, 20, 0)):
2909 self.EnableRepositoryExtension("worktreeConfig")
Renaud Paquay788e9622017-01-27 11:41:12 -08002910
Gavin Makea2e3302023-03-11 06:46:20 +00002911 # If we have a separate directory to hold refs, initialize it as
2912 # well.
2913 if self.objdir != self.gitdir:
2914 if init_git_dir:
2915 os.makedirs(self.gitdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002916
Gavin Makea2e3302023-03-11 06:46:20 +00002917 if init_obj_dir or init_git_dir:
2918 self._ReferenceGitDir(
2919 self.objdir, self.gitdir, copy_all=True
2920 )
2921 try:
2922 self._CheckDirReference(self.objdir, self.gitdir)
2923 except GitError as e:
2924 if force_sync:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00002925 logger.error(
2926 "Retrying clone after deleting %s", self.gitdir
Gavin Makea2e3302023-03-11 06:46:20 +00002927 )
2928 try:
2929 platform_utils.rmtree(
2930 platform_utils.realpath(self.gitdir)
2931 )
2932 if self.worktree and os.path.exists(
2933 platform_utils.realpath(self.worktree)
2934 ):
2935 platform_utils.rmtree(
2936 platform_utils.realpath(self.worktree)
2937 )
2938 return self._InitGitDir(
2939 mirror_git=mirror_git,
2940 force_sync=False,
2941 quiet=quiet,
2942 )
2943 except Exception:
2944 raise e
2945 raise e
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002946
Gavin Makea2e3302023-03-11 06:46:20 +00002947 if init_git_dir:
2948 mp = self.manifest.manifestProject
2949 ref_dir = mp.reference or ""
Julien Camperguedd654222014-01-09 16:21:37 +01002950
Gavin Makea2e3302023-03-11 06:46:20 +00002951 def _expanded_ref_dirs():
2952 """Iterate through possible git reference dir paths."""
2953 name = self.name + ".git"
2954 yield mirror_git or os.path.join(ref_dir, name)
2955 for prefix in "", self.remote.name:
2956 yield os.path.join(
2957 ref_dir, ".repo", "project-objects", prefix, name
2958 )
2959 yield os.path.join(
2960 ref_dir, ".repo", "worktrees", prefix, name
2961 )
2962
2963 if ref_dir or mirror_git:
2964 found_ref_dir = None
2965 for path in _expanded_ref_dirs():
2966 if os.path.exists(path):
2967 found_ref_dir = path
2968 break
2969 ref_dir = found_ref_dir
2970
2971 if ref_dir:
2972 if not os.path.isabs(ref_dir):
2973 # The alternate directory is relative to the object
2974 # database.
2975 ref_dir = os.path.relpath(
2976 ref_dir, os.path.join(self.objdir, "objects")
2977 )
2978 _lwrite(
2979 os.path.join(
2980 self.objdir, "objects/info/alternates"
2981 ),
2982 os.path.join(ref_dir, "objects") + "\n",
2983 )
2984
2985 m = self.manifest.manifestProject.config
2986 for key in ["user.name", "user.email"]:
2987 if m.Has(key, include_defaults=False):
2988 self.config.SetString(key, m.GetString(key))
2989 if not self.manifest.EnableGitLfs:
2990 self.config.SetString(
2991 "filter.lfs.smudge", "git-lfs smudge --skip -- %f"
2992 )
2993 self.config.SetString(
2994 "filter.lfs.process", "git-lfs filter-process --skip"
2995 )
2996 self.config.SetBoolean(
2997 "core.bare", True if self.manifest.IsMirror else None
2998 )
Josip Sokcevic9267d582023-10-19 14:46:11 -07002999
3000 if not init_obj_dir:
3001 # The project might be shared (obj_dir already initialized), but
3002 # such information is not available here. Instead of passing it,
3003 # set it as shared, and rely to be unset down the execution
3004 # path.
3005 if git_require((2, 7, 0)):
3006 self.EnableRepositoryExtension("preciousObjects")
3007 else:
3008 self.config.SetString("gc.pruneExpire", "never")
3009
Gavin Makea2e3302023-03-11 06:46:20 +00003010 except Exception:
3011 if init_obj_dir and os.path.exists(self.objdir):
3012 platform_utils.rmtree(self.objdir)
3013 if init_git_dir and os.path.exists(self.gitdir):
3014 platform_utils.rmtree(self.gitdir)
3015 raise
3016
3017 def _UpdateHooks(self, quiet=False):
3018 if os.path.exists(self.objdir):
3019 self._InitHooks(quiet=quiet)
3020
3021 def _InitHooks(self, quiet=False):
3022 hooks = platform_utils.realpath(os.path.join(self.objdir, "hooks"))
3023 if not os.path.exists(hooks):
3024 os.makedirs(hooks)
3025
3026 # Delete sample hooks. They're noise.
3027 for hook in glob.glob(os.path.join(hooks, "*.sample")):
3028 try:
3029 platform_utils.remove(hook, missing_ok=True)
3030 except PermissionError:
3031 pass
3032
3033 for stock_hook in _ProjectHooks():
3034 name = os.path.basename(stock_hook)
3035
3036 if (
3037 name in ("commit-msg",)
3038 and not self.remote.review
3039 and self is not self.manifest.manifestProject
3040 ):
3041 # Don't install a Gerrit Code Review hook if this
3042 # project does not appear to use it for reviews.
3043 #
3044 # Since the manifest project is one of those, but also
3045 # managed through gerrit, it's excluded.
3046 continue
3047
3048 dst = os.path.join(hooks, name)
3049 if platform_utils.islink(dst):
3050 continue
3051 if os.path.exists(dst):
3052 # If the files are the same, we'll leave it alone. We create
3053 # symlinks below by default but fallback to hardlinks if the OS
3054 # blocks them. So if we're here, it's probably because we made a
3055 # hardlink below.
3056 if not filecmp.cmp(stock_hook, dst, shallow=False):
3057 if not quiet:
Aravind Vasudevan8bc50002023-10-13 19:22:47 +00003058 logger.warning(
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00003059 "warn: %s: Not replacing locally modified %s hook",
Gavin Makea2e3302023-03-11 06:46:20 +00003060 self.RelPath(local=False),
3061 name,
3062 )
3063 continue
3064 try:
3065 platform_utils.symlink(
3066 os.path.relpath(stock_hook, os.path.dirname(dst)), dst
3067 )
3068 except OSError as e:
3069 if e.errno == errno.EPERM:
3070 try:
3071 os.link(stock_hook, dst)
3072 except OSError:
Jason Chang32b59562023-07-14 16:45:35 -07003073 raise GitError(
3074 self._get_symlink_error_message(), project=self.name
3075 )
Gavin Makea2e3302023-03-11 06:46:20 +00003076 else:
3077 raise
3078
3079 def _InitRemote(self):
3080 if self.remote.url:
3081 remote = self.GetRemote()
3082 remote.url = self.remote.url
3083 remote.pushUrl = self.remote.pushUrl
3084 remote.review = self.remote.review
3085 remote.projectname = self.name
3086
3087 if self.worktree:
3088 remote.ResetFetch(mirror=False)
3089 else:
3090 remote.ResetFetch(mirror=True)
3091 remote.Save()
3092
3093 def _InitMRef(self):
3094 """Initialize the pseudo m/<manifest branch> ref."""
3095 if self.manifest.branch:
3096 if self.use_git_worktrees:
3097 # Set up the m/ space to point to the worktree-specific ref
3098 # space. We'll update the worktree-specific ref space on each
3099 # checkout.
3100 ref = R_M + self.manifest.branch
3101 if not self.bare_ref.symref(ref):
3102 self.bare_git.symbolic_ref(
3103 "-m",
3104 "redirecting to worktree scope",
3105 ref,
3106 R_WORKTREE_M + self.manifest.branch,
3107 )
3108
3109 # We can't update this ref with git worktrees until it exists.
3110 # We'll wait until the initial checkout to set it.
3111 if not os.path.exists(self.worktree):
3112 return
3113
3114 base = R_WORKTREE_M
3115 active_git = self.work_git
3116
3117 self._InitAnyMRef(HEAD, self.bare_git, detach=True)
3118 else:
3119 base = R_M
3120 active_git = self.bare_git
3121
3122 self._InitAnyMRef(base + self.manifest.branch, active_git)
3123
3124 def _InitMirrorHead(self):
3125 self._InitAnyMRef(HEAD, self.bare_git)
3126
3127 def _InitAnyMRef(self, ref, active_git, detach=False):
3128 """Initialize |ref| in |active_git| to the value in the manifest.
3129
3130 This points |ref| to the <project> setting in the manifest.
3131
3132 Args:
3133 ref: The branch to update.
3134 active_git: The git repository to make updates in.
3135 detach: Whether to update target of symbolic refs, or overwrite the
3136 ref directly (and thus make it non-symbolic).
3137 """
3138 cur = self.bare_ref.symref(ref)
3139
3140 if self.revisionId:
3141 if cur != "" or self.bare_ref.get(ref) != self.revisionId:
3142 msg = "manifest set to %s" % self.revisionId
3143 dst = self.revisionId + "^0"
3144 active_git.UpdateRef(ref, dst, message=msg, detach=True)
Julien Camperguedd654222014-01-09 16:21:37 +01003145 else:
Gavin Makea2e3302023-03-11 06:46:20 +00003146 remote = self.GetRemote()
3147 dst = remote.ToLocal(self.revisionExpr)
3148 if cur != dst:
3149 msg = "manifest set to %s" % self.revisionExpr
3150 if detach:
3151 active_git.UpdateRef(ref, dst, message=msg, detach=True)
3152 else:
3153 active_git.symbolic_ref("-m", msg, ref, dst)
Julien Camperguedd654222014-01-09 16:21:37 +01003154
Gavin Makea2e3302023-03-11 06:46:20 +00003155 def _CheckDirReference(self, srcdir, destdir):
3156 # Git worktrees don't use symlinks to share at all.
3157 if self.use_git_worktrees:
3158 return
Julien Camperguedd654222014-01-09 16:21:37 +01003159
Gavin Makea2e3302023-03-11 06:46:20 +00003160 for name in self.shareable_dirs:
3161 # Try to self-heal a bit in simple cases.
3162 dst_path = os.path.join(destdir, name)
3163 src_path = os.path.join(srcdir, name)
Julien Camperguedd654222014-01-09 16:21:37 +01003164
Gavin Makea2e3302023-03-11 06:46:20 +00003165 dst = platform_utils.realpath(dst_path)
3166 if os.path.lexists(dst):
3167 src = platform_utils.realpath(src_path)
3168 # Fail if the links are pointing to the wrong place.
3169 if src != dst:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00003170 logger.error(
3171 "error: %s is different in %s vs %s",
3172 name,
3173 destdir,
3174 srcdir,
3175 )
Gavin Makea2e3302023-03-11 06:46:20 +00003176 raise GitError(
3177 "--force-sync not enabled; cannot overwrite a local "
3178 "work tree. If you're comfortable with the "
3179 "possibility of losing the work tree's git metadata,"
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04003180 " use "
3181 f"`repo sync --force-sync {self.RelPath(local=False)}` "
3182 "to proceed.",
Jason Chang32b59562023-07-14 16:45:35 -07003183 project=self.name,
Gavin Makea2e3302023-03-11 06:46:20 +00003184 )
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003185
Gavin Makea2e3302023-03-11 06:46:20 +00003186 def _ReferenceGitDir(self, gitdir, dotgit, copy_all):
3187 """Update |dotgit| to reference |gitdir|, using symlinks where possible.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003188
Gavin Makea2e3302023-03-11 06:46:20 +00003189 Args:
3190 gitdir: The bare git repository. Must already be initialized.
3191 dotgit: The repository you would like to initialize.
3192 copy_all: If true, copy all remaining files from |gitdir| ->
3193 |dotgit|. This saves you the effort of initializing |dotgit|
3194 yourself.
3195 """
3196 symlink_dirs = self.shareable_dirs[:]
3197 to_symlink = symlink_dirs
Kimiyuki Onaka0501b292020-08-28 10:05:27 +09003198
Gavin Makea2e3302023-03-11 06:46:20 +00003199 to_copy = []
3200 if copy_all:
3201 to_copy = platform_utils.listdir(gitdir)
Kimiyuki Onaka0501b292020-08-28 10:05:27 +09003202
Gavin Makea2e3302023-03-11 06:46:20 +00003203 dotgit = platform_utils.realpath(dotgit)
3204 for name in set(to_copy).union(to_symlink):
3205 try:
3206 src = platform_utils.realpath(os.path.join(gitdir, name))
3207 dst = os.path.join(dotgit, name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003208
Gavin Makea2e3302023-03-11 06:46:20 +00003209 if os.path.lexists(dst):
3210 continue
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003211
Gavin Makea2e3302023-03-11 06:46:20 +00003212 # If the source dir doesn't exist, create an empty dir.
3213 if name in symlink_dirs and not os.path.lexists(src):
3214 os.makedirs(src)
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003215
Gavin Makea2e3302023-03-11 06:46:20 +00003216 if name in to_symlink:
3217 platform_utils.symlink(
3218 os.path.relpath(src, os.path.dirname(dst)), dst
3219 )
3220 elif copy_all and not platform_utils.islink(dst):
3221 if platform_utils.isdir(src):
3222 shutil.copytree(src, dst)
3223 elif os.path.isfile(src):
3224 shutil.copy(src, dst)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003225
Gavin Makea2e3302023-03-11 06:46:20 +00003226 except OSError as e:
3227 if e.errno == errno.EPERM:
3228 raise DownloadError(self._get_symlink_error_message())
3229 else:
3230 raise
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003231
Gavin Makea2e3302023-03-11 06:46:20 +00003232 def _InitGitWorktree(self):
3233 """Init the project using git worktrees."""
3234 self.bare_git.worktree("prune")
3235 self.bare_git.worktree(
3236 "add",
3237 "-ff",
3238 "--checkout",
3239 "--detach",
3240 "--lock",
3241 self.worktree,
3242 self.GetRevisionId(),
3243 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003244
Gavin Makea2e3302023-03-11 06:46:20 +00003245 # Rewrite the internal state files to use relative paths between the
3246 # checkouts & worktrees.
3247 dotgit = os.path.join(self.worktree, ".git")
Jason R. Coombs034950b2023-10-20 23:32:02 +05453248 with open(dotgit) as fp:
Gavin Makea2e3302023-03-11 06:46:20 +00003249 # Figure out the checkout->worktree path.
Mike Frysinger4b0eb5a2020-02-23 23:22:34 -05003250 setting = fp.read()
Gavin Makea2e3302023-03-11 06:46:20 +00003251 assert setting.startswith("gitdir:")
3252 git_worktree_path = setting.split(":", 1)[1].strip()
3253 # Some platforms (e.g. Windows) won't let us update dotgit in situ
3254 # because of file permissions. Delete it and recreate it from scratch
3255 # to avoid.
3256 platform_utils.remove(dotgit)
3257 # Use relative path from checkout->worktree & maintain Unix line endings
3258 # on all OS's to match git behavior.
3259 with open(dotgit, "w", newline="\n") as fp:
3260 print(
3261 "gitdir:",
3262 os.path.relpath(git_worktree_path, self.worktree),
3263 file=fp,
3264 )
3265 # Use relative path from worktree->checkout & maintain Unix line endings
3266 # on all OS's to match git behavior.
3267 with open(
3268 os.path.join(git_worktree_path, "gitdir"), "w", newline="\n"
3269 ) as fp:
3270 print(os.path.relpath(dotgit, git_worktree_path), file=fp)
Mike Frysinger4b0eb5a2020-02-23 23:22:34 -05003271
Gavin Makea2e3302023-03-11 06:46:20 +00003272 self._InitMRef()
Mike Frysinger4b0eb5a2020-02-23 23:22:34 -05003273
Gavin Makea2e3302023-03-11 06:46:20 +00003274 def _InitWorkTree(self, force_sync=False, submodules=False):
3275 """Setup the worktree .git path.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003276
Gavin Makea2e3302023-03-11 06:46:20 +00003277 This is the user-visible path like src/foo/.git/.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003278
Gavin Makea2e3302023-03-11 06:46:20 +00003279 With non-git-worktrees, this will be a symlink to the .repo/projects/
3280 path. With git-worktrees, this will be a .git file using "gitdir: ..."
3281 syntax.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003282
Gavin Makea2e3302023-03-11 06:46:20 +00003283 Older checkouts had .git/ directories. If we see that, migrate it.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003284
Gavin Makea2e3302023-03-11 06:46:20 +00003285 This also handles changes in the manifest. Maybe this project was
3286 backed by "foo/bar" on the server, but now it's "new/foo/bar". We have
3287 to update the path we point to under .repo/projects/ to match.
3288 """
3289 dotgit = os.path.join(self.worktree, ".git")
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003290
Gavin Makea2e3302023-03-11 06:46:20 +00003291 # If using an old layout style (a directory), migrate it.
3292 if not platform_utils.islink(dotgit) and platform_utils.isdir(dotgit):
Jason Chang32b59562023-07-14 16:45:35 -07003293 self._MigrateOldWorkTreeGitDir(dotgit, project=self.name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003294
Gavin Makea2e3302023-03-11 06:46:20 +00003295 init_dotgit = not os.path.exists(dotgit)
3296 if self.use_git_worktrees:
3297 if init_dotgit:
3298 self._InitGitWorktree()
3299 self._CopyAndLinkFiles()
3300 else:
3301 if not init_dotgit:
3302 # See if the project has changed.
3303 if platform_utils.realpath(
3304 self.gitdir
3305 ) != platform_utils.realpath(dotgit):
3306 platform_utils.remove(dotgit)
Doug Anderson37282b42011-03-04 11:54:18 -08003307
Gavin Makea2e3302023-03-11 06:46:20 +00003308 if init_dotgit or not os.path.exists(dotgit):
3309 os.makedirs(self.worktree, exist_ok=True)
3310 platform_utils.symlink(
3311 os.path.relpath(self.gitdir, self.worktree), dotgit
3312 )
Doug Anderson37282b42011-03-04 11:54:18 -08003313
Gavin Makea2e3302023-03-11 06:46:20 +00003314 if init_dotgit:
3315 _lwrite(
3316 os.path.join(dotgit, HEAD), "%s\n" % self.GetRevisionId()
3317 )
Doug Anderson37282b42011-03-04 11:54:18 -08003318
Gavin Makea2e3302023-03-11 06:46:20 +00003319 # Finish checking out the worktree.
3320 cmd = ["read-tree", "--reset", "-u", "-v", HEAD]
3321 if GitCommand(self, cmd).Wait() != 0:
3322 raise GitError(
Jason Chang32b59562023-07-14 16:45:35 -07003323 "Cannot initialize work tree for " + self.name,
3324 project=self.name,
Gavin Makea2e3302023-03-11 06:46:20 +00003325 )
Doug Anderson37282b42011-03-04 11:54:18 -08003326
Gavin Makea2e3302023-03-11 06:46:20 +00003327 if submodules:
3328 self._SyncSubmodules(quiet=True)
3329 self._CopyAndLinkFiles()
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003330
Gavin Makea2e3302023-03-11 06:46:20 +00003331 @classmethod
Jason Chang32b59562023-07-14 16:45:35 -07003332 def _MigrateOldWorkTreeGitDir(cls, dotgit, project=None):
Gavin Makea2e3302023-03-11 06:46:20 +00003333 """Migrate the old worktree .git/ dir style to a symlink.
3334
3335 This logic specifically only uses state from |dotgit| to figure out
3336 where to move content and not |self|. This way if the backing project
3337 also changed places, we only do the .git/ dir to .git symlink migration
3338 here. The path updates will happen independently.
3339 """
3340 # Figure out where in .repo/projects/ it's pointing to.
3341 if not os.path.islink(os.path.join(dotgit, "refs")):
Jason Chang32b59562023-07-14 16:45:35 -07003342 raise GitError(
3343 f"{dotgit}: unsupported checkout state", project=project
3344 )
Gavin Makea2e3302023-03-11 06:46:20 +00003345 gitdir = os.path.dirname(os.path.realpath(os.path.join(dotgit, "refs")))
3346
3347 # Remove known symlink paths that exist in .repo/projects/.
3348 KNOWN_LINKS = {
3349 "config",
3350 "description",
3351 "hooks",
3352 "info",
3353 "logs",
3354 "objects",
3355 "packed-refs",
3356 "refs",
3357 "rr-cache",
3358 "shallow",
3359 "svn",
3360 }
3361 # Paths that we know will be in both, but are safe to clobber in
3362 # .repo/projects/.
3363 SAFE_TO_CLOBBER = {
3364 "COMMIT_EDITMSG",
3365 "FETCH_HEAD",
3366 "HEAD",
3367 "gc.log",
3368 "gitk.cache",
3369 "index",
3370 "ORIG_HEAD",
3371 }
3372
3373 # First see if we'd succeed before starting the migration.
3374 unknown_paths = []
3375 for name in platform_utils.listdir(dotgit):
3376 # Ignore all temporary/backup names. These are common with vim &
3377 # emacs.
3378 if name.endswith("~") or (name[0] == "#" and name[-1] == "#"):
3379 continue
3380
3381 dotgit_path = os.path.join(dotgit, name)
3382 if name in KNOWN_LINKS:
3383 if not platform_utils.islink(dotgit_path):
3384 unknown_paths.append(f"{dotgit_path}: should be a symlink")
3385 else:
3386 gitdir_path = os.path.join(gitdir, name)
3387 if name not in SAFE_TO_CLOBBER and os.path.exists(gitdir_path):
3388 unknown_paths.append(
3389 f"{dotgit_path}: unknown file; please file a bug"
3390 )
3391 if unknown_paths:
Jason Chang32b59562023-07-14 16:45:35 -07003392 raise GitError(
3393 "Aborting migration: " + "\n".join(unknown_paths),
3394 project=project,
3395 )
Gavin Makea2e3302023-03-11 06:46:20 +00003396
3397 # Now walk the paths and sync the .git/ to .repo/projects/.
3398 for name in platform_utils.listdir(dotgit):
3399 dotgit_path = os.path.join(dotgit, name)
3400
3401 # Ignore all temporary/backup names. These are common with vim &
3402 # emacs.
3403 if name.endswith("~") or (name[0] == "#" and name[-1] == "#"):
3404 platform_utils.remove(dotgit_path)
3405 elif name in KNOWN_LINKS:
3406 platform_utils.remove(dotgit_path)
3407 else:
3408 gitdir_path = os.path.join(gitdir, name)
3409 platform_utils.remove(gitdir_path, missing_ok=True)
3410 platform_utils.rename(dotgit_path, gitdir_path)
3411
3412 # Now that the dir should be empty, clear it out, and symlink it over.
3413 platform_utils.rmdir(dotgit)
3414 platform_utils.symlink(
Jason R. Coombs47944bb2023-09-29 12:42:22 -04003415 os.path.relpath(gitdir, os.path.dirname(os.path.realpath(dotgit))),
3416 dotgit,
Gavin Makea2e3302023-03-11 06:46:20 +00003417 )
3418
3419 def _get_symlink_error_message(self):
3420 if platform_utils.isWindows():
3421 return (
3422 "Unable to create symbolic link. Please re-run the command as "
3423 "Administrator, or see "
3424 "https://github.com/git-for-windows/git/wiki/Symbolic-Links "
3425 "for other options."
3426 )
3427 return "filesystem must support symlinks"
3428
3429 def _revlist(self, *args, **kw):
3430 a = []
3431 a.extend(args)
3432 a.append("--")
3433 return self.work_git.rev_list(*a, **kw)
3434
3435 @property
3436 def _allrefs(self):
3437 return self.bare_ref.all
3438
3439 def _getLogs(
3440 self, rev1, rev2, oneline=False, color=True, pretty_format=None
3441 ):
3442 """Get logs between two revisions of this project."""
3443 comp = ".."
3444 if rev1:
3445 revs = [rev1]
3446 if rev2:
3447 revs.extend([comp, rev2])
3448 cmd = ["log", "".join(revs)]
3449 out = DiffColoring(self.config)
3450 if out.is_on and color:
3451 cmd.append("--color")
3452 if pretty_format is not None:
3453 cmd.append("--pretty=format:%s" % pretty_format)
3454 if oneline:
3455 cmd.append("--oneline")
3456
3457 try:
3458 log = GitCommand(
3459 self, cmd, capture_stdout=True, capture_stderr=True
3460 )
3461 if log.Wait() == 0:
3462 return log.stdout
3463 except GitError:
3464 # worktree may not exist if groups changed for example. In that
3465 # case, try in gitdir instead.
3466 if not os.path.exists(self.worktree):
3467 return self.bare_git.log(*cmd[1:])
3468 else:
3469 raise
3470 return None
3471
3472 def getAddedAndRemovedLogs(
3473 self, toProject, oneline=False, color=True, pretty_format=None
3474 ):
3475 """Get the list of logs from this revision to given revisionId"""
3476 logs = {}
3477 selfId = self.GetRevisionId(self._allrefs)
3478 toId = toProject.GetRevisionId(toProject._allrefs)
3479
3480 logs["added"] = self._getLogs(
3481 selfId,
3482 toId,
3483 oneline=oneline,
3484 color=color,
3485 pretty_format=pretty_format,
3486 )
3487 logs["removed"] = self._getLogs(
3488 toId,
3489 selfId,
3490 oneline=oneline,
3491 color=color,
3492 pretty_format=pretty_format,
3493 )
3494 return logs
3495
Mike Frysingerd4aee652023-10-19 05:13:32 -04003496 class _GitGetByExec:
Gavin Makea2e3302023-03-11 06:46:20 +00003497 def __init__(self, project, bare, gitdir):
3498 self._project = project
3499 self._bare = bare
3500 self._gitdir = gitdir
3501
3502 # __getstate__ and __setstate__ are required for pickling because
3503 # __getattr__ exists.
3504 def __getstate__(self):
3505 return (self._project, self._bare, self._gitdir)
3506
3507 def __setstate__(self, state):
3508 self._project, self._bare, self._gitdir = state
3509
3510 def LsOthers(self):
3511 p = GitCommand(
3512 self._project,
3513 ["ls-files", "-z", "--others", "--exclude-standard"],
3514 bare=False,
3515 gitdir=self._gitdir,
3516 capture_stdout=True,
3517 capture_stderr=True,
3518 )
3519 if p.Wait() == 0:
3520 out = p.stdout
3521 if out:
3522 # Backslash is not anomalous.
3523 return out[:-1].split("\0")
3524 return []
3525
3526 def DiffZ(self, name, *args):
3527 cmd = [name]
3528 cmd.append("-z")
3529 cmd.append("--ignore-submodules")
3530 cmd.extend(args)
3531 p = GitCommand(
3532 self._project,
3533 cmd,
3534 gitdir=self._gitdir,
3535 bare=False,
3536 capture_stdout=True,
3537 capture_stderr=True,
3538 )
3539 p.Wait()
3540 r = {}
3541 out = p.stdout
3542 if out:
3543 out = iter(out[:-1].split("\0"))
3544 while out:
3545 try:
3546 info = next(out)
3547 path = next(out)
3548 except StopIteration:
3549 break
3550
Mike Frysingerd4aee652023-10-19 05:13:32 -04003551 class _Info:
Gavin Makea2e3302023-03-11 06:46:20 +00003552 def __init__(self, path, omode, nmode, oid, nid, state):
3553 self.path = path
3554 self.src_path = None
3555 self.old_mode = omode
3556 self.new_mode = nmode
3557 self.old_id = oid
3558 self.new_id = nid
3559
3560 if len(state) == 1:
3561 self.status = state
3562 self.level = None
3563 else:
3564 self.status = state[:1]
3565 self.level = state[1:]
3566 while self.level.startswith("0"):
3567 self.level = self.level[1:]
3568
3569 info = info[1:].split(" ")
3570 info = _Info(path, *info)
3571 if info.status in ("R", "C"):
3572 info.src_path = info.path
3573 info.path = next(out)
3574 r[info.path] = info
3575 return r
3576
3577 def GetDotgitPath(self, subpath=None):
3578 """Return the full path to the .git dir.
3579
3580 As a convenience, append |subpath| if provided.
3581 """
3582 if self._bare:
3583 dotgit = self._gitdir
3584 else:
3585 dotgit = os.path.join(self._project.worktree, ".git")
3586 if os.path.isfile(dotgit):
3587 # Git worktrees use a "gitdir:" syntax to point to the
3588 # scratch space.
3589 with open(dotgit) as fp:
3590 setting = fp.read()
3591 assert setting.startswith("gitdir:")
3592 gitdir = setting.split(":", 1)[1].strip()
3593 dotgit = os.path.normpath(
3594 os.path.join(self._project.worktree, gitdir)
3595 )
3596
3597 return dotgit if subpath is None else os.path.join(dotgit, subpath)
3598
3599 def GetHead(self):
3600 """Return the ref that HEAD points to."""
3601 path = self.GetDotgitPath(subpath=HEAD)
3602 try:
3603 with open(path) as fd:
3604 line = fd.readline()
Jason R. Coombsae824fb2023-10-20 23:32:40 +05453605 except OSError as e:
Gavin Makea2e3302023-03-11 06:46:20 +00003606 raise NoManifestException(path, str(e))
3607 try:
3608 line = line.decode()
3609 except AttributeError:
3610 pass
3611 if line.startswith("ref: "):
3612 return line[5:-1]
3613 return line[:-1]
3614
3615 def SetHead(self, ref, message=None):
3616 cmdv = []
3617 if message is not None:
3618 cmdv.extend(["-m", message])
3619 cmdv.append(HEAD)
3620 cmdv.append(ref)
3621 self.symbolic_ref(*cmdv)
3622
3623 def DetachHead(self, new, message=None):
3624 cmdv = ["--no-deref"]
3625 if message is not None:
3626 cmdv.extend(["-m", message])
3627 cmdv.append(HEAD)
3628 cmdv.append(new)
3629 self.update_ref(*cmdv)
3630
3631 def UpdateRef(self, name, new, old=None, message=None, detach=False):
3632 cmdv = []
3633 if message is not None:
3634 cmdv.extend(["-m", message])
3635 if detach:
3636 cmdv.append("--no-deref")
3637 cmdv.append(name)
3638 cmdv.append(new)
3639 if old is not None:
3640 cmdv.append(old)
3641 self.update_ref(*cmdv)
3642
3643 def DeleteRef(self, name, old=None):
3644 if not old:
3645 old = self.rev_parse(name)
3646 self.update_ref("-d", name, old)
3647 self._project.bare_ref.deleted(name)
3648
Jason Chang87058c62023-09-27 11:34:43 -07003649 def rev_list(self, *args, log_as_error=True, **kw):
Gavin Makea2e3302023-03-11 06:46:20 +00003650 if "format" in kw:
3651 cmdv = ["log", "--pretty=format:%s" % kw["format"]]
3652 else:
3653 cmdv = ["rev-list"]
3654 cmdv.extend(args)
3655 p = GitCommand(
3656 self._project,
3657 cmdv,
3658 bare=self._bare,
3659 gitdir=self._gitdir,
3660 capture_stdout=True,
3661 capture_stderr=True,
Jason Chang32b59562023-07-14 16:45:35 -07003662 verify_command=True,
Jason Chang87058c62023-09-27 11:34:43 -07003663 log_as_error=log_as_error,
Gavin Makea2e3302023-03-11 06:46:20 +00003664 )
Jason Chang32b59562023-07-14 16:45:35 -07003665 p.Wait()
Gavin Makea2e3302023-03-11 06:46:20 +00003666 return p.stdout.splitlines()
3667
3668 def __getattr__(self, name):
3669 """Allow arbitrary git commands using pythonic syntax.
3670
3671 This allows you to do things like:
3672 git_obj.rev_parse('HEAD')
3673
3674 Since we don't have a 'rev_parse' method defined, the __getattr__
3675 will run. We'll replace the '_' with a '-' and try to run a git
3676 command. Any other positional arguments will be passed to the git
3677 command, and the following keyword arguments are supported:
3678 config: An optional dict of git config options to be passed with
3679 '-c'.
3680
3681 Args:
3682 name: The name of the git command to call. Any '_' characters
3683 will be replaced with '-'.
3684
3685 Returns:
3686 A callable object that will try to call git with the named
3687 command.
3688 """
3689 name = name.replace("_", "-")
3690
Jason Chang87058c62023-09-27 11:34:43 -07003691 def runner(*args, log_as_error=True, **kwargs):
Gavin Makea2e3302023-03-11 06:46:20 +00003692 cmdv = []
3693 config = kwargs.pop("config", None)
3694 for k in kwargs:
3695 raise TypeError(
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04003696 f"{name}() got an unexpected keyword argument {k!r}"
Gavin Makea2e3302023-03-11 06:46:20 +00003697 )
3698 if config is not None:
3699 for k, v in config.items():
3700 cmdv.append("-c")
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04003701 cmdv.append(f"{k}={v}")
Gavin Makea2e3302023-03-11 06:46:20 +00003702 cmdv.append(name)
3703 cmdv.extend(args)
3704 p = GitCommand(
3705 self._project,
3706 cmdv,
3707 bare=self._bare,
3708 gitdir=self._gitdir,
3709 capture_stdout=True,
3710 capture_stderr=True,
Jason Chang32b59562023-07-14 16:45:35 -07003711 verify_command=True,
Jason Chang87058c62023-09-27 11:34:43 -07003712 log_as_error=log_as_error,
Gavin Makea2e3302023-03-11 06:46:20 +00003713 )
Jason Chang32b59562023-07-14 16:45:35 -07003714 p.Wait()
Gavin Makea2e3302023-03-11 06:46:20 +00003715 r = p.stdout
3716 if r.endswith("\n") and r.index("\n") == len(r) - 1:
3717 return r[:-1]
3718 return r
3719
3720 return runner
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003721
3722
Jason Chang32b59562023-07-14 16:45:35 -07003723class LocalSyncFail(RepoError):
3724 """Default error when there is an Sync_LocalHalf error."""
3725
3726
3727class _PriorSyncFailedError(LocalSyncFail):
Gavin Makea2e3302023-03-11 06:46:20 +00003728 def __str__(self):
3729 return "prior sync failed; rebase still in progress"
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003730
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003731
Jason Chang32b59562023-07-14 16:45:35 -07003732class _DirtyError(LocalSyncFail):
Gavin Makea2e3302023-03-11 06:46:20 +00003733 def __str__(self):
3734 return "contains uncommitted changes"
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003735
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003736
Mike Frysingerd4aee652023-10-19 05:13:32 -04003737class _InfoMessage:
Gavin Makea2e3302023-03-11 06:46:20 +00003738 def __init__(self, project, text):
3739 self.project = project
3740 self.text = text
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003741
Gavin Makea2e3302023-03-11 06:46:20 +00003742 def Print(self, syncbuf):
3743 syncbuf.out.info(
3744 "%s/: %s", self.project.RelPath(local=False), self.text
3745 )
3746 syncbuf.out.nl()
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003747
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003748
Mike Frysingerd4aee652023-10-19 05:13:32 -04003749class _Failure:
Gavin Makea2e3302023-03-11 06:46:20 +00003750 def __init__(self, project, why):
3751 self.project = project
3752 self.why = why
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003753
Gavin Makea2e3302023-03-11 06:46:20 +00003754 def Print(self, syncbuf):
3755 syncbuf.out.fail(
3756 "error: %s/: %s", self.project.RelPath(local=False), str(self.why)
3757 )
3758 syncbuf.out.nl()
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003759
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003760
Mike Frysingerd4aee652023-10-19 05:13:32 -04003761class _Later:
Gavin Makea2e3302023-03-11 06:46:20 +00003762 def __init__(self, project, action):
3763 self.project = project
3764 self.action = action
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003765
Gavin Makea2e3302023-03-11 06:46:20 +00003766 def Run(self, syncbuf):
3767 out = syncbuf.out
3768 out.project("project %s/", self.project.RelPath(local=False))
3769 out.nl()
3770 try:
3771 self.action()
3772 out.nl()
3773 return True
3774 except GitError:
3775 out.nl()
3776 return False
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003777
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003778
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003779class _SyncColoring(Coloring):
Gavin Makea2e3302023-03-11 06:46:20 +00003780 def __init__(self, config):
3781 super().__init__(config, "reposync")
3782 self.project = self.printer("header", attr="bold")
3783 self.info = self.printer("info")
3784 self.fail = self.printer("fail", fg="red")
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003785
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003786
Mike Frysingerd4aee652023-10-19 05:13:32 -04003787class SyncBuffer:
Gavin Makea2e3302023-03-11 06:46:20 +00003788 def __init__(self, config, detach_head=False):
3789 self._messages = []
3790 self._failures = []
3791 self._later_queue1 = []
3792 self._later_queue2 = []
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003793
Gavin Makea2e3302023-03-11 06:46:20 +00003794 self.out = _SyncColoring(config)
3795 self.out.redirect(sys.stderr)
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003796
Gavin Makea2e3302023-03-11 06:46:20 +00003797 self.detach_head = detach_head
3798 self.clean = True
3799 self.recent_clean = True
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003800
Gavin Makea2e3302023-03-11 06:46:20 +00003801 def info(self, project, fmt, *args):
3802 self._messages.append(_InfoMessage(project, fmt % args))
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003803
Gavin Makea2e3302023-03-11 06:46:20 +00003804 def fail(self, project, err=None):
3805 self._failures.append(_Failure(project, err))
David Rileye0684ad2017-04-05 00:02:59 -07003806 self._MarkUnclean()
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003807
Gavin Makea2e3302023-03-11 06:46:20 +00003808 def later1(self, project, what):
3809 self._later_queue1.append(_Later(project, what))
Mike Frysinger70d861f2019-08-26 15:22:36 -04003810
Gavin Makea2e3302023-03-11 06:46:20 +00003811 def later2(self, project, what):
3812 self._later_queue2.append(_Later(project, what))
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003813
Gavin Makea2e3302023-03-11 06:46:20 +00003814 def Finish(self):
3815 self._PrintMessages()
3816 self._RunLater()
3817 self._PrintMessages()
3818 return self.clean
3819
3820 def Recently(self):
3821 recent_clean = self.recent_clean
3822 self.recent_clean = True
3823 return recent_clean
3824
3825 def _MarkUnclean(self):
3826 self.clean = False
3827 self.recent_clean = False
3828
3829 def _RunLater(self):
3830 for q in ["_later_queue1", "_later_queue2"]:
3831 if not self._RunQueue(q):
3832 return
3833
3834 def _RunQueue(self, queue):
3835 for m in getattr(self, queue):
3836 if not m.Run(self):
3837 self._MarkUnclean()
3838 return False
3839 setattr(self, queue, [])
3840 return True
3841
3842 def _PrintMessages(self):
3843 if self._messages or self._failures:
3844 if os.isatty(2):
3845 self.out.write(progress.CSI_ERASE_LINE)
3846 self.out.write("\r")
3847
3848 for m in self._messages:
3849 m.Print(self)
3850 for m in self._failures:
3851 m.Print(self)
3852
3853 self._messages = []
3854 self._failures = []
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003855
3856
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003857class MetaProject(Project):
Gavin Makea2e3302023-03-11 06:46:20 +00003858 """A special project housed under .repo."""
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003859
Gavin Makea2e3302023-03-11 06:46:20 +00003860 def __init__(self, manifest, name, gitdir, worktree):
3861 Project.__init__(
3862 self,
3863 manifest=manifest,
3864 name=name,
3865 gitdir=gitdir,
3866 objdir=gitdir,
3867 worktree=worktree,
3868 remote=RemoteSpec("origin"),
3869 relpath=".repo/%s" % name,
3870 revisionExpr="refs/heads/master",
3871 revisionId=None,
3872 groups=None,
3873 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003874
Gavin Makea2e3302023-03-11 06:46:20 +00003875 def PreSync(self):
3876 if self.Exists:
3877 cb = self.CurrentBranch
3878 if cb:
3879 base = self.GetBranch(cb).merge
3880 if base:
3881 self.revisionExpr = base
3882 self.revisionId = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003883
Gavin Makea2e3302023-03-11 06:46:20 +00003884 @property
3885 def HasChanges(self):
3886 """Has the remote received new commits not yet checked out?"""
3887 if not self.remote or not self.revisionExpr:
3888 return False
Shawn O. Pearce336f7bd2009-04-18 10:39:28 -07003889
Gavin Makea2e3302023-03-11 06:46:20 +00003890 all_refs = self.bare_ref.all
3891 revid = self.GetRevisionId(all_refs)
3892 head = self.work_git.GetHead()
3893 if head.startswith(R_HEADS):
3894 try:
3895 head = all_refs[head]
3896 except KeyError:
3897 head = None
Shawn O. Pearce336f7bd2009-04-18 10:39:28 -07003898
Gavin Makea2e3302023-03-11 06:46:20 +00003899 if revid == head:
3900 return False
3901 elif self._revlist(not_rev(HEAD), revid):
3902 return True
3903 return False
LaMont Jones9b72cf22022-03-29 21:54:22 +00003904
3905
3906class RepoProject(MetaProject):
Gavin Makea2e3302023-03-11 06:46:20 +00003907 """The MetaProject for repo itself."""
LaMont Jones9b72cf22022-03-29 21:54:22 +00003908
Gavin Makea2e3302023-03-11 06:46:20 +00003909 @property
3910 def LastFetch(self):
3911 try:
3912 fh = os.path.join(self.gitdir, "FETCH_HEAD")
3913 return os.path.getmtime(fh)
3914 except OSError:
3915 return 0
LaMont Jones9b72cf22022-03-29 21:54:22 +00003916
Sergiy Belozorov78e82ec2023-01-05 18:57:31 +01003917
LaMont Jones9b72cf22022-03-29 21:54:22 +00003918class ManifestProject(MetaProject):
Gavin Makea2e3302023-03-11 06:46:20 +00003919 """The MetaProject for manifests."""
LaMont Jones9b72cf22022-03-29 21:54:22 +00003920
Tomasz Wasilczyk4c809212023-12-08 13:42:17 -08003921 def MetaBranchSwitch(self, submodules=False, verbose=False):
Gavin Makea2e3302023-03-11 06:46:20 +00003922 """Prepare for manifest branch switch."""
LaMont Jones9b72cf22022-03-29 21:54:22 +00003923
Gavin Makea2e3302023-03-11 06:46:20 +00003924 # detach and delete manifest branch, allowing a new
3925 # branch to take over
3926 syncbuf = SyncBuffer(self.config, detach_head=True)
Tomasz Wasilczyk4c809212023-12-08 13:42:17 -08003927 self.Sync_LocalHalf(syncbuf, submodules=submodules, verbose=verbose)
Gavin Makea2e3302023-03-11 06:46:20 +00003928 syncbuf.Finish()
LaMont Jones9b72cf22022-03-29 21:54:22 +00003929
Gavin Makea2e3302023-03-11 06:46:20 +00003930 return (
3931 GitCommand(
3932 self,
3933 ["update-ref", "-d", "refs/heads/default"],
3934 capture_stdout=True,
3935 capture_stderr=True,
3936 ).Wait()
3937 == 0
3938 )
LaMont Jones9b03f152022-03-29 23:01:18 +00003939
Gavin Makea2e3302023-03-11 06:46:20 +00003940 @property
3941 def standalone_manifest_url(self):
3942 """The URL of the standalone manifest, or None."""
3943 return self.config.GetString("manifest.standalone")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003944
Gavin Makea2e3302023-03-11 06:46:20 +00003945 @property
3946 def manifest_groups(self):
3947 """The manifest groups string."""
3948 return self.config.GetString("manifest.groups")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003949
Gavin Makea2e3302023-03-11 06:46:20 +00003950 @property
3951 def reference(self):
3952 """The --reference for this manifest."""
3953 return self.config.GetString("repo.reference")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003954
Gavin Makea2e3302023-03-11 06:46:20 +00003955 @property
3956 def dissociate(self):
3957 """Whether to dissociate."""
3958 return self.config.GetBoolean("repo.dissociate")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003959
Gavin Makea2e3302023-03-11 06:46:20 +00003960 @property
3961 def archive(self):
3962 """Whether we use archive."""
3963 return self.config.GetBoolean("repo.archive")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003964
Gavin Makea2e3302023-03-11 06:46:20 +00003965 @property
3966 def mirror(self):
3967 """Whether we use mirror."""
3968 return self.config.GetBoolean("repo.mirror")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003969
Gavin Makea2e3302023-03-11 06:46:20 +00003970 @property
3971 def use_worktree(self):
3972 """Whether we use worktree."""
3973 return self.config.GetBoolean("repo.worktree")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003974
Gavin Makea2e3302023-03-11 06:46:20 +00003975 @property
3976 def clone_bundle(self):
3977 """Whether we use clone_bundle."""
3978 return self.config.GetBoolean("repo.clonebundle")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003979
Gavin Makea2e3302023-03-11 06:46:20 +00003980 @property
3981 def submodules(self):
3982 """Whether we use submodules."""
3983 return self.config.GetBoolean("repo.submodules")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003984
Gavin Makea2e3302023-03-11 06:46:20 +00003985 @property
3986 def git_lfs(self):
3987 """Whether we use git_lfs."""
3988 return self.config.GetBoolean("repo.git-lfs")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003989
Gavin Makea2e3302023-03-11 06:46:20 +00003990 @property
3991 def use_superproject(self):
3992 """Whether we use superproject."""
3993 return self.config.GetBoolean("repo.superproject")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003994
Gavin Makea2e3302023-03-11 06:46:20 +00003995 @property
3996 def partial_clone(self):
3997 """Whether this is a partial clone."""
3998 return self.config.GetBoolean("repo.partialclone")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003999
Gavin Makea2e3302023-03-11 06:46:20 +00004000 @property
4001 def depth(self):
4002 """Partial clone depth."""
Roberto Vladimir Prado Carranza3d58d212023-09-13 10:27:26 +02004003 return self.config.GetInt("repo.depth")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00004004
Gavin Makea2e3302023-03-11 06:46:20 +00004005 @property
4006 def clone_filter(self):
4007 """The clone filter."""
4008 return self.config.GetString("repo.clonefilter")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00004009
Gavin Makea2e3302023-03-11 06:46:20 +00004010 @property
4011 def partial_clone_exclude(self):
4012 """Partial clone exclude string"""
4013 return self.config.GetString("repo.partialcloneexclude")
LaMont Jones4ada0432022-04-14 15:10:43 +00004014
Gavin Makea2e3302023-03-11 06:46:20 +00004015 @property
Jason Chang17833322023-05-23 13:06:55 -07004016 def clone_filter_for_depth(self):
4017 """Replace shallow clone with partial clone."""
4018 return self.config.GetString("repo.clonefilterfordepth")
4019
4020 @property
Gavin Makea2e3302023-03-11 06:46:20 +00004021 def manifest_platform(self):
4022 """The --platform argument from `repo init`."""
4023 return self.config.GetString("manifest.platform")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00004024
Gavin Makea2e3302023-03-11 06:46:20 +00004025 @property
4026 def _platform_name(self):
4027 """Return the name of the platform."""
4028 return platform.system().lower()
LaMont Jones9b03f152022-03-29 23:01:18 +00004029
Gavin Makea2e3302023-03-11 06:46:20 +00004030 def SyncWithPossibleInit(
4031 self,
4032 submanifest,
4033 verbose=False,
4034 current_branch_only=False,
4035 tags="",
4036 git_event_log=None,
4037 ):
4038 """Sync a manifestProject, possibly for the first time.
LaMont Jonesbdcba7d2022-04-11 22:50:11 +00004039
Gavin Makea2e3302023-03-11 06:46:20 +00004040 Call Sync() with arguments from the most recent `repo init`. If this is
4041 a new sub manifest, then inherit options from the parent's
4042 manifestProject.
LaMont Jonesbdcba7d2022-04-11 22:50:11 +00004043
Gavin Makea2e3302023-03-11 06:46:20 +00004044 This is used by subcmds.Sync() to do an initial download of new sub
4045 manifests.
LaMont Jonesbdcba7d2022-04-11 22:50:11 +00004046
Gavin Makea2e3302023-03-11 06:46:20 +00004047 Args:
4048 submanifest: an XmlSubmanifest, the submanifest to re-sync.
4049 verbose: a boolean, whether to show all output, rather than only
4050 errors.
4051 current_branch_only: a boolean, whether to only fetch the current
4052 manifest branch from the server.
4053 tags: a boolean, whether to fetch tags.
4054 git_event_log: an EventLog, for git tracing.
4055 """
4056 # TODO(lamontjones): when refactoring sync (and init?) consider how to
4057 # better get the init options that we should use for new submanifests
4058 # that are added when syncing an existing workspace.
4059 git_event_log = git_event_log or EventLog()
LaMont Jonesb90a4222022-04-14 15:00:09 +00004060 spec = submanifest.ToSubmanifestSpec()
Gavin Makea2e3302023-03-11 06:46:20 +00004061 # Use the init options from the existing manifestProject, or the parent
4062 # if it doesn't exist.
4063 #
4064 # Today, we only support changing manifest_groups on the sub-manifest,
4065 # with no supported-for-the-user way to change the other arguments from
4066 # those specified by the outermost manifest.
4067 #
4068 # TODO(lamontjones): determine which of these should come from the
4069 # outermost manifest and which should come from the parent manifest.
4070 mp = self if self.Exists else submanifest.parent.manifestProject
4071 return self.Sync(
LaMont Jones55ee3042022-04-06 17:10:21 +00004072 manifest_url=spec.manifestUrl,
4073 manifest_branch=spec.revision,
Gavin Makea2e3302023-03-11 06:46:20 +00004074 standalone_manifest=mp.standalone_manifest_url,
4075 groups=mp.manifest_groups,
4076 platform=mp.manifest_platform,
4077 mirror=mp.mirror,
4078 dissociate=mp.dissociate,
4079 reference=mp.reference,
4080 worktree=mp.use_worktree,
4081 submodules=mp.submodules,
4082 archive=mp.archive,
4083 partial_clone=mp.partial_clone,
4084 clone_filter=mp.clone_filter,
4085 partial_clone_exclude=mp.partial_clone_exclude,
4086 clone_bundle=mp.clone_bundle,
4087 git_lfs=mp.git_lfs,
4088 use_superproject=mp.use_superproject,
LaMont Jones55ee3042022-04-06 17:10:21 +00004089 verbose=verbose,
4090 current_branch_only=current_branch_only,
4091 tags=tags,
Gavin Makea2e3302023-03-11 06:46:20 +00004092 depth=mp.depth,
LaMont Jones55ee3042022-04-06 17:10:21 +00004093 git_event_log=git_event_log,
4094 manifest_name=spec.manifestName,
Gavin Makea2e3302023-03-11 06:46:20 +00004095 this_manifest_only=True,
LaMont Jones55ee3042022-04-06 17:10:21 +00004096 outer_manifest=False,
Jason Chang17833322023-05-23 13:06:55 -07004097 clone_filter_for_depth=mp.clone_filter_for_depth,
LaMont Jones55ee3042022-04-06 17:10:21 +00004098 )
LaMont Jones409407a2022-04-05 21:21:56 +00004099
Gavin Makea2e3302023-03-11 06:46:20 +00004100 def Sync(
4101 self,
4102 _kwargs_only=(),
4103 manifest_url="",
4104 manifest_branch=None,
4105 standalone_manifest=False,
4106 groups="",
4107 mirror=False,
4108 reference="",
4109 dissociate=False,
4110 worktree=False,
4111 submodules=False,
4112 archive=False,
4113 partial_clone=None,
4114 depth=None,
4115 clone_filter="blob:none",
4116 partial_clone_exclude=None,
4117 clone_bundle=None,
4118 git_lfs=None,
4119 use_superproject=None,
4120 verbose=False,
4121 current_branch_only=False,
4122 git_event_log=None,
4123 platform="",
4124 manifest_name="default.xml",
4125 tags="",
4126 this_manifest_only=False,
4127 outer_manifest=True,
Jason Chang17833322023-05-23 13:06:55 -07004128 clone_filter_for_depth=None,
Gavin Makea2e3302023-03-11 06:46:20 +00004129 ):
4130 """Sync the manifest and all submanifests.
LaMont Jones409407a2022-04-05 21:21:56 +00004131
Gavin Makea2e3302023-03-11 06:46:20 +00004132 Args:
4133 manifest_url: a string, the URL of the manifest project.
4134 manifest_branch: a string, the manifest branch to use.
4135 standalone_manifest: a boolean, whether to store the manifest as a
4136 static file.
4137 groups: a string, restricts the checkout to projects with the
4138 specified groups.
4139 mirror: a boolean, whether to create a mirror of the remote
4140 repository.
4141 reference: a string, location of a repo instance to use as a
4142 reference.
4143 dissociate: a boolean, whether to dissociate from reference mirrors
4144 after clone.
4145 worktree: a boolean, whether to use git-worktree to manage projects.
4146 submodules: a boolean, whether sync submodules associated with the
4147 manifest project.
4148 archive: a boolean, whether to checkout each project as an archive.
4149 See git-archive.
4150 partial_clone: a boolean, whether to perform a partial clone.
4151 depth: an int, how deep of a shallow clone to create.
4152 clone_filter: a string, filter to use with partial_clone.
4153 partial_clone_exclude : a string, comma-delimeted list of project
4154 names to exclude from partial clone.
4155 clone_bundle: a boolean, whether to enable /clone.bundle on
4156 HTTP/HTTPS.
4157 git_lfs: a boolean, whether to enable git LFS support.
4158 use_superproject: a boolean, whether to use the manifest
4159 superproject to sync projects.
4160 verbose: a boolean, whether to show all output, rather than only
4161 errors.
4162 current_branch_only: a boolean, whether to only fetch the current
4163 manifest branch from the server.
4164 platform: a string, restrict the checkout to projects with the
4165 specified platform group.
4166 git_event_log: an EventLog, for git tracing.
4167 tags: a boolean, whether to fetch tags.
4168 manifest_name: a string, the name of the manifest file to use.
4169 this_manifest_only: a boolean, whether to only operate on the
4170 current sub manifest.
4171 outer_manifest: a boolean, whether to start at the outermost
4172 manifest.
Jason Chang17833322023-05-23 13:06:55 -07004173 clone_filter_for_depth: a string, when specified replaces shallow
4174 clones with partial.
LaMont Jones9b03f152022-03-29 23:01:18 +00004175
Gavin Makea2e3302023-03-11 06:46:20 +00004176 Returns:
4177 a boolean, whether the sync was successful.
4178 """
4179 assert _kwargs_only == (), "Sync only accepts keyword arguments."
LaMont Jones9b03f152022-03-29 23:01:18 +00004180
Gavin Makea2e3302023-03-11 06:46:20 +00004181 groups = groups or self.manifest.GetDefaultGroupsStr(
4182 with_platform=False
4183 )
4184 platform = platform or "auto"
4185 git_event_log = git_event_log or EventLog()
4186 if outer_manifest and self.manifest.is_submanifest:
4187 # In a multi-manifest checkout, use the outer manifest unless we are
4188 # told not to.
4189 return self.client.outer_manifest.manifestProject.Sync(
4190 manifest_url=manifest_url,
4191 manifest_branch=manifest_branch,
4192 standalone_manifest=standalone_manifest,
4193 groups=groups,
4194 platform=platform,
4195 mirror=mirror,
4196 dissociate=dissociate,
4197 reference=reference,
4198 worktree=worktree,
4199 submodules=submodules,
4200 archive=archive,
4201 partial_clone=partial_clone,
4202 clone_filter=clone_filter,
4203 partial_clone_exclude=partial_clone_exclude,
4204 clone_bundle=clone_bundle,
4205 git_lfs=git_lfs,
4206 use_superproject=use_superproject,
4207 verbose=verbose,
4208 current_branch_only=current_branch_only,
4209 tags=tags,
4210 depth=depth,
4211 git_event_log=git_event_log,
4212 manifest_name=manifest_name,
4213 this_manifest_only=this_manifest_only,
4214 outer_manifest=False,
4215 )
LaMont Jones9b03f152022-03-29 23:01:18 +00004216
Gavin Makea2e3302023-03-11 06:46:20 +00004217 # If repo has already been initialized, we take -u with the absence of
4218 # --standalone-manifest to mean "transition to a standard repo set up",
4219 # which necessitates starting fresh.
4220 # If --standalone-manifest is set, we always tear everything down and
4221 # start anew.
4222 if self.Exists:
4223 was_standalone_manifest = self.config.GetString(
4224 "manifest.standalone"
4225 )
4226 if was_standalone_manifest and not manifest_url:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004227 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +00004228 "fatal: repo was initialized with a standlone manifest, "
4229 "cannot be re-initialized without --manifest-url/-u"
4230 )
4231 return False
4232
4233 if standalone_manifest or (
4234 was_standalone_manifest and manifest_url
4235 ):
4236 self.config.ClearCache()
4237 if self.gitdir and os.path.exists(self.gitdir):
4238 platform_utils.rmtree(self.gitdir)
4239 if self.worktree and os.path.exists(self.worktree):
4240 platform_utils.rmtree(self.worktree)
4241
4242 is_new = not self.Exists
4243 if is_new:
4244 if not manifest_url:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004245 logger.error("fatal: manifest url is required.")
Gavin Makea2e3302023-03-11 06:46:20 +00004246 return False
4247
4248 if verbose:
4249 print(
4250 "Downloading manifest from %s"
4251 % (GitConfig.ForUser().UrlInsteadOf(manifest_url),),
4252 file=sys.stderr,
4253 )
4254
4255 # The manifest project object doesn't keep track of the path on the
4256 # server where this git is located, so let's save that here.
4257 mirrored_manifest_git = None
4258 if reference:
4259 manifest_git_path = urllib.parse.urlparse(manifest_url).path[1:]
4260 mirrored_manifest_git = os.path.join(
4261 reference, manifest_git_path
4262 )
4263 if not mirrored_manifest_git.endswith(".git"):
4264 mirrored_manifest_git += ".git"
4265 if not os.path.exists(mirrored_manifest_git):
4266 mirrored_manifest_git = os.path.join(
4267 reference, ".repo/manifests.git"
4268 )
4269
4270 self._InitGitDir(mirror_git=mirrored_manifest_git)
4271
4272 # If standalone_manifest is set, mark the project as "standalone" --
4273 # we'll still do much of the manifests.git set up, but will avoid actual
4274 # syncs to a remote.
4275 if standalone_manifest:
4276 self.config.SetString("manifest.standalone", manifest_url)
4277 elif not manifest_url and not manifest_branch:
4278 # If -u is set and --standalone-manifest is not, then we're not in
4279 # standalone mode. Otherwise, use config to infer what we were in
4280 # the last init.
4281 standalone_manifest = bool(
4282 self.config.GetString("manifest.standalone")
4283 )
4284 if not standalone_manifest:
4285 self.config.SetString("manifest.standalone", None)
4286
4287 self._ConfigureDepth(depth)
4288
4289 # Set the remote URL before the remote branch as we might need it below.
4290 if manifest_url:
4291 r = self.GetRemote()
4292 r.url = manifest_url
4293 r.ResetFetch()
4294 r.Save()
4295
4296 if not standalone_manifest:
4297 if manifest_branch:
4298 if manifest_branch == "HEAD":
4299 manifest_branch = self.ResolveRemoteHead()
4300 if manifest_branch is None:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004301 logger.error("fatal: unable to resolve HEAD")
Gavin Makea2e3302023-03-11 06:46:20 +00004302 return False
4303 self.revisionExpr = manifest_branch
4304 else:
4305 if is_new:
4306 default_branch = self.ResolveRemoteHead()
4307 if default_branch is None:
4308 # If the remote doesn't have HEAD configured, default to
4309 # master.
4310 default_branch = "refs/heads/master"
4311 self.revisionExpr = default_branch
4312 else:
4313 self.PreSync()
4314
4315 groups = re.split(r"[,\s]+", groups or "")
4316 all_platforms = ["linux", "darwin", "windows"]
4317 platformize = lambda x: "platform-" + x
4318 if platform == "auto":
4319 if not mirror and not self.mirror:
4320 groups.append(platformize(self._platform_name))
4321 elif platform == "all":
4322 groups.extend(map(platformize, all_platforms))
4323 elif platform in all_platforms:
4324 groups.append(platformize(platform))
4325 elif platform != "none":
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004326 logger.error("fatal: invalid platform flag", file=sys.stderr)
Gavin Makea2e3302023-03-11 06:46:20 +00004327 return False
4328 self.config.SetString("manifest.platform", platform)
4329
4330 groups = [x for x in groups if x]
4331 groupstr = ",".join(groups)
4332 if (
4333 platform == "auto"
4334 and groupstr == self.manifest.GetDefaultGroupsStr()
4335 ):
4336 groupstr = None
4337 self.config.SetString("manifest.groups", groupstr)
4338
4339 if reference:
4340 self.config.SetString("repo.reference", reference)
4341
4342 if dissociate:
4343 self.config.SetBoolean("repo.dissociate", dissociate)
4344
4345 if worktree:
4346 if mirror:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004347 logger.error("fatal: --mirror and --worktree are incompatible")
Gavin Makea2e3302023-03-11 06:46:20 +00004348 return False
4349 if submodules:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004350 logger.error(
4351 "fatal: --submodules and --worktree are incompatible"
Gavin Makea2e3302023-03-11 06:46:20 +00004352 )
4353 return False
4354 self.config.SetBoolean("repo.worktree", worktree)
4355 if is_new:
4356 self.use_git_worktrees = True
Aravind Vasudevan8bc50002023-10-13 19:22:47 +00004357 logger.warning("warning: --worktree is experimental!")
Gavin Makea2e3302023-03-11 06:46:20 +00004358
4359 if archive:
4360 if is_new:
4361 self.config.SetBoolean("repo.archive", archive)
4362 else:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004363 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +00004364 "fatal: --archive is only supported when initializing a "
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004365 "new workspace."
Gavin Makea2e3302023-03-11 06:46:20 +00004366 )
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004367 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +00004368 "Either delete the .repo folder in this workspace, or "
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004369 "initialize in another location."
Gavin Makea2e3302023-03-11 06:46:20 +00004370 )
4371 return False
4372
4373 if mirror:
4374 if is_new:
4375 self.config.SetBoolean("repo.mirror", mirror)
4376 else:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004377 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +00004378 "fatal: --mirror is only supported when initializing a new "
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004379 "workspace."
Gavin Makea2e3302023-03-11 06:46:20 +00004380 )
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004381 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +00004382 "Either delete the .repo folder in this workspace, or "
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004383 "initialize in another location."
Gavin Makea2e3302023-03-11 06:46:20 +00004384 )
4385 return False
4386
4387 if partial_clone is not None:
4388 if mirror:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004389 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +00004390 "fatal: --mirror and --partial-clone are mutually "
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004391 "exclusive"
Gavin Makea2e3302023-03-11 06:46:20 +00004392 )
4393 return False
4394 self.config.SetBoolean("repo.partialclone", partial_clone)
4395 if clone_filter:
4396 self.config.SetString("repo.clonefilter", clone_filter)
4397 elif self.partial_clone:
4398 clone_filter = self.clone_filter
4399 else:
4400 clone_filter = None
4401
4402 if partial_clone_exclude is not None:
4403 self.config.SetString(
4404 "repo.partialcloneexclude", partial_clone_exclude
4405 )
4406
4407 if clone_bundle is None:
4408 clone_bundle = False if partial_clone else True
4409 else:
4410 self.config.SetBoolean("repo.clonebundle", clone_bundle)
4411
4412 if submodules:
4413 self.config.SetBoolean("repo.submodules", submodules)
4414
4415 if git_lfs is not None:
4416 if git_lfs:
4417 git_require((2, 17, 0), fail=True, msg="Git LFS support")
4418
4419 self.config.SetBoolean("repo.git-lfs", git_lfs)
4420 if not is_new:
Aravind Vasudevan8bc50002023-10-13 19:22:47 +00004421 logger.warning(
Gavin Makea2e3302023-03-11 06:46:20 +00004422 "warning: Changing --git-lfs settings will only affect new "
4423 "project checkouts.\n"
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004424 " Existing projects will require manual updates.\n"
Gavin Makea2e3302023-03-11 06:46:20 +00004425 )
4426
Jason Chang17833322023-05-23 13:06:55 -07004427 if clone_filter_for_depth is not None:
4428 self.ConfigureCloneFilterForDepth(clone_filter_for_depth)
4429
Gavin Makea2e3302023-03-11 06:46:20 +00004430 if use_superproject is not None:
4431 self.config.SetBoolean("repo.superproject", use_superproject)
4432
4433 if not standalone_manifest:
4434 success = self.Sync_NetworkHalf(
4435 is_new=is_new,
4436 quiet=not verbose,
4437 verbose=verbose,
4438 clone_bundle=clone_bundle,
4439 current_branch_only=current_branch_only,
4440 tags=tags,
4441 submodules=submodules,
4442 clone_filter=clone_filter,
4443 partial_clone_exclude=self.manifest.PartialCloneExclude,
Jason Chang17833322023-05-23 13:06:55 -07004444 clone_filter_for_depth=self.manifest.CloneFilterForDepth,
Gavin Makea2e3302023-03-11 06:46:20 +00004445 ).success
4446 if not success:
4447 r = self.GetRemote()
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004448 logger.error("fatal: cannot obtain manifest %s", r.url)
Gavin Makea2e3302023-03-11 06:46:20 +00004449
4450 # Better delete the manifest git dir if we created it; otherwise
4451 # next time (when user fixes problems) we won't go through the
4452 # "is_new" logic.
4453 if is_new:
4454 platform_utils.rmtree(self.gitdir)
4455 return False
4456
4457 if manifest_branch:
Tomasz Wasilczyk4c809212023-12-08 13:42:17 -08004458 self.MetaBranchSwitch(submodules=submodules, verbose=verbose)
Gavin Makea2e3302023-03-11 06:46:20 +00004459
4460 syncbuf = SyncBuffer(self.config)
Tomasz Wasilczyk4c809212023-12-08 13:42:17 -08004461 self.Sync_LocalHalf(syncbuf, submodules=submodules, verbose=verbose)
Gavin Makea2e3302023-03-11 06:46:20 +00004462 syncbuf.Finish()
4463
4464 if is_new or self.CurrentBranch is None:
Jason Chang1a3612f2023-08-08 14:12:53 -07004465 try:
4466 self.StartBranch("default")
4467 except GitError as e:
4468 msg = str(e)
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004469 logger.error(
4470 "fatal: cannot create default in manifest %s", msg
Gavin Makea2e3302023-03-11 06:46:20 +00004471 )
4472 return False
4473
4474 if not manifest_name:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004475 logger.error("fatal: manifest name (-m) is required.")
Gavin Makea2e3302023-03-11 06:46:20 +00004476 return False
4477
4478 elif is_new:
4479 # This is a new standalone manifest.
4480 manifest_name = "default.xml"
4481 manifest_data = fetch.fetch_file(manifest_url, verbose=verbose)
4482 dest = os.path.join(self.worktree, manifest_name)
4483 os.makedirs(os.path.dirname(dest), exist_ok=True)
4484 with open(dest, "wb") as f:
4485 f.write(manifest_data)
4486
4487 try:
4488 self.manifest.Link(manifest_name)
4489 except ManifestParseError as e:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004490 logger.error("fatal: manifest '%s' not available", manifest_name)
4491 logger.error("fatal: %s", e)
Gavin Makea2e3302023-03-11 06:46:20 +00004492 return False
4493
4494 if not this_manifest_only:
4495 for submanifest in self.manifest.submanifests.values():
4496 spec = submanifest.ToSubmanifestSpec()
4497 submanifest.repo_client.manifestProject.Sync(
4498 manifest_url=spec.manifestUrl,
4499 manifest_branch=spec.revision,
4500 standalone_manifest=standalone_manifest,
4501 groups=self.manifest_groups,
4502 platform=platform,
4503 mirror=mirror,
4504 dissociate=dissociate,
4505 reference=reference,
4506 worktree=worktree,
4507 submodules=submodules,
4508 archive=archive,
4509 partial_clone=partial_clone,
4510 clone_filter=clone_filter,
4511 partial_clone_exclude=partial_clone_exclude,
4512 clone_bundle=clone_bundle,
4513 git_lfs=git_lfs,
4514 use_superproject=use_superproject,
4515 verbose=verbose,
4516 current_branch_only=current_branch_only,
4517 tags=tags,
4518 depth=depth,
4519 git_event_log=git_event_log,
4520 manifest_name=spec.manifestName,
4521 this_manifest_only=False,
4522 outer_manifest=False,
4523 )
4524
4525 # Lastly, if the manifest has a <superproject> then have the
4526 # superproject sync it (if it will be used).
4527 if git_superproject.UseSuperproject(use_superproject, self.manifest):
4528 sync_result = self.manifest.superproject.Sync(git_event_log)
4529 if not sync_result.success:
4530 submanifest = ""
4531 if self.manifest.path_prefix:
4532 submanifest = f"for {self.manifest.path_prefix} "
Aravind Vasudevan8bc50002023-10-13 19:22:47 +00004533 logger.warning(
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004534 "warning: git update of superproject %s failed, "
Gavin Makea2e3302023-03-11 06:46:20 +00004535 "repo sync will not use superproject to fetch source; "
4536 "while this error is not fatal, and you can continue to "
4537 "run repo sync, please run repo init with the "
4538 "--no-use-superproject option to stop seeing this warning",
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004539 submanifest,
Gavin Makea2e3302023-03-11 06:46:20 +00004540 )
4541 if sync_result.fatal and use_superproject is not None:
4542 return False
4543
4544 return True
4545
Jason Chang17833322023-05-23 13:06:55 -07004546 def ConfigureCloneFilterForDepth(self, clone_filter_for_depth):
4547 """Configure clone filter to replace shallow clones.
4548
4549 Args:
4550 clone_filter_for_depth: a string or None, e.g. 'blob:none' will
4551 disable shallow clones and replace with partial clone. None will
4552 enable shallow clones.
4553 """
4554 self.config.SetString(
4555 "repo.clonefilterfordepth", clone_filter_for_depth
4556 )
4557
Gavin Makea2e3302023-03-11 06:46:20 +00004558 def _ConfigureDepth(self, depth):
4559 """Configure the depth we'll sync down.
4560
4561 Args:
4562 depth: an int, how deep of a partial clone to create.
4563 """
4564 # Opt.depth will be non-None if user actually passed --depth to repo
4565 # init.
4566 if depth is not None:
4567 if depth > 0:
4568 # Positive values will set the depth.
4569 depth = str(depth)
4570 else:
4571 # Negative numbers will clear the depth; passing None to
4572 # SetString will do that.
4573 depth = None
4574
4575 # We store the depth in the main manifest project.
4576 self.config.SetString("repo.depth", depth)