blob: db74c6512307f06980a39482ecdbb614fa0df345 [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.
Tomasz Wasilczyk208f3442024-01-05 12:23:10 -08001639 syncbuf.later1(self, _doff, not verbose)
Gavin Makea2e3302023-03-11 06:46:20 +00001640 if submodules:
Tomasz Wasilczyk208f3442024-01-05 12:23:10 -08001641 syncbuf.later1(self, _dosubmodules, not verbose)
Gavin Makea2e3302023-03-11 06:46:20 +00001642 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
Tomasz Wasilczyk208f3442024-01-05 12:23:10 -08001700 syncbuf.later2(self, _dorebase, not verbose)
Gavin Makea2e3302023-03-11 06:46:20 +00001701 if submodules:
Tomasz Wasilczyk208f3442024-01-05 12:23:10 -08001702 syncbuf.later2(self, _dosubmodules, not verbose)
1703 syncbuf.later2(self, _docopyandlink, not verbose)
Gavin Makea2e3302023-03-11 06:46:20 +00001704 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:
Tomasz Wasilczyk208f3442024-01-05 12:23:10 -08001714 syncbuf.later1(self, _doff, not verbose)
Gavin Makea2e3302023-03-11 06:46:20 +00001715 if submodules:
Tomasz Wasilczyk208f3442024-01-05 12:23:10 -08001716 syncbuf.later1(self, _dosubmodules, not verbose)
Gavin Makea2e3302023-03-11 06:46:20 +00001717
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
Tomasz Wasilczyk208f3442024-01-05 12:23:10 -08002886 def _FastForward(self, head, ffonly=False, quiet=True):
Gavin Makea2e3302023-03-11 06:46:20 +00002887 cmd = ["merge", "--no-stat", head]
2888 if ffonly:
2889 cmd.append("--ff-only")
Tomasz Wasilczyk208f3442024-01-05 12:23:10 -08002890 if quiet:
2891 cmd.append("-q")
Gavin Makea2e3302023-03-11 06:46:20 +00002892 if GitCommand(self, cmd).Wait() != 0:
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04002893 raise GitError(f"{self.name} merge {head} ", project=self.name)
Mike Frysinger89ed8ac2022-01-06 05:42:24 -05002894
Gavin Makea2e3302023-03-11 06:46:20 +00002895 def _InitGitDir(self, mirror_git=None, force_sync=False, quiet=False):
2896 init_git_dir = not os.path.exists(self.gitdir)
2897 init_obj_dir = not os.path.exists(self.objdir)
2898 try:
2899 # Initialize the bare repository, which contains all of the objects.
2900 if init_obj_dir:
2901 os.makedirs(self.objdir)
2902 self.bare_objdir.init()
Mike Frysinger2a089cf2021-11-13 23:29:42 -05002903
Gavin Makea2e3302023-03-11 06:46:20 +00002904 self._UpdateHooks(quiet=quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002905
Gavin Makea2e3302023-03-11 06:46:20 +00002906 if self.use_git_worktrees:
2907 # Enable per-worktree config file support if possible. This
2908 # is more a nice-to-have feature for users rather than a
2909 # hard requirement.
2910 if git_require((2, 20, 0)):
2911 self.EnableRepositoryExtension("worktreeConfig")
Renaud Paquay788e9622017-01-27 11:41:12 -08002912
Gavin Makea2e3302023-03-11 06:46:20 +00002913 # If we have a separate directory to hold refs, initialize it as
2914 # well.
2915 if self.objdir != self.gitdir:
2916 if init_git_dir:
2917 os.makedirs(self.gitdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002918
Gavin Makea2e3302023-03-11 06:46:20 +00002919 if init_obj_dir or init_git_dir:
2920 self._ReferenceGitDir(
2921 self.objdir, self.gitdir, copy_all=True
2922 )
2923 try:
2924 self._CheckDirReference(self.objdir, self.gitdir)
2925 except GitError as e:
2926 if force_sync:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00002927 logger.error(
2928 "Retrying clone after deleting %s", self.gitdir
Gavin Makea2e3302023-03-11 06:46:20 +00002929 )
2930 try:
2931 platform_utils.rmtree(
2932 platform_utils.realpath(self.gitdir)
2933 )
2934 if self.worktree and os.path.exists(
2935 platform_utils.realpath(self.worktree)
2936 ):
2937 platform_utils.rmtree(
2938 platform_utils.realpath(self.worktree)
2939 )
2940 return self._InitGitDir(
2941 mirror_git=mirror_git,
2942 force_sync=False,
2943 quiet=quiet,
2944 )
2945 except Exception:
2946 raise e
2947 raise e
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002948
Gavin Makea2e3302023-03-11 06:46:20 +00002949 if init_git_dir:
2950 mp = self.manifest.manifestProject
2951 ref_dir = mp.reference or ""
Julien Camperguedd654222014-01-09 16:21:37 +01002952
Gavin Makea2e3302023-03-11 06:46:20 +00002953 def _expanded_ref_dirs():
2954 """Iterate through possible git reference dir paths."""
2955 name = self.name + ".git"
2956 yield mirror_git or os.path.join(ref_dir, name)
2957 for prefix in "", self.remote.name:
2958 yield os.path.join(
2959 ref_dir, ".repo", "project-objects", prefix, name
2960 )
2961 yield os.path.join(
2962 ref_dir, ".repo", "worktrees", prefix, name
2963 )
2964
2965 if ref_dir or mirror_git:
2966 found_ref_dir = None
2967 for path in _expanded_ref_dirs():
2968 if os.path.exists(path):
2969 found_ref_dir = path
2970 break
2971 ref_dir = found_ref_dir
2972
2973 if ref_dir:
2974 if not os.path.isabs(ref_dir):
2975 # The alternate directory is relative to the object
2976 # database.
2977 ref_dir = os.path.relpath(
2978 ref_dir, os.path.join(self.objdir, "objects")
2979 )
2980 _lwrite(
2981 os.path.join(
2982 self.objdir, "objects/info/alternates"
2983 ),
2984 os.path.join(ref_dir, "objects") + "\n",
2985 )
2986
2987 m = self.manifest.manifestProject.config
2988 for key in ["user.name", "user.email"]:
2989 if m.Has(key, include_defaults=False):
2990 self.config.SetString(key, m.GetString(key))
2991 if not self.manifest.EnableGitLfs:
2992 self.config.SetString(
2993 "filter.lfs.smudge", "git-lfs smudge --skip -- %f"
2994 )
2995 self.config.SetString(
2996 "filter.lfs.process", "git-lfs filter-process --skip"
2997 )
2998 self.config.SetBoolean(
2999 "core.bare", True if self.manifest.IsMirror else None
3000 )
Josip Sokcevic9267d582023-10-19 14:46:11 -07003001
3002 if not init_obj_dir:
3003 # The project might be shared (obj_dir already initialized), but
3004 # such information is not available here. Instead of passing it,
3005 # set it as shared, and rely to be unset down the execution
3006 # path.
3007 if git_require((2, 7, 0)):
3008 self.EnableRepositoryExtension("preciousObjects")
3009 else:
3010 self.config.SetString("gc.pruneExpire", "never")
3011
Gavin Makea2e3302023-03-11 06:46:20 +00003012 except Exception:
3013 if init_obj_dir and os.path.exists(self.objdir):
3014 platform_utils.rmtree(self.objdir)
3015 if init_git_dir and os.path.exists(self.gitdir):
3016 platform_utils.rmtree(self.gitdir)
3017 raise
3018
3019 def _UpdateHooks(self, quiet=False):
3020 if os.path.exists(self.objdir):
3021 self._InitHooks(quiet=quiet)
3022
3023 def _InitHooks(self, quiet=False):
3024 hooks = platform_utils.realpath(os.path.join(self.objdir, "hooks"))
3025 if not os.path.exists(hooks):
3026 os.makedirs(hooks)
3027
3028 # Delete sample hooks. They're noise.
3029 for hook in glob.glob(os.path.join(hooks, "*.sample")):
3030 try:
3031 platform_utils.remove(hook, missing_ok=True)
3032 except PermissionError:
3033 pass
3034
3035 for stock_hook in _ProjectHooks():
3036 name = os.path.basename(stock_hook)
3037
3038 if (
3039 name in ("commit-msg",)
3040 and not self.remote.review
3041 and self is not self.manifest.manifestProject
3042 ):
3043 # Don't install a Gerrit Code Review hook if this
3044 # project does not appear to use it for reviews.
3045 #
3046 # Since the manifest project is one of those, but also
3047 # managed through gerrit, it's excluded.
3048 continue
3049
3050 dst = os.path.join(hooks, name)
3051 if platform_utils.islink(dst):
3052 continue
3053 if os.path.exists(dst):
3054 # If the files are the same, we'll leave it alone. We create
3055 # symlinks below by default but fallback to hardlinks if the OS
3056 # blocks them. So if we're here, it's probably because we made a
3057 # hardlink below.
3058 if not filecmp.cmp(stock_hook, dst, shallow=False):
3059 if not quiet:
Aravind Vasudevan8bc50002023-10-13 19:22:47 +00003060 logger.warning(
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00003061 "warn: %s: Not replacing locally modified %s hook",
Gavin Makea2e3302023-03-11 06:46:20 +00003062 self.RelPath(local=False),
3063 name,
3064 )
3065 continue
3066 try:
3067 platform_utils.symlink(
3068 os.path.relpath(stock_hook, os.path.dirname(dst)), dst
3069 )
3070 except OSError as e:
3071 if e.errno == errno.EPERM:
3072 try:
3073 os.link(stock_hook, dst)
3074 except OSError:
Jason Chang32b59562023-07-14 16:45:35 -07003075 raise GitError(
3076 self._get_symlink_error_message(), project=self.name
3077 )
Gavin Makea2e3302023-03-11 06:46:20 +00003078 else:
3079 raise
3080
3081 def _InitRemote(self):
3082 if self.remote.url:
3083 remote = self.GetRemote()
3084 remote.url = self.remote.url
3085 remote.pushUrl = self.remote.pushUrl
3086 remote.review = self.remote.review
3087 remote.projectname = self.name
3088
3089 if self.worktree:
3090 remote.ResetFetch(mirror=False)
3091 else:
3092 remote.ResetFetch(mirror=True)
3093 remote.Save()
3094
3095 def _InitMRef(self):
3096 """Initialize the pseudo m/<manifest branch> ref."""
3097 if self.manifest.branch:
3098 if self.use_git_worktrees:
3099 # Set up the m/ space to point to the worktree-specific ref
3100 # space. We'll update the worktree-specific ref space on each
3101 # checkout.
3102 ref = R_M + self.manifest.branch
3103 if not self.bare_ref.symref(ref):
3104 self.bare_git.symbolic_ref(
3105 "-m",
3106 "redirecting to worktree scope",
3107 ref,
3108 R_WORKTREE_M + self.manifest.branch,
3109 )
3110
3111 # We can't update this ref with git worktrees until it exists.
3112 # We'll wait until the initial checkout to set it.
3113 if not os.path.exists(self.worktree):
3114 return
3115
3116 base = R_WORKTREE_M
3117 active_git = self.work_git
3118
3119 self._InitAnyMRef(HEAD, self.bare_git, detach=True)
3120 else:
3121 base = R_M
3122 active_git = self.bare_git
3123
3124 self._InitAnyMRef(base + self.manifest.branch, active_git)
3125
3126 def _InitMirrorHead(self):
3127 self._InitAnyMRef(HEAD, self.bare_git)
3128
3129 def _InitAnyMRef(self, ref, active_git, detach=False):
3130 """Initialize |ref| in |active_git| to the value in the manifest.
3131
3132 This points |ref| to the <project> setting in the manifest.
3133
3134 Args:
3135 ref: The branch to update.
3136 active_git: The git repository to make updates in.
3137 detach: Whether to update target of symbolic refs, or overwrite the
3138 ref directly (and thus make it non-symbolic).
3139 """
3140 cur = self.bare_ref.symref(ref)
3141
3142 if self.revisionId:
3143 if cur != "" or self.bare_ref.get(ref) != self.revisionId:
3144 msg = "manifest set to %s" % self.revisionId
3145 dst = self.revisionId + "^0"
3146 active_git.UpdateRef(ref, dst, message=msg, detach=True)
Julien Camperguedd654222014-01-09 16:21:37 +01003147 else:
Gavin Makea2e3302023-03-11 06:46:20 +00003148 remote = self.GetRemote()
3149 dst = remote.ToLocal(self.revisionExpr)
3150 if cur != dst:
3151 msg = "manifest set to %s" % self.revisionExpr
3152 if detach:
3153 active_git.UpdateRef(ref, dst, message=msg, detach=True)
3154 else:
3155 active_git.symbolic_ref("-m", msg, ref, dst)
Julien Camperguedd654222014-01-09 16:21:37 +01003156
Gavin Makea2e3302023-03-11 06:46:20 +00003157 def _CheckDirReference(self, srcdir, destdir):
3158 # Git worktrees don't use symlinks to share at all.
3159 if self.use_git_worktrees:
3160 return
Julien Camperguedd654222014-01-09 16:21:37 +01003161
Gavin Makea2e3302023-03-11 06:46:20 +00003162 for name in self.shareable_dirs:
3163 # Try to self-heal a bit in simple cases.
3164 dst_path = os.path.join(destdir, name)
3165 src_path = os.path.join(srcdir, name)
Julien Camperguedd654222014-01-09 16:21:37 +01003166
Gavin Makea2e3302023-03-11 06:46:20 +00003167 dst = platform_utils.realpath(dst_path)
3168 if os.path.lexists(dst):
3169 src = platform_utils.realpath(src_path)
3170 # Fail if the links are pointing to the wrong place.
3171 if src != dst:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00003172 logger.error(
3173 "error: %s is different in %s vs %s",
3174 name,
3175 destdir,
3176 srcdir,
3177 )
Gavin Makea2e3302023-03-11 06:46:20 +00003178 raise GitError(
3179 "--force-sync not enabled; cannot overwrite a local "
3180 "work tree. If you're comfortable with the "
3181 "possibility of losing the work tree's git metadata,"
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04003182 " use "
3183 f"`repo sync --force-sync {self.RelPath(local=False)}` "
3184 "to proceed.",
Jason Chang32b59562023-07-14 16:45:35 -07003185 project=self.name,
Gavin Makea2e3302023-03-11 06:46:20 +00003186 )
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003187
Gavin Makea2e3302023-03-11 06:46:20 +00003188 def _ReferenceGitDir(self, gitdir, dotgit, copy_all):
3189 """Update |dotgit| to reference |gitdir|, using symlinks where possible.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003190
Gavin Makea2e3302023-03-11 06:46:20 +00003191 Args:
3192 gitdir: The bare git repository. Must already be initialized.
3193 dotgit: The repository you would like to initialize.
3194 copy_all: If true, copy all remaining files from |gitdir| ->
3195 |dotgit|. This saves you the effort of initializing |dotgit|
3196 yourself.
3197 """
3198 symlink_dirs = self.shareable_dirs[:]
3199 to_symlink = symlink_dirs
Kimiyuki Onaka0501b292020-08-28 10:05:27 +09003200
Gavin Makea2e3302023-03-11 06:46:20 +00003201 to_copy = []
3202 if copy_all:
3203 to_copy = platform_utils.listdir(gitdir)
Kimiyuki Onaka0501b292020-08-28 10:05:27 +09003204
Gavin Makea2e3302023-03-11 06:46:20 +00003205 dotgit = platform_utils.realpath(dotgit)
3206 for name in set(to_copy).union(to_symlink):
3207 try:
3208 src = platform_utils.realpath(os.path.join(gitdir, name))
3209 dst = os.path.join(dotgit, name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003210
Gavin Makea2e3302023-03-11 06:46:20 +00003211 if os.path.lexists(dst):
3212 continue
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003213
Gavin Makea2e3302023-03-11 06:46:20 +00003214 # If the source dir doesn't exist, create an empty dir.
3215 if name in symlink_dirs and not os.path.lexists(src):
3216 os.makedirs(src)
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003217
Gavin Makea2e3302023-03-11 06:46:20 +00003218 if name in to_symlink:
3219 platform_utils.symlink(
3220 os.path.relpath(src, os.path.dirname(dst)), dst
3221 )
3222 elif copy_all and not platform_utils.islink(dst):
3223 if platform_utils.isdir(src):
3224 shutil.copytree(src, dst)
3225 elif os.path.isfile(src):
3226 shutil.copy(src, dst)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003227
Gavin Makea2e3302023-03-11 06:46:20 +00003228 except OSError as e:
3229 if e.errno == errno.EPERM:
3230 raise DownloadError(self._get_symlink_error_message())
3231 else:
3232 raise
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003233
Gavin Makea2e3302023-03-11 06:46:20 +00003234 def _InitGitWorktree(self):
3235 """Init the project using git worktrees."""
3236 self.bare_git.worktree("prune")
3237 self.bare_git.worktree(
3238 "add",
3239 "-ff",
3240 "--checkout",
3241 "--detach",
3242 "--lock",
3243 self.worktree,
3244 self.GetRevisionId(),
3245 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003246
Gavin Makea2e3302023-03-11 06:46:20 +00003247 # Rewrite the internal state files to use relative paths between the
3248 # checkouts & worktrees.
3249 dotgit = os.path.join(self.worktree, ".git")
Jason R. Coombs034950b2023-10-20 23:32:02 +05453250 with open(dotgit) as fp:
Gavin Makea2e3302023-03-11 06:46:20 +00003251 # Figure out the checkout->worktree path.
Mike Frysinger4b0eb5a2020-02-23 23:22:34 -05003252 setting = fp.read()
Gavin Makea2e3302023-03-11 06:46:20 +00003253 assert setting.startswith("gitdir:")
3254 git_worktree_path = setting.split(":", 1)[1].strip()
3255 # Some platforms (e.g. Windows) won't let us update dotgit in situ
3256 # because of file permissions. Delete it and recreate it from scratch
3257 # to avoid.
3258 platform_utils.remove(dotgit)
3259 # Use relative path from checkout->worktree & maintain Unix line endings
3260 # on all OS's to match git behavior.
3261 with open(dotgit, "w", newline="\n") as fp:
3262 print(
3263 "gitdir:",
3264 os.path.relpath(git_worktree_path, self.worktree),
3265 file=fp,
3266 )
3267 # Use relative path from worktree->checkout & maintain Unix line endings
3268 # on all OS's to match git behavior.
3269 with open(
3270 os.path.join(git_worktree_path, "gitdir"), "w", newline="\n"
3271 ) as fp:
3272 print(os.path.relpath(dotgit, git_worktree_path), file=fp)
Mike Frysinger4b0eb5a2020-02-23 23:22:34 -05003273
Gavin Makea2e3302023-03-11 06:46:20 +00003274 self._InitMRef()
Mike Frysinger4b0eb5a2020-02-23 23:22:34 -05003275
Gavin Makea2e3302023-03-11 06:46:20 +00003276 def _InitWorkTree(self, force_sync=False, submodules=False):
3277 """Setup the worktree .git path.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003278
Gavin Makea2e3302023-03-11 06:46:20 +00003279 This is the user-visible path like src/foo/.git/.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003280
Gavin Makea2e3302023-03-11 06:46:20 +00003281 With non-git-worktrees, this will be a symlink to the .repo/projects/
3282 path. With git-worktrees, this will be a .git file using "gitdir: ..."
3283 syntax.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003284
Gavin Makea2e3302023-03-11 06:46:20 +00003285 Older checkouts had .git/ directories. If we see that, migrate it.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003286
Gavin Makea2e3302023-03-11 06:46:20 +00003287 This also handles changes in the manifest. Maybe this project was
3288 backed by "foo/bar" on the server, but now it's "new/foo/bar". We have
3289 to update the path we point to under .repo/projects/ to match.
3290 """
3291 dotgit = os.path.join(self.worktree, ".git")
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003292
Gavin Makea2e3302023-03-11 06:46:20 +00003293 # If using an old layout style (a directory), migrate it.
3294 if not platform_utils.islink(dotgit) and platform_utils.isdir(dotgit):
Jason Chang32b59562023-07-14 16:45:35 -07003295 self._MigrateOldWorkTreeGitDir(dotgit, project=self.name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003296
Gavin Makea2e3302023-03-11 06:46:20 +00003297 init_dotgit = not os.path.exists(dotgit)
3298 if self.use_git_worktrees:
3299 if init_dotgit:
3300 self._InitGitWorktree()
3301 self._CopyAndLinkFiles()
3302 else:
3303 if not init_dotgit:
3304 # See if the project has changed.
3305 if platform_utils.realpath(
3306 self.gitdir
3307 ) != platform_utils.realpath(dotgit):
3308 platform_utils.remove(dotgit)
Doug Anderson37282b42011-03-04 11:54:18 -08003309
Gavin Makea2e3302023-03-11 06:46:20 +00003310 if init_dotgit or not os.path.exists(dotgit):
3311 os.makedirs(self.worktree, exist_ok=True)
3312 platform_utils.symlink(
3313 os.path.relpath(self.gitdir, self.worktree), dotgit
3314 )
Doug Anderson37282b42011-03-04 11:54:18 -08003315
Gavin Makea2e3302023-03-11 06:46:20 +00003316 if init_dotgit:
3317 _lwrite(
3318 os.path.join(dotgit, HEAD), "%s\n" % self.GetRevisionId()
3319 )
Doug Anderson37282b42011-03-04 11:54:18 -08003320
Gavin Makea2e3302023-03-11 06:46:20 +00003321 # Finish checking out the worktree.
3322 cmd = ["read-tree", "--reset", "-u", "-v", HEAD]
3323 if GitCommand(self, cmd).Wait() != 0:
3324 raise GitError(
Jason Chang32b59562023-07-14 16:45:35 -07003325 "Cannot initialize work tree for " + self.name,
3326 project=self.name,
Gavin Makea2e3302023-03-11 06:46:20 +00003327 )
Doug Anderson37282b42011-03-04 11:54:18 -08003328
Gavin Makea2e3302023-03-11 06:46:20 +00003329 if submodules:
3330 self._SyncSubmodules(quiet=True)
3331 self._CopyAndLinkFiles()
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003332
Gavin Makea2e3302023-03-11 06:46:20 +00003333 @classmethod
Jason Chang32b59562023-07-14 16:45:35 -07003334 def _MigrateOldWorkTreeGitDir(cls, dotgit, project=None):
Gavin Makea2e3302023-03-11 06:46:20 +00003335 """Migrate the old worktree .git/ dir style to a symlink.
3336
3337 This logic specifically only uses state from |dotgit| to figure out
3338 where to move content and not |self|. This way if the backing project
3339 also changed places, we only do the .git/ dir to .git symlink migration
3340 here. The path updates will happen independently.
3341 """
3342 # Figure out where in .repo/projects/ it's pointing to.
3343 if not os.path.islink(os.path.join(dotgit, "refs")):
Jason Chang32b59562023-07-14 16:45:35 -07003344 raise GitError(
3345 f"{dotgit}: unsupported checkout state", project=project
3346 )
Gavin Makea2e3302023-03-11 06:46:20 +00003347 gitdir = os.path.dirname(os.path.realpath(os.path.join(dotgit, "refs")))
3348
3349 # Remove known symlink paths that exist in .repo/projects/.
3350 KNOWN_LINKS = {
3351 "config",
3352 "description",
3353 "hooks",
3354 "info",
3355 "logs",
3356 "objects",
3357 "packed-refs",
3358 "refs",
3359 "rr-cache",
3360 "shallow",
3361 "svn",
3362 }
3363 # Paths that we know will be in both, but are safe to clobber in
3364 # .repo/projects/.
3365 SAFE_TO_CLOBBER = {
3366 "COMMIT_EDITMSG",
3367 "FETCH_HEAD",
3368 "HEAD",
3369 "gc.log",
3370 "gitk.cache",
3371 "index",
3372 "ORIG_HEAD",
3373 }
3374
3375 # First see if we'd succeed before starting the migration.
3376 unknown_paths = []
3377 for name in platform_utils.listdir(dotgit):
3378 # Ignore all temporary/backup names. These are common with vim &
3379 # emacs.
3380 if name.endswith("~") or (name[0] == "#" and name[-1] == "#"):
3381 continue
3382
3383 dotgit_path = os.path.join(dotgit, name)
3384 if name in KNOWN_LINKS:
3385 if not platform_utils.islink(dotgit_path):
3386 unknown_paths.append(f"{dotgit_path}: should be a symlink")
3387 else:
3388 gitdir_path = os.path.join(gitdir, name)
3389 if name not in SAFE_TO_CLOBBER and os.path.exists(gitdir_path):
3390 unknown_paths.append(
3391 f"{dotgit_path}: unknown file; please file a bug"
3392 )
3393 if unknown_paths:
Jason Chang32b59562023-07-14 16:45:35 -07003394 raise GitError(
3395 "Aborting migration: " + "\n".join(unknown_paths),
3396 project=project,
3397 )
Gavin Makea2e3302023-03-11 06:46:20 +00003398
3399 # Now walk the paths and sync the .git/ to .repo/projects/.
3400 for name in platform_utils.listdir(dotgit):
3401 dotgit_path = os.path.join(dotgit, name)
3402
3403 # Ignore all temporary/backup names. These are common with vim &
3404 # emacs.
3405 if name.endswith("~") or (name[0] == "#" and name[-1] == "#"):
3406 platform_utils.remove(dotgit_path)
3407 elif name in KNOWN_LINKS:
3408 platform_utils.remove(dotgit_path)
3409 else:
3410 gitdir_path = os.path.join(gitdir, name)
3411 platform_utils.remove(gitdir_path, missing_ok=True)
3412 platform_utils.rename(dotgit_path, gitdir_path)
3413
3414 # Now that the dir should be empty, clear it out, and symlink it over.
3415 platform_utils.rmdir(dotgit)
3416 platform_utils.symlink(
Jason R. Coombs47944bb2023-09-29 12:42:22 -04003417 os.path.relpath(gitdir, os.path.dirname(os.path.realpath(dotgit))),
3418 dotgit,
Gavin Makea2e3302023-03-11 06:46:20 +00003419 )
3420
3421 def _get_symlink_error_message(self):
3422 if platform_utils.isWindows():
3423 return (
3424 "Unable to create symbolic link. Please re-run the command as "
3425 "Administrator, or see "
3426 "https://github.com/git-for-windows/git/wiki/Symbolic-Links "
3427 "for other options."
3428 )
3429 return "filesystem must support symlinks"
3430
3431 def _revlist(self, *args, **kw):
3432 a = []
3433 a.extend(args)
3434 a.append("--")
3435 return self.work_git.rev_list(*a, **kw)
3436
3437 @property
3438 def _allrefs(self):
3439 return self.bare_ref.all
3440
3441 def _getLogs(
3442 self, rev1, rev2, oneline=False, color=True, pretty_format=None
3443 ):
3444 """Get logs between two revisions of this project."""
3445 comp = ".."
3446 if rev1:
3447 revs = [rev1]
3448 if rev2:
3449 revs.extend([comp, rev2])
3450 cmd = ["log", "".join(revs)]
3451 out = DiffColoring(self.config)
3452 if out.is_on and color:
3453 cmd.append("--color")
3454 if pretty_format is not None:
3455 cmd.append("--pretty=format:%s" % pretty_format)
3456 if oneline:
3457 cmd.append("--oneline")
3458
3459 try:
3460 log = GitCommand(
3461 self, cmd, capture_stdout=True, capture_stderr=True
3462 )
3463 if log.Wait() == 0:
3464 return log.stdout
3465 except GitError:
3466 # worktree may not exist if groups changed for example. In that
3467 # case, try in gitdir instead.
3468 if not os.path.exists(self.worktree):
3469 return self.bare_git.log(*cmd[1:])
3470 else:
3471 raise
3472 return None
3473
3474 def getAddedAndRemovedLogs(
3475 self, toProject, oneline=False, color=True, pretty_format=None
3476 ):
3477 """Get the list of logs from this revision to given revisionId"""
3478 logs = {}
3479 selfId = self.GetRevisionId(self._allrefs)
3480 toId = toProject.GetRevisionId(toProject._allrefs)
3481
3482 logs["added"] = self._getLogs(
3483 selfId,
3484 toId,
3485 oneline=oneline,
3486 color=color,
3487 pretty_format=pretty_format,
3488 )
3489 logs["removed"] = self._getLogs(
3490 toId,
3491 selfId,
3492 oneline=oneline,
3493 color=color,
3494 pretty_format=pretty_format,
3495 )
3496 return logs
3497
Mike Frysingerd4aee652023-10-19 05:13:32 -04003498 class _GitGetByExec:
Gavin Makea2e3302023-03-11 06:46:20 +00003499 def __init__(self, project, bare, gitdir):
3500 self._project = project
3501 self._bare = bare
3502 self._gitdir = gitdir
3503
3504 # __getstate__ and __setstate__ are required for pickling because
3505 # __getattr__ exists.
3506 def __getstate__(self):
3507 return (self._project, self._bare, self._gitdir)
3508
3509 def __setstate__(self, state):
3510 self._project, self._bare, self._gitdir = state
3511
3512 def LsOthers(self):
3513 p = GitCommand(
3514 self._project,
3515 ["ls-files", "-z", "--others", "--exclude-standard"],
3516 bare=False,
3517 gitdir=self._gitdir,
3518 capture_stdout=True,
3519 capture_stderr=True,
3520 )
3521 if p.Wait() == 0:
3522 out = p.stdout
3523 if out:
3524 # Backslash is not anomalous.
3525 return out[:-1].split("\0")
3526 return []
3527
3528 def DiffZ(self, name, *args):
3529 cmd = [name]
3530 cmd.append("-z")
3531 cmd.append("--ignore-submodules")
3532 cmd.extend(args)
3533 p = GitCommand(
3534 self._project,
3535 cmd,
3536 gitdir=self._gitdir,
3537 bare=False,
3538 capture_stdout=True,
3539 capture_stderr=True,
3540 )
3541 p.Wait()
3542 r = {}
3543 out = p.stdout
3544 if out:
3545 out = iter(out[:-1].split("\0"))
3546 while out:
3547 try:
3548 info = next(out)
3549 path = next(out)
3550 except StopIteration:
3551 break
3552
Mike Frysingerd4aee652023-10-19 05:13:32 -04003553 class _Info:
Gavin Makea2e3302023-03-11 06:46:20 +00003554 def __init__(self, path, omode, nmode, oid, nid, state):
3555 self.path = path
3556 self.src_path = None
3557 self.old_mode = omode
3558 self.new_mode = nmode
3559 self.old_id = oid
3560 self.new_id = nid
3561
3562 if len(state) == 1:
3563 self.status = state
3564 self.level = None
3565 else:
3566 self.status = state[:1]
3567 self.level = state[1:]
3568 while self.level.startswith("0"):
3569 self.level = self.level[1:]
3570
3571 info = info[1:].split(" ")
3572 info = _Info(path, *info)
3573 if info.status in ("R", "C"):
3574 info.src_path = info.path
3575 info.path = next(out)
3576 r[info.path] = info
3577 return r
3578
3579 def GetDotgitPath(self, subpath=None):
3580 """Return the full path to the .git dir.
3581
3582 As a convenience, append |subpath| if provided.
3583 """
3584 if self._bare:
3585 dotgit = self._gitdir
3586 else:
3587 dotgit = os.path.join(self._project.worktree, ".git")
3588 if os.path.isfile(dotgit):
3589 # Git worktrees use a "gitdir:" syntax to point to the
3590 # scratch space.
3591 with open(dotgit) as fp:
3592 setting = fp.read()
3593 assert setting.startswith("gitdir:")
3594 gitdir = setting.split(":", 1)[1].strip()
3595 dotgit = os.path.normpath(
3596 os.path.join(self._project.worktree, gitdir)
3597 )
3598
3599 return dotgit if subpath is None else os.path.join(dotgit, subpath)
3600
3601 def GetHead(self):
3602 """Return the ref that HEAD points to."""
3603 path = self.GetDotgitPath(subpath=HEAD)
3604 try:
3605 with open(path) as fd:
3606 line = fd.readline()
Jason R. Coombsae824fb2023-10-20 23:32:40 +05453607 except OSError as e:
Gavin Makea2e3302023-03-11 06:46:20 +00003608 raise NoManifestException(path, str(e))
3609 try:
3610 line = line.decode()
3611 except AttributeError:
3612 pass
3613 if line.startswith("ref: "):
3614 return line[5:-1]
3615 return line[:-1]
3616
3617 def SetHead(self, ref, message=None):
3618 cmdv = []
3619 if message is not None:
3620 cmdv.extend(["-m", message])
3621 cmdv.append(HEAD)
3622 cmdv.append(ref)
3623 self.symbolic_ref(*cmdv)
3624
3625 def DetachHead(self, new, message=None):
3626 cmdv = ["--no-deref"]
3627 if message is not None:
3628 cmdv.extend(["-m", message])
3629 cmdv.append(HEAD)
3630 cmdv.append(new)
3631 self.update_ref(*cmdv)
3632
3633 def UpdateRef(self, name, new, old=None, message=None, detach=False):
3634 cmdv = []
3635 if message is not None:
3636 cmdv.extend(["-m", message])
3637 if detach:
3638 cmdv.append("--no-deref")
3639 cmdv.append(name)
3640 cmdv.append(new)
3641 if old is not None:
3642 cmdv.append(old)
3643 self.update_ref(*cmdv)
3644
3645 def DeleteRef(self, name, old=None):
3646 if not old:
3647 old = self.rev_parse(name)
3648 self.update_ref("-d", name, old)
3649 self._project.bare_ref.deleted(name)
3650
Jason Chang87058c62023-09-27 11:34:43 -07003651 def rev_list(self, *args, log_as_error=True, **kw):
Gavin Makea2e3302023-03-11 06:46:20 +00003652 if "format" in kw:
3653 cmdv = ["log", "--pretty=format:%s" % kw["format"]]
3654 else:
3655 cmdv = ["rev-list"]
3656 cmdv.extend(args)
3657 p = GitCommand(
3658 self._project,
3659 cmdv,
3660 bare=self._bare,
3661 gitdir=self._gitdir,
3662 capture_stdout=True,
3663 capture_stderr=True,
Jason Chang32b59562023-07-14 16:45:35 -07003664 verify_command=True,
Jason Chang87058c62023-09-27 11:34:43 -07003665 log_as_error=log_as_error,
Gavin Makea2e3302023-03-11 06:46:20 +00003666 )
Jason Chang32b59562023-07-14 16:45:35 -07003667 p.Wait()
Gavin Makea2e3302023-03-11 06:46:20 +00003668 return p.stdout.splitlines()
3669
3670 def __getattr__(self, name):
3671 """Allow arbitrary git commands using pythonic syntax.
3672
3673 This allows you to do things like:
3674 git_obj.rev_parse('HEAD')
3675
3676 Since we don't have a 'rev_parse' method defined, the __getattr__
3677 will run. We'll replace the '_' with a '-' and try to run a git
3678 command. Any other positional arguments will be passed to the git
3679 command, and the following keyword arguments are supported:
3680 config: An optional dict of git config options to be passed with
3681 '-c'.
3682
3683 Args:
3684 name: The name of the git command to call. Any '_' characters
3685 will be replaced with '-'.
3686
3687 Returns:
3688 A callable object that will try to call git with the named
3689 command.
3690 """
3691 name = name.replace("_", "-")
3692
Jason Chang87058c62023-09-27 11:34:43 -07003693 def runner(*args, log_as_error=True, **kwargs):
Gavin Makea2e3302023-03-11 06:46:20 +00003694 cmdv = []
3695 config = kwargs.pop("config", None)
3696 for k in kwargs:
3697 raise TypeError(
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04003698 f"{name}() got an unexpected keyword argument {k!r}"
Gavin Makea2e3302023-03-11 06:46:20 +00003699 )
3700 if config is not None:
3701 for k, v in config.items():
3702 cmdv.append("-c")
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -04003703 cmdv.append(f"{k}={v}")
Gavin Makea2e3302023-03-11 06:46:20 +00003704 cmdv.append(name)
3705 cmdv.extend(args)
3706 p = GitCommand(
3707 self._project,
3708 cmdv,
3709 bare=self._bare,
3710 gitdir=self._gitdir,
3711 capture_stdout=True,
3712 capture_stderr=True,
Jason Chang32b59562023-07-14 16:45:35 -07003713 verify_command=True,
Jason Chang87058c62023-09-27 11:34:43 -07003714 log_as_error=log_as_error,
Gavin Makea2e3302023-03-11 06:46:20 +00003715 )
Jason Chang32b59562023-07-14 16:45:35 -07003716 p.Wait()
Gavin Makea2e3302023-03-11 06:46:20 +00003717 r = p.stdout
3718 if r.endswith("\n") and r.index("\n") == len(r) - 1:
3719 return r[:-1]
3720 return r
3721
3722 return runner
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003723
3724
Jason Chang32b59562023-07-14 16:45:35 -07003725class LocalSyncFail(RepoError):
3726 """Default error when there is an Sync_LocalHalf error."""
3727
3728
3729class _PriorSyncFailedError(LocalSyncFail):
Gavin Makea2e3302023-03-11 06:46:20 +00003730 def __str__(self):
3731 return "prior sync failed; rebase still in progress"
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003732
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003733
Jason Chang32b59562023-07-14 16:45:35 -07003734class _DirtyError(LocalSyncFail):
Gavin Makea2e3302023-03-11 06:46:20 +00003735 def __str__(self):
3736 return "contains uncommitted changes"
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003737
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003738
Mike Frysingerd4aee652023-10-19 05:13:32 -04003739class _InfoMessage:
Gavin Makea2e3302023-03-11 06:46:20 +00003740 def __init__(self, project, text):
3741 self.project = project
3742 self.text = text
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003743
Gavin Makea2e3302023-03-11 06:46:20 +00003744 def Print(self, syncbuf):
3745 syncbuf.out.info(
3746 "%s/: %s", self.project.RelPath(local=False), self.text
3747 )
3748 syncbuf.out.nl()
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003749
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003750
Mike Frysingerd4aee652023-10-19 05:13:32 -04003751class _Failure:
Gavin Makea2e3302023-03-11 06:46:20 +00003752 def __init__(self, project, why):
3753 self.project = project
3754 self.why = why
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003755
Gavin Makea2e3302023-03-11 06:46:20 +00003756 def Print(self, syncbuf):
3757 syncbuf.out.fail(
3758 "error: %s/: %s", self.project.RelPath(local=False), str(self.why)
3759 )
3760 syncbuf.out.nl()
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003761
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003762
Mike Frysingerd4aee652023-10-19 05:13:32 -04003763class _Later:
Tomasz Wasilczyk208f3442024-01-05 12:23:10 -08003764 def __init__(self, project, action, quiet):
Gavin Makea2e3302023-03-11 06:46:20 +00003765 self.project = project
3766 self.action = action
Tomasz Wasilczyk208f3442024-01-05 12:23:10 -08003767 self.quiet = quiet
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003768
Gavin Makea2e3302023-03-11 06:46:20 +00003769 def Run(self, syncbuf):
3770 out = syncbuf.out
Tomasz Wasilczyk208f3442024-01-05 12:23:10 -08003771 if not self.quiet:
3772 out.project("project %s/", self.project.RelPath(local=False))
3773 out.nl()
Gavin Makea2e3302023-03-11 06:46:20 +00003774 try:
3775 self.action()
Tomasz Wasilczyk208f3442024-01-05 12:23:10 -08003776 if not self.quiet:
3777 out.nl()
Gavin Makea2e3302023-03-11 06:46:20 +00003778 return True
3779 except GitError:
3780 out.nl()
3781 return False
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003782
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003783
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003784class _SyncColoring(Coloring):
Gavin Makea2e3302023-03-11 06:46:20 +00003785 def __init__(self, config):
3786 super().__init__(config, "reposync")
3787 self.project = self.printer("header", attr="bold")
3788 self.info = self.printer("info")
3789 self.fail = self.printer("fail", fg="red")
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003790
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003791
Mike Frysingerd4aee652023-10-19 05:13:32 -04003792class SyncBuffer:
Gavin Makea2e3302023-03-11 06:46:20 +00003793 def __init__(self, config, detach_head=False):
3794 self._messages = []
3795 self._failures = []
3796 self._later_queue1 = []
3797 self._later_queue2 = []
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003798
Gavin Makea2e3302023-03-11 06:46:20 +00003799 self.out = _SyncColoring(config)
3800 self.out.redirect(sys.stderr)
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003801
Gavin Makea2e3302023-03-11 06:46:20 +00003802 self.detach_head = detach_head
3803 self.clean = True
3804 self.recent_clean = True
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003805
Gavin Makea2e3302023-03-11 06:46:20 +00003806 def info(self, project, fmt, *args):
3807 self._messages.append(_InfoMessage(project, fmt % args))
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003808
Gavin Makea2e3302023-03-11 06:46:20 +00003809 def fail(self, project, err=None):
3810 self._failures.append(_Failure(project, err))
David Rileye0684ad2017-04-05 00:02:59 -07003811 self._MarkUnclean()
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003812
Tomasz Wasilczyk208f3442024-01-05 12:23:10 -08003813 def later1(self, project, what, quiet):
3814 self._later_queue1.append(_Later(project, what, quiet))
Mike Frysinger70d861f2019-08-26 15:22:36 -04003815
Tomasz Wasilczyk208f3442024-01-05 12:23:10 -08003816 def later2(self, project, what, quiet):
3817 self._later_queue2.append(_Later(project, what, quiet))
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003818
Gavin Makea2e3302023-03-11 06:46:20 +00003819 def Finish(self):
3820 self._PrintMessages()
3821 self._RunLater()
3822 self._PrintMessages()
3823 return self.clean
3824
3825 def Recently(self):
3826 recent_clean = self.recent_clean
3827 self.recent_clean = True
3828 return recent_clean
3829
3830 def _MarkUnclean(self):
3831 self.clean = False
3832 self.recent_clean = False
3833
3834 def _RunLater(self):
3835 for q in ["_later_queue1", "_later_queue2"]:
3836 if not self._RunQueue(q):
3837 return
3838
3839 def _RunQueue(self, queue):
3840 for m in getattr(self, queue):
3841 if not m.Run(self):
3842 self._MarkUnclean()
3843 return False
3844 setattr(self, queue, [])
3845 return True
3846
3847 def _PrintMessages(self):
3848 if self._messages or self._failures:
3849 if os.isatty(2):
3850 self.out.write(progress.CSI_ERASE_LINE)
3851 self.out.write("\r")
3852
3853 for m in self._messages:
3854 m.Print(self)
3855 for m in self._failures:
3856 m.Print(self)
3857
3858 self._messages = []
3859 self._failures = []
Shawn O. Pearce350cde42009-04-16 11:21:18 -07003860
3861
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003862class MetaProject(Project):
Gavin Makea2e3302023-03-11 06:46:20 +00003863 """A special project housed under .repo."""
Mark E. Hamilton30b0f4e2016-02-10 10:44:30 -07003864
Gavin Makea2e3302023-03-11 06:46:20 +00003865 def __init__(self, manifest, name, gitdir, worktree):
3866 Project.__init__(
3867 self,
3868 manifest=manifest,
3869 name=name,
3870 gitdir=gitdir,
3871 objdir=gitdir,
3872 worktree=worktree,
3873 remote=RemoteSpec("origin"),
3874 relpath=".repo/%s" % name,
3875 revisionExpr="refs/heads/master",
3876 revisionId=None,
3877 groups=None,
3878 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003879
Gavin Makea2e3302023-03-11 06:46:20 +00003880 def PreSync(self):
3881 if self.Exists:
3882 cb = self.CurrentBranch
3883 if cb:
3884 base = self.GetBranch(cb).merge
3885 if base:
3886 self.revisionExpr = base
3887 self.revisionId = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003888
Gavin Makea2e3302023-03-11 06:46:20 +00003889 @property
3890 def HasChanges(self):
3891 """Has the remote received new commits not yet checked out?"""
3892 if not self.remote or not self.revisionExpr:
3893 return False
Shawn O. Pearce336f7bd2009-04-18 10:39:28 -07003894
Gavin Makea2e3302023-03-11 06:46:20 +00003895 all_refs = self.bare_ref.all
3896 revid = self.GetRevisionId(all_refs)
3897 head = self.work_git.GetHead()
3898 if head.startswith(R_HEADS):
3899 try:
3900 head = all_refs[head]
3901 except KeyError:
3902 head = None
Shawn O. Pearce336f7bd2009-04-18 10:39:28 -07003903
Gavin Makea2e3302023-03-11 06:46:20 +00003904 if revid == head:
3905 return False
3906 elif self._revlist(not_rev(HEAD), revid):
3907 return True
3908 return False
LaMont Jones9b72cf22022-03-29 21:54:22 +00003909
3910
3911class RepoProject(MetaProject):
Gavin Makea2e3302023-03-11 06:46:20 +00003912 """The MetaProject for repo itself."""
LaMont Jones9b72cf22022-03-29 21:54:22 +00003913
Gavin Makea2e3302023-03-11 06:46:20 +00003914 @property
3915 def LastFetch(self):
3916 try:
3917 fh = os.path.join(self.gitdir, "FETCH_HEAD")
3918 return os.path.getmtime(fh)
3919 except OSError:
3920 return 0
LaMont Jones9b72cf22022-03-29 21:54:22 +00003921
Sergiy Belozorov78e82ec2023-01-05 18:57:31 +01003922
LaMont Jones9b72cf22022-03-29 21:54:22 +00003923class ManifestProject(MetaProject):
Gavin Makea2e3302023-03-11 06:46:20 +00003924 """The MetaProject for manifests."""
LaMont Jones9b72cf22022-03-29 21:54:22 +00003925
Tomasz Wasilczyk4c809212023-12-08 13:42:17 -08003926 def MetaBranchSwitch(self, submodules=False, verbose=False):
Gavin Makea2e3302023-03-11 06:46:20 +00003927 """Prepare for manifest branch switch."""
LaMont Jones9b72cf22022-03-29 21:54:22 +00003928
Gavin Makea2e3302023-03-11 06:46:20 +00003929 # detach and delete manifest branch, allowing a new
3930 # branch to take over
3931 syncbuf = SyncBuffer(self.config, detach_head=True)
Tomasz Wasilczyk4c809212023-12-08 13:42:17 -08003932 self.Sync_LocalHalf(syncbuf, submodules=submodules, verbose=verbose)
Gavin Makea2e3302023-03-11 06:46:20 +00003933 syncbuf.Finish()
LaMont Jones9b72cf22022-03-29 21:54:22 +00003934
Gavin Makea2e3302023-03-11 06:46:20 +00003935 return (
3936 GitCommand(
3937 self,
3938 ["update-ref", "-d", "refs/heads/default"],
3939 capture_stdout=True,
3940 capture_stderr=True,
3941 ).Wait()
3942 == 0
3943 )
LaMont Jones9b03f152022-03-29 23:01:18 +00003944
Gavin Makea2e3302023-03-11 06:46:20 +00003945 @property
3946 def standalone_manifest_url(self):
3947 """The URL of the standalone manifest, or None."""
3948 return self.config.GetString("manifest.standalone")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003949
Gavin Makea2e3302023-03-11 06:46:20 +00003950 @property
3951 def manifest_groups(self):
3952 """The manifest groups string."""
3953 return self.config.GetString("manifest.groups")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003954
Gavin Makea2e3302023-03-11 06:46:20 +00003955 @property
3956 def reference(self):
3957 """The --reference for this manifest."""
3958 return self.config.GetString("repo.reference")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003959
Gavin Makea2e3302023-03-11 06:46:20 +00003960 @property
3961 def dissociate(self):
3962 """Whether to dissociate."""
3963 return self.config.GetBoolean("repo.dissociate")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003964
Gavin Makea2e3302023-03-11 06:46:20 +00003965 @property
3966 def archive(self):
3967 """Whether we use archive."""
3968 return self.config.GetBoolean("repo.archive")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003969
Gavin Makea2e3302023-03-11 06:46:20 +00003970 @property
3971 def mirror(self):
3972 """Whether we use mirror."""
3973 return self.config.GetBoolean("repo.mirror")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003974
Gavin Makea2e3302023-03-11 06:46:20 +00003975 @property
3976 def use_worktree(self):
3977 """Whether we use worktree."""
3978 return self.config.GetBoolean("repo.worktree")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003979
Gavin Makea2e3302023-03-11 06:46:20 +00003980 @property
3981 def clone_bundle(self):
3982 """Whether we use clone_bundle."""
3983 return self.config.GetBoolean("repo.clonebundle")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003984
Gavin Makea2e3302023-03-11 06:46:20 +00003985 @property
3986 def submodules(self):
3987 """Whether we use submodules."""
3988 return self.config.GetBoolean("repo.submodules")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003989
Gavin Makea2e3302023-03-11 06:46:20 +00003990 @property
3991 def git_lfs(self):
3992 """Whether we use git_lfs."""
3993 return self.config.GetBoolean("repo.git-lfs")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003994
Gavin Makea2e3302023-03-11 06:46:20 +00003995 @property
3996 def use_superproject(self):
3997 """Whether we use superproject."""
3998 return self.config.GetBoolean("repo.superproject")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00003999
Gavin Makea2e3302023-03-11 06:46:20 +00004000 @property
4001 def partial_clone(self):
4002 """Whether this is a partial clone."""
4003 return self.config.GetBoolean("repo.partialclone")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00004004
Gavin Makea2e3302023-03-11 06:46:20 +00004005 @property
4006 def depth(self):
4007 """Partial clone depth."""
Roberto Vladimir Prado Carranza3d58d212023-09-13 10:27:26 +02004008 return self.config.GetInt("repo.depth")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00004009
Gavin Makea2e3302023-03-11 06:46:20 +00004010 @property
4011 def clone_filter(self):
4012 """The clone filter."""
4013 return self.config.GetString("repo.clonefilter")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00004014
Gavin Makea2e3302023-03-11 06:46:20 +00004015 @property
4016 def partial_clone_exclude(self):
4017 """Partial clone exclude string"""
4018 return self.config.GetString("repo.partialcloneexclude")
LaMont Jones4ada0432022-04-14 15:10:43 +00004019
Gavin Makea2e3302023-03-11 06:46:20 +00004020 @property
Jason Chang17833322023-05-23 13:06:55 -07004021 def clone_filter_for_depth(self):
4022 """Replace shallow clone with partial clone."""
4023 return self.config.GetString("repo.clonefilterfordepth")
4024
4025 @property
Gavin Makea2e3302023-03-11 06:46:20 +00004026 def manifest_platform(self):
4027 """The --platform argument from `repo init`."""
4028 return self.config.GetString("manifest.platform")
LaMont Jonesd82be3e2022-04-05 19:30:46 +00004029
Gavin Makea2e3302023-03-11 06:46:20 +00004030 @property
4031 def _platform_name(self):
4032 """Return the name of the platform."""
4033 return platform.system().lower()
LaMont Jones9b03f152022-03-29 23:01:18 +00004034
Gavin Makea2e3302023-03-11 06:46:20 +00004035 def SyncWithPossibleInit(
4036 self,
4037 submanifest,
4038 verbose=False,
4039 current_branch_only=False,
4040 tags="",
4041 git_event_log=None,
4042 ):
4043 """Sync a manifestProject, possibly for the first time.
LaMont Jonesbdcba7d2022-04-11 22:50:11 +00004044
Gavin Makea2e3302023-03-11 06:46:20 +00004045 Call Sync() with arguments from the most recent `repo init`. If this is
4046 a new sub manifest, then inherit options from the parent's
4047 manifestProject.
LaMont Jonesbdcba7d2022-04-11 22:50:11 +00004048
Gavin Makea2e3302023-03-11 06:46:20 +00004049 This is used by subcmds.Sync() to do an initial download of new sub
4050 manifests.
LaMont Jonesbdcba7d2022-04-11 22:50:11 +00004051
Gavin Makea2e3302023-03-11 06:46:20 +00004052 Args:
4053 submanifest: an XmlSubmanifest, the submanifest to re-sync.
4054 verbose: a boolean, whether to show all output, rather than only
4055 errors.
4056 current_branch_only: a boolean, whether to only fetch the current
4057 manifest branch from the server.
4058 tags: a boolean, whether to fetch tags.
4059 git_event_log: an EventLog, for git tracing.
4060 """
4061 # TODO(lamontjones): when refactoring sync (and init?) consider how to
4062 # better get the init options that we should use for new submanifests
4063 # that are added when syncing an existing workspace.
4064 git_event_log = git_event_log or EventLog()
LaMont Jonesb90a4222022-04-14 15:00:09 +00004065 spec = submanifest.ToSubmanifestSpec()
Gavin Makea2e3302023-03-11 06:46:20 +00004066 # Use the init options from the existing manifestProject, or the parent
4067 # if it doesn't exist.
4068 #
4069 # Today, we only support changing manifest_groups on the sub-manifest,
4070 # with no supported-for-the-user way to change the other arguments from
4071 # those specified by the outermost manifest.
4072 #
4073 # TODO(lamontjones): determine which of these should come from the
4074 # outermost manifest and which should come from the parent manifest.
4075 mp = self if self.Exists else submanifest.parent.manifestProject
4076 return self.Sync(
LaMont Jones55ee3042022-04-06 17:10:21 +00004077 manifest_url=spec.manifestUrl,
4078 manifest_branch=spec.revision,
Gavin Makea2e3302023-03-11 06:46:20 +00004079 standalone_manifest=mp.standalone_manifest_url,
4080 groups=mp.manifest_groups,
4081 platform=mp.manifest_platform,
4082 mirror=mp.mirror,
4083 dissociate=mp.dissociate,
4084 reference=mp.reference,
4085 worktree=mp.use_worktree,
4086 submodules=mp.submodules,
4087 archive=mp.archive,
4088 partial_clone=mp.partial_clone,
4089 clone_filter=mp.clone_filter,
4090 partial_clone_exclude=mp.partial_clone_exclude,
4091 clone_bundle=mp.clone_bundle,
4092 git_lfs=mp.git_lfs,
4093 use_superproject=mp.use_superproject,
LaMont Jones55ee3042022-04-06 17:10:21 +00004094 verbose=verbose,
4095 current_branch_only=current_branch_only,
4096 tags=tags,
Gavin Makea2e3302023-03-11 06:46:20 +00004097 depth=mp.depth,
LaMont Jones55ee3042022-04-06 17:10:21 +00004098 git_event_log=git_event_log,
4099 manifest_name=spec.manifestName,
Gavin Makea2e3302023-03-11 06:46:20 +00004100 this_manifest_only=True,
LaMont Jones55ee3042022-04-06 17:10:21 +00004101 outer_manifest=False,
Jason Chang17833322023-05-23 13:06:55 -07004102 clone_filter_for_depth=mp.clone_filter_for_depth,
LaMont Jones55ee3042022-04-06 17:10:21 +00004103 )
LaMont Jones409407a2022-04-05 21:21:56 +00004104
Gavin Makea2e3302023-03-11 06:46:20 +00004105 def Sync(
4106 self,
4107 _kwargs_only=(),
4108 manifest_url="",
4109 manifest_branch=None,
4110 standalone_manifest=False,
4111 groups="",
4112 mirror=False,
4113 reference="",
4114 dissociate=False,
4115 worktree=False,
4116 submodules=False,
4117 archive=False,
4118 partial_clone=None,
4119 depth=None,
4120 clone_filter="blob:none",
4121 partial_clone_exclude=None,
4122 clone_bundle=None,
4123 git_lfs=None,
4124 use_superproject=None,
4125 verbose=False,
4126 current_branch_only=False,
4127 git_event_log=None,
4128 platform="",
4129 manifest_name="default.xml",
4130 tags="",
4131 this_manifest_only=False,
4132 outer_manifest=True,
Jason Chang17833322023-05-23 13:06:55 -07004133 clone_filter_for_depth=None,
Gavin Makea2e3302023-03-11 06:46:20 +00004134 ):
4135 """Sync the manifest and all submanifests.
LaMont Jones409407a2022-04-05 21:21:56 +00004136
Gavin Makea2e3302023-03-11 06:46:20 +00004137 Args:
4138 manifest_url: a string, the URL of the manifest project.
4139 manifest_branch: a string, the manifest branch to use.
4140 standalone_manifest: a boolean, whether to store the manifest as a
4141 static file.
4142 groups: a string, restricts the checkout to projects with the
4143 specified groups.
4144 mirror: a boolean, whether to create a mirror of the remote
4145 repository.
4146 reference: a string, location of a repo instance to use as a
4147 reference.
4148 dissociate: a boolean, whether to dissociate from reference mirrors
4149 after clone.
4150 worktree: a boolean, whether to use git-worktree to manage projects.
4151 submodules: a boolean, whether sync submodules associated with the
4152 manifest project.
4153 archive: a boolean, whether to checkout each project as an archive.
4154 See git-archive.
4155 partial_clone: a boolean, whether to perform a partial clone.
4156 depth: an int, how deep of a shallow clone to create.
4157 clone_filter: a string, filter to use with partial_clone.
4158 partial_clone_exclude : a string, comma-delimeted list of project
4159 names to exclude from partial clone.
4160 clone_bundle: a boolean, whether to enable /clone.bundle on
4161 HTTP/HTTPS.
4162 git_lfs: a boolean, whether to enable git LFS support.
4163 use_superproject: a boolean, whether to use the manifest
4164 superproject to sync projects.
4165 verbose: a boolean, whether to show all output, rather than only
4166 errors.
4167 current_branch_only: a boolean, whether to only fetch the current
4168 manifest branch from the server.
4169 platform: a string, restrict the checkout to projects with the
4170 specified platform group.
4171 git_event_log: an EventLog, for git tracing.
4172 tags: a boolean, whether to fetch tags.
4173 manifest_name: a string, the name of the manifest file to use.
4174 this_manifest_only: a boolean, whether to only operate on the
4175 current sub manifest.
4176 outer_manifest: a boolean, whether to start at the outermost
4177 manifest.
Jason Chang17833322023-05-23 13:06:55 -07004178 clone_filter_for_depth: a string, when specified replaces shallow
4179 clones with partial.
LaMont Jones9b03f152022-03-29 23:01:18 +00004180
Gavin Makea2e3302023-03-11 06:46:20 +00004181 Returns:
4182 a boolean, whether the sync was successful.
4183 """
4184 assert _kwargs_only == (), "Sync only accepts keyword arguments."
LaMont Jones9b03f152022-03-29 23:01:18 +00004185
Gavin Makea2e3302023-03-11 06:46:20 +00004186 groups = groups or self.manifest.GetDefaultGroupsStr(
4187 with_platform=False
4188 )
4189 platform = platform or "auto"
4190 git_event_log = git_event_log or EventLog()
4191 if outer_manifest and self.manifest.is_submanifest:
4192 # In a multi-manifest checkout, use the outer manifest unless we are
4193 # told not to.
4194 return self.client.outer_manifest.manifestProject.Sync(
4195 manifest_url=manifest_url,
4196 manifest_branch=manifest_branch,
4197 standalone_manifest=standalone_manifest,
4198 groups=groups,
4199 platform=platform,
4200 mirror=mirror,
4201 dissociate=dissociate,
4202 reference=reference,
4203 worktree=worktree,
4204 submodules=submodules,
4205 archive=archive,
4206 partial_clone=partial_clone,
4207 clone_filter=clone_filter,
4208 partial_clone_exclude=partial_clone_exclude,
4209 clone_bundle=clone_bundle,
4210 git_lfs=git_lfs,
4211 use_superproject=use_superproject,
4212 verbose=verbose,
4213 current_branch_only=current_branch_only,
4214 tags=tags,
4215 depth=depth,
4216 git_event_log=git_event_log,
4217 manifest_name=manifest_name,
4218 this_manifest_only=this_manifest_only,
4219 outer_manifest=False,
4220 )
LaMont Jones9b03f152022-03-29 23:01:18 +00004221
Gavin Makea2e3302023-03-11 06:46:20 +00004222 # If repo has already been initialized, we take -u with the absence of
4223 # --standalone-manifest to mean "transition to a standard repo set up",
4224 # which necessitates starting fresh.
4225 # If --standalone-manifest is set, we always tear everything down and
4226 # start anew.
4227 if self.Exists:
4228 was_standalone_manifest = self.config.GetString(
4229 "manifest.standalone"
4230 )
4231 if was_standalone_manifest and not manifest_url:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004232 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +00004233 "fatal: repo was initialized with a standlone manifest, "
4234 "cannot be re-initialized without --manifest-url/-u"
4235 )
4236 return False
4237
4238 if standalone_manifest or (
4239 was_standalone_manifest and manifest_url
4240 ):
4241 self.config.ClearCache()
4242 if self.gitdir and os.path.exists(self.gitdir):
4243 platform_utils.rmtree(self.gitdir)
4244 if self.worktree and os.path.exists(self.worktree):
4245 platform_utils.rmtree(self.worktree)
4246
4247 is_new = not self.Exists
4248 if is_new:
4249 if not manifest_url:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004250 logger.error("fatal: manifest url is required.")
Gavin Makea2e3302023-03-11 06:46:20 +00004251 return False
4252
4253 if verbose:
4254 print(
4255 "Downloading manifest from %s"
4256 % (GitConfig.ForUser().UrlInsteadOf(manifest_url),),
4257 file=sys.stderr,
4258 )
4259
4260 # The manifest project object doesn't keep track of the path on the
4261 # server where this git is located, so let's save that here.
4262 mirrored_manifest_git = None
4263 if reference:
4264 manifest_git_path = urllib.parse.urlparse(manifest_url).path[1:]
4265 mirrored_manifest_git = os.path.join(
4266 reference, manifest_git_path
4267 )
4268 if not mirrored_manifest_git.endswith(".git"):
4269 mirrored_manifest_git += ".git"
4270 if not os.path.exists(mirrored_manifest_git):
4271 mirrored_manifest_git = os.path.join(
4272 reference, ".repo/manifests.git"
4273 )
4274
4275 self._InitGitDir(mirror_git=mirrored_manifest_git)
4276
4277 # If standalone_manifest is set, mark the project as "standalone" --
4278 # we'll still do much of the manifests.git set up, but will avoid actual
4279 # syncs to a remote.
4280 if standalone_manifest:
4281 self.config.SetString("manifest.standalone", manifest_url)
4282 elif not manifest_url and not manifest_branch:
4283 # If -u is set and --standalone-manifest is not, then we're not in
4284 # standalone mode. Otherwise, use config to infer what we were in
4285 # the last init.
4286 standalone_manifest = bool(
4287 self.config.GetString("manifest.standalone")
4288 )
4289 if not standalone_manifest:
4290 self.config.SetString("manifest.standalone", None)
4291
4292 self._ConfigureDepth(depth)
4293
4294 # Set the remote URL before the remote branch as we might need it below.
4295 if manifest_url:
4296 r = self.GetRemote()
4297 r.url = manifest_url
4298 r.ResetFetch()
4299 r.Save()
4300
4301 if not standalone_manifest:
4302 if manifest_branch:
4303 if manifest_branch == "HEAD":
4304 manifest_branch = self.ResolveRemoteHead()
4305 if manifest_branch is None:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004306 logger.error("fatal: unable to resolve HEAD")
Gavin Makea2e3302023-03-11 06:46:20 +00004307 return False
4308 self.revisionExpr = manifest_branch
4309 else:
4310 if is_new:
4311 default_branch = self.ResolveRemoteHead()
4312 if default_branch is None:
4313 # If the remote doesn't have HEAD configured, default to
4314 # master.
4315 default_branch = "refs/heads/master"
4316 self.revisionExpr = default_branch
4317 else:
4318 self.PreSync()
4319
4320 groups = re.split(r"[,\s]+", groups or "")
4321 all_platforms = ["linux", "darwin", "windows"]
4322 platformize = lambda x: "platform-" + x
4323 if platform == "auto":
4324 if not mirror and not self.mirror:
4325 groups.append(platformize(self._platform_name))
4326 elif platform == "all":
4327 groups.extend(map(platformize, all_platforms))
4328 elif platform in all_platforms:
4329 groups.append(platformize(platform))
4330 elif platform != "none":
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004331 logger.error("fatal: invalid platform flag", file=sys.stderr)
Gavin Makea2e3302023-03-11 06:46:20 +00004332 return False
4333 self.config.SetString("manifest.platform", platform)
4334
4335 groups = [x for x in groups if x]
4336 groupstr = ",".join(groups)
4337 if (
4338 platform == "auto"
4339 and groupstr == self.manifest.GetDefaultGroupsStr()
4340 ):
4341 groupstr = None
4342 self.config.SetString("manifest.groups", groupstr)
4343
4344 if reference:
4345 self.config.SetString("repo.reference", reference)
4346
4347 if dissociate:
4348 self.config.SetBoolean("repo.dissociate", dissociate)
4349
4350 if worktree:
4351 if mirror:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004352 logger.error("fatal: --mirror and --worktree are incompatible")
Gavin Makea2e3302023-03-11 06:46:20 +00004353 return False
4354 if submodules:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004355 logger.error(
4356 "fatal: --submodules and --worktree are incompatible"
Gavin Makea2e3302023-03-11 06:46:20 +00004357 )
4358 return False
4359 self.config.SetBoolean("repo.worktree", worktree)
4360 if is_new:
4361 self.use_git_worktrees = True
Aravind Vasudevan8bc50002023-10-13 19:22:47 +00004362 logger.warning("warning: --worktree is experimental!")
Gavin Makea2e3302023-03-11 06:46:20 +00004363
4364 if archive:
4365 if is_new:
4366 self.config.SetBoolean("repo.archive", archive)
4367 else:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004368 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +00004369 "fatal: --archive is only supported when initializing a "
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004370 "new workspace."
Gavin Makea2e3302023-03-11 06:46:20 +00004371 )
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004372 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +00004373 "Either delete the .repo folder in this workspace, or "
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004374 "initialize in another location."
Gavin Makea2e3302023-03-11 06:46:20 +00004375 )
4376 return False
4377
4378 if mirror:
4379 if is_new:
4380 self.config.SetBoolean("repo.mirror", mirror)
4381 else:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004382 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +00004383 "fatal: --mirror is only supported when initializing a new "
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004384 "workspace."
Gavin Makea2e3302023-03-11 06:46:20 +00004385 )
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004386 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +00004387 "Either delete the .repo folder in this workspace, or "
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004388 "initialize in another location."
Gavin Makea2e3302023-03-11 06:46:20 +00004389 )
4390 return False
4391
4392 if partial_clone is not None:
4393 if mirror:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004394 logger.error(
Gavin Makea2e3302023-03-11 06:46:20 +00004395 "fatal: --mirror and --partial-clone are mutually "
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004396 "exclusive"
Gavin Makea2e3302023-03-11 06:46:20 +00004397 )
4398 return False
4399 self.config.SetBoolean("repo.partialclone", partial_clone)
4400 if clone_filter:
4401 self.config.SetString("repo.clonefilter", clone_filter)
4402 elif self.partial_clone:
4403 clone_filter = self.clone_filter
4404 else:
4405 clone_filter = None
4406
4407 if partial_clone_exclude is not None:
4408 self.config.SetString(
4409 "repo.partialcloneexclude", partial_clone_exclude
4410 )
4411
4412 if clone_bundle is None:
4413 clone_bundle = False if partial_clone else True
4414 else:
4415 self.config.SetBoolean("repo.clonebundle", clone_bundle)
4416
4417 if submodules:
4418 self.config.SetBoolean("repo.submodules", submodules)
4419
4420 if git_lfs is not None:
4421 if git_lfs:
4422 git_require((2, 17, 0), fail=True, msg="Git LFS support")
4423
4424 self.config.SetBoolean("repo.git-lfs", git_lfs)
4425 if not is_new:
Aravind Vasudevan8bc50002023-10-13 19:22:47 +00004426 logger.warning(
Gavin Makea2e3302023-03-11 06:46:20 +00004427 "warning: Changing --git-lfs settings will only affect new "
4428 "project checkouts.\n"
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004429 " Existing projects will require manual updates.\n"
Gavin Makea2e3302023-03-11 06:46:20 +00004430 )
4431
Jason Chang17833322023-05-23 13:06:55 -07004432 if clone_filter_for_depth is not None:
4433 self.ConfigureCloneFilterForDepth(clone_filter_for_depth)
4434
Gavin Makea2e3302023-03-11 06:46:20 +00004435 if use_superproject is not None:
4436 self.config.SetBoolean("repo.superproject", use_superproject)
4437
4438 if not standalone_manifest:
4439 success = self.Sync_NetworkHalf(
4440 is_new=is_new,
4441 quiet=not verbose,
4442 verbose=verbose,
4443 clone_bundle=clone_bundle,
4444 current_branch_only=current_branch_only,
4445 tags=tags,
4446 submodules=submodules,
4447 clone_filter=clone_filter,
4448 partial_clone_exclude=self.manifest.PartialCloneExclude,
Jason Chang17833322023-05-23 13:06:55 -07004449 clone_filter_for_depth=self.manifest.CloneFilterForDepth,
Gavin Makea2e3302023-03-11 06:46:20 +00004450 ).success
4451 if not success:
4452 r = self.GetRemote()
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004453 logger.error("fatal: cannot obtain manifest %s", r.url)
Gavin Makea2e3302023-03-11 06:46:20 +00004454
4455 # Better delete the manifest git dir if we created it; otherwise
4456 # next time (when user fixes problems) we won't go through the
4457 # "is_new" logic.
4458 if is_new:
4459 platform_utils.rmtree(self.gitdir)
4460 return False
4461
4462 if manifest_branch:
Tomasz Wasilczyk4c809212023-12-08 13:42:17 -08004463 self.MetaBranchSwitch(submodules=submodules, verbose=verbose)
Gavin Makea2e3302023-03-11 06:46:20 +00004464
4465 syncbuf = SyncBuffer(self.config)
Tomasz Wasilczyk4c809212023-12-08 13:42:17 -08004466 self.Sync_LocalHalf(syncbuf, submodules=submodules, verbose=verbose)
Gavin Makea2e3302023-03-11 06:46:20 +00004467 syncbuf.Finish()
4468
4469 if is_new or self.CurrentBranch is None:
Jason Chang1a3612f2023-08-08 14:12:53 -07004470 try:
4471 self.StartBranch("default")
4472 except GitError as e:
4473 msg = str(e)
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004474 logger.error(
4475 "fatal: cannot create default in manifest %s", msg
Gavin Makea2e3302023-03-11 06:46:20 +00004476 )
4477 return False
4478
4479 if not manifest_name:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004480 logger.error("fatal: manifest name (-m) is required.")
Gavin Makea2e3302023-03-11 06:46:20 +00004481 return False
4482
4483 elif is_new:
4484 # This is a new standalone manifest.
4485 manifest_name = "default.xml"
4486 manifest_data = fetch.fetch_file(manifest_url, verbose=verbose)
4487 dest = os.path.join(self.worktree, manifest_name)
4488 os.makedirs(os.path.dirname(dest), exist_ok=True)
4489 with open(dest, "wb") as f:
4490 f.write(manifest_data)
4491
4492 try:
4493 self.manifest.Link(manifest_name)
4494 except ManifestParseError as e:
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004495 logger.error("fatal: manifest '%s' not available", manifest_name)
4496 logger.error("fatal: %s", e)
Gavin Makea2e3302023-03-11 06:46:20 +00004497 return False
4498
4499 if not this_manifest_only:
4500 for submanifest in self.manifest.submanifests.values():
4501 spec = submanifest.ToSubmanifestSpec()
4502 submanifest.repo_client.manifestProject.Sync(
4503 manifest_url=spec.manifestUrl,
4504 manifest_branch=spec.revision,
4505 standalone_manifest=standalone_manifest,
4506 groups=self.manifest_groups,
4507 platform=platform,
4508 mirror=mirror,
4509 dissociate=dissociate,
4510 reference=reference,
4511 worktree=worktree,
4512 submodules=submodules,
4513 archive=archive,
4514 partial_clone=partial_clone,
4515 clone_filter=clone_filter,
4516 partial_clone_exclude=partial_clone_exclude,
4517 clone_bundle=clone_bundle,
4518 git_lfs=git_lfs,
4519 use_superproject=use_superproject,
4520 verbose=verbose,
4521 current_branch_only=current_branch_only,
4522 tags=tags,
4523 depth=depth,
4524 git_event_log=git_event_log,
4525 manifest_name=spec.manifestName,
4526 this_manifest_only=False,
4527 outer_manifest=False,
4528 )
4529
4530 # Lastly, if the manifest has a <superproject> then have the
4531 # superproject sync it (if it will be used).
4532 if git_superproject.UseSuperproject(use_superproject, self.manifest):
4533 sync_result = self.manifest.superproject.Sync(git_event_log)
4534 if not sync_result.success:
4535 submanifest = ""
4536 if self.manifest.path_prefix:
4537 submanifest = f"for {self.manifest.path_prefix} "
Aravind Vasudevan8bc50002023-10-13 19:22:47 +00004538 logger.warning(
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004539 "warning: git update of superproject %s failed, "
Gavin Makea2e3302023-03-11 06:46:20 +00004540 "repo sync will not use superproject to fetch source; "
4541 "while this error is not fatal, and you can continue to "
4542 "run repo sync, please run repo init with the "
4543 "--no-use-superproject option to stop seeing this warning",
Aravind Vasudevan7a1f1f72023-09-14 08:17:20 +00004544 submanifest,
Gavin Makea2e3302023-03-11 06:46:20 +00004545 )
4546 if sync_result.fatal and use_superproject is not None:
4547 return False
4548
4549 return True
4550
Jason Chang17833322023-05-23 13:06:55 -07004551 def ConfigureCloneFilterForDepth(self, clone_filter_for_depth):
4552 """Configure clone filter to replace shallow clones.
4553
4554 Args:
4555 clone_filter_for_depth: a string or None, e.g. 'blob:none' will
4556 disable shallow clones and replace with partial clone. None will
4557 enable shallow clones.
4558 """
4559 self.config.SetString(
4560 "repo.clonefilterfordepth", clone_filter_for_depth
4561 )
4562
Gavin Makea2e3302023-03-11 06:46:20 +00004563 def _ConfigureDepth(self, depth):
4564 """Configure the depth we'll sync down.
4565
4566 Args:
4567 depth: an int, how deep of a partial clone to create.
4568 """
4569 # Opt.depth will be non-None if user actually passed --depth to repo
4570 # init.
4571 if depth is not None:
4572 if depth > 0:
4573 # Positive values will set the depth.
4574 depth = str(depth)
4575 else:
4576 # Negative numbers will clear the depth; passing None to
4577 # SetString will do that.
4578 depth = None
4579
4580 # We store the depth in the main manifest project.
4581 self.config.SetString("repo.depth", depth)