blob: d944b40977448c52369208e417878da4781df236 [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
Raman Tenneti993af5e2021-05-12 12:00:31 -070015import collections
Colin Cross23acdd32012-04-21 00:33:54 -070016import itertools
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070017import os
Raman Tenneti080877e2021-03-09 15:19:06 -080018import platform
Conley Owensdb728cd2011-09-26 16:34:01 -070019import re
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070020import sys
Mike Frysingeracf63b22019-06-13 02:24:21 -040021import urllib.parse
Mike Frysinger64477332023-08-21 21:20:32 -040022import xml.dom.minidom
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070023
Mike Frysinger64477332023-08-21 21:20:32 -040024from error import ManifestInvalidPathError
25from error import ManifestInvalidRevisionError
26from error import ManifestParseError
Daniel Kutik035f22a2022-12-13 12:34:23 +010027from git_config import GitConfig
Mike Frysinger64477332023-08-21 21:20:32 -040028from git_refs import HEAD
29from git_refs import R_HEADS
LaMont Jonesd56e2eb2022-04-07 18:14:46 +000030from git_superproject import Superproject
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070031import platform_utils
Mike Frysinger64477332023-08-21 21:20:32 -040032from project import Annotation
33from project import ManifestProject
34from project import Project
35from project import RemoteSpec
36from project import RepoProject
Raman Tenneti993af5e2021-05-12 12:00:31 -070037from wrapper import Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070038
Mike Frysinger64477332023-08-21 21:20:32 -040039
Gavin Makea2e3302023-03-11 06:46:20 +000040MANIFEST_FILE_NAME = "manifest.xml"
41LOCAL_MANIFEST_NAME = "local_manifest.xml"
42LOCAL_MANIFESTS_DIR_NAME = "local_manifests"
43SUBMANIFEST_DIR = "submanifests"
LaMont Jonescc879a92021-11-18 22:40:18 +000044# Limit submanifests to an arbitrary depth for loop detection.
45MAX_SUBMANIFEST_DEPTH = 8
LaMont Jonesb308db12022-02-25 17:05:21 +000046# Add all projects from sub manifest into a group.
Gavin Makea2e3302023-03-11 06:46:20 +000047SUBMANIFEST_GROUP_PREFIX = "submanifest:"
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070048
Raman Tenneti78f4dd32021-06-07 13:27:37 -070049# Add all projects from local manifest into a group.
Gavin Makea2e3302023-03-11 06:46:20 +000050LOCAL_MANIFEST_GROUP_PREFIX = "local:"
Raman Tenneti78f4dd32021-06-07 13:27:37 -070051
Raman Tenneti993af5e2021-05-12 12:00:31 -070052# ContactInfo has the self-registered bug url, supplied by the manifest authors.
Gavin Makea2e3302023-03-11 06:46:20 +000053ContactInfo = collections.namedtuple("ContactInfo", "bugurl")
Raman Tenneti993af5e2021-05-12 12:00:31 -070054
Anthony Kingcb07ba72015-03-28 23:26:04 +000055# urljoin gets confused if the scheme is not known.
Gavin Makea2e3302023-03-11 06:46:20 +000056urllib.parse.uses_relative.extend(
57 ["ssh", "git", "persistent-https", "sso", "rpc"]
58)
59urllib.parse.uses_netloc.extend(
60 ["ssh", "git", "persistent-https", "sso", "rpc"]
61)
Conley Owensdb728cd2011-09-26 16:34:01 -070062
David Pursehouse819827a2020-02-12 15:20:19 +090063
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050064def XmlBool(node, attr, default=None):
Gavin Makea2e3302023-03-11 06:46:20 +000065 """Determine boolean value of |node|'s |attr|.
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050066
Gavin Makea2e3302023-03-11 06:46:20 +000067 Invalid values will issue a non-fatal warning.
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050068
Gavin Makea2e3302023-03-11 06:46:20 +000069 Args:
70 node: XML node whose attributes we access.
71 attr: The attribute to access.
72 default: If the attribute is not set (value is empty), then use this.
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050073
Gavin Makea2e3302023-03-11 06:46:20 +000074 Returns:
75 True if the attribute is a valid string representing true.
76 False if the attribute is a valid string representing false.
77 |default| otherwise.
78 """
79 value = node.getAttribute(attr)
80 s = value.lower()
81 if s == "":
82 return default
83 elif s in {"yes", "true", "1"}:
84 return True
85 elif s in {"no", "false", "0"}:
86 return False
87 else:
88 print(
89 'warning: manifest: %s="%s": ignoring invalid XML boolean'
90 % (attr, value),
91 file=sys.stderr,
92 )
93 return default
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050094
95
96def XmlInt(node, attr, default=None):
Gavin Makea2e3302023-03-11 06:46:20 +000097 """Determine integer value of |node|'s |attr|.
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050098
Gavin Makea2e3302023-03-11 06:46:20 +000099 Args:
100 node: XML node whose attributes we access.
101 attr: The attribute to access.
102 default: If the attribute is not set (value is empty), then use this.
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500103
Gavin Makea2e3302023-03-11 06:46:20 +0000104 Returns:
105 The number if the attribute is a valid number.
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500106
Gavin Makea2e3302023-03-11 06:46:20 +0000107 Raises:
108 ManifestParseError: The number is invalid.
109 """
110 value = node.getAttribute(attr)
111 if not value:
112 return default
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500113
Gavin Makea2e3302023-03-11 06:46:20 +0000114 try:
115 return int(value)
116 except ValueError:
117 raise ManifestParseError(
118 'manifest: invalid %s="%s" integer' % (attr, value)
119 )
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500120
121
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700122class _Default(object):
Gavin Makea2e3302023-03-11 06:46:20 +0000123 """Project defaults within the manifest."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700124
Gavin Makea2e3302023-03-11 06:46:20 +0000125 revisionExpr = None
126 destBranchExpr = None
127 upstreamExpr = None
128 remote = None
129 sync_j = None
130 sync_c = False
131 sync_s = False
132 sync_tags = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700133
Gavin Makea2e3302023-03-11 06:46:20 +0000134 def __eq__(self, other):
135 if not isinstance(other, _Default):
136 return False
137 return self.__dict__ == other.__dict__
Julien Campergue74879922013-10-09 14:38:46 +0200138
Gavin Makea2e3302023-03-11 06:46:20 +0000139 def __ne__(self, other):
140 if not isinstance(other, _Default):
141 return True
142 return self.__dict__ != other.__dict__
Julien Campergue74879922013-10-09 14:38:46 +0200143
David Pursehouse819827a2020-02-12 15:20:19 +0900144
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700145class _XmlRemote(object):
Gavin Makea2e3302023-03-11 06:46:20 +0000146 def __init__(
147 self,
148 name,
149 alias=None,
150 fetch=None,
151 pushUrl=None,
152 manifestUrl=None,
153 review=None,
154 revision=None,
155 ):
156 self.name = name
157 self.fetchUrl = fetch
158 self.pushUrl = pushUrl
159 self.manifestUrl = manifestUrl
160 self.remoteAlias = alias
161 self.reviewUrl = review
162 self.revision = revision
163 self.resolvedFetchUrl = self._resolveFetchUrl()
164 self.annotations = []
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700165
Gavin Makea2e3302023-03-11 06:46:20 +0000166 def __eq__(self, other):
167 if not isinstance(other, _XmlRemote):
168 return False
169 return (
170 sorted(self.annotations) == sorted(other.annotations)
171 and self.name == other.name
172 and self.fetchUrl == other.fetchUrl
173 and self.pushUrl == other.pushUrl
174 and self.remoteAlias == other.remoteAlias
175 and self.reviewUrl == other.reviewUrl
176 and self.revision == other.revision
177 )
David Pursehouse717ece92012-11-13 08:49:16 +0900178
Gavin Makea2e3302023-03-11 06:46:20 +0000179 def __ne__(self, other):
180 return not self.__eq__(other)
David Pursehouse717ece92012-11-13 08:49:16 +0900181
Gavin Makea2e3302023-03-11 06:46:20 +0000182 def _resolveFetchUrl(self):
183 if self.fetchUrl is None:
184 return ""
185 url = self.fetchUrl.rstrip("/")
186 manifestUrl = self.manifestUrl.rstrip("/")
187 # urljoin will gets confused over quite a few things. The ones we care
188 # about here are:
189 # * no scheme in the base url, like <hostname:port>
190 # We handle no scheme by replacing it with an obscure protocol, gopher
191 # and then replacing it with the original when we are done.
Anthony Kingcb07ba72015-03-28 23:26:04 +0000192
Gavin Makea2e3302023-03-11 06:46:20 +0000193 if manifestUrl.find(":") != manifestUrl.find("/") - 1:
194 url = urllib.parse.urljoin("gopher://" + manifestUrl, url)
195 url = re.sub(r"^gopher://", "", url)
196 else:
197 url = urllib.parse.urljoin(manifestUrl, url)
198 return url
Conley Owensceea3682011-10-20 10:45:47 -0700199
Gavin Makea2e3302023-03-11 06:46:20 +0000200 def ToRemoteSpec(self, projectName):
201 fetchUrl = self.resolvedFetchUrl.rstrip("/")
202 url = fetchUrl + "/" + projectName
203 remoteName = self.name
204 if self.remoteAlias:
205 remoteName = self.remoteAlias
206 return RemoteSpec(
207 remoteName,
208 url=url,
209 pushUrl=self.pushUrl,
210 review=self.reviewUrl,
211 orig_name=self.name,
212 fetchUrl=self.fetchUrl,
213 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700214
Gavin Makea2e3302023-03-11 06:46:20 +0000215 def AddAnnotation(self, name, value, keep):
216 self.annotations.append(Annotation(name, value, keep))
Jack Neus6ea0cae2021-07-20 20:52:33 +0000217
David Pursehouse819827a2020-02-12 15:20:19 +0900218
LaMont Jonescc879a92021-11-18 22:40:18 +0000219class _XmlSubmanifest:
Gavin Makea2e3302023-03-11 06:46:20 +0000220 """Manage the <submanifest> element specified in the manifest.
LaMont Jonescc879a92021-11-18 22:40:18 +0000221
Gavin Makea2e3302023-03-11 06:46:20 +0000222 Attributes:
223 name: a string, the name for this submanifest.
224 remote: a string, the remote.name for this submanifest.
225 project: a string, the name of the manifest project.
226 revision: a string, the commitish.
227 manifestName: a string, the submanifest file name.
228 groups: a list of strings, the groups to add to all projects in the
229 submanifest.
230 default_groups: a list of strings, the default groups to sync.
231 path: a string, the relative path for the submanifest checkout.
232 parent: an XmlManifest, the parent manifest.
233 annotations: (derived) a list of annotations.
234 present: (derived) a boolean, whether the sub manifest file is present.
235 """
LaMont Jonescc879a92021-11-18 22:40:18 +0000236
Gavin Makea2e3302023-03-11 06:46:20 +0000237 def __init__(
238 self,
239 name,
240 remote=None,
241 project=None,
242 revision=None,
243 manifestName=None,
244 groups=None,
245 default_groups=None,
246 path=None,
247 parent=None,
248 ):
249 self.name = name
250 self.remote = remote
251 self.project = project
252 self.revision = revision
253 self.manifestName = manifestName
254 self.groups = groups
255 self.default_groups = default_groups
256 self.path = path
257 self.parent = parent
258 self.annotations = []
259 outer_client = parent._outer_client or parent
260 if self.remote and not self.project:
261 raise ManifestParseError(
262 f"Submanifest {name}: must specify project when remote is "
263 "given."
264 )
265 # Construct the absolute path to the manifest file using the parent's
266 # method, so that we can correctly create our repo_client.
267 manifestFile = parent.SubmanifestInfoDir(
268 os.path.join(parent.path_prefix, self.relpath),
269 os.path.join("manifests", manifestName or "default.xml"),
270 )
271 linkFile = parent.SubmanifestInfoDir(
272 os.path.join(parent.path_prefix, self.relpath), MANIFEST_FILE_NAME
273 )
274 self.repo_client = RepoClient(
275 parent.repodir,
276 linkFile,
277 parent_groups=",".join(groups) or "",
278 submanifest_path=self.relpath,
279 outer_client=outer_client,
280 default_groups=default_groups,
281 )
LaMont Jonescc879a92021-11-18 22:40:18 +0000282
Gavin Makea2e3302023-03-11 06:46:20 +0000283 self.present = os.path.exists(manifestFile)
LaMont Jonescc879a92021-11-18 22:40:18 +0000284
Gavin Makea2e3302023-03-11 06:46:20 +0000285 def __eq__(self, other):
286 if not isinstance(other, _XmlSubmanifest):
287 return False
288 return (
289 self.name == other.name
290 and self.remote == other.remote
291 and self.project == other.project
292 and self.revision == other.revision
293 and self.manifestName == other.manifestName
294 and self.groups == other.groups
295 and self.default_groups == other.default_groups
296 and self.path == other.path
297 and sorted(self.annotations) == sorted(other.annotations)
298 )
LaMont Jonescc879a92021-11-18 22:40:18 +0000299
Gavin Makea2e3302023-03-11 06:46:20 +0000300 def __ne__(self, other):
301 return not self.__eq__(other)
LaMont Jonescc879a92021-11-18 22:40:18 +0000302
Gavin Makea2e3302023-03-11 06:46:20 +0000303 def ToSubmanifestSpec(self):
304 """Return a SubmanifestSpec object, populating attributes"""
305 mp = self.parent.manifestProject
306 remote = self.parent.remotes[
307 self.remote or self.parent.default.remote.name
308 ]
309 # If a project was given, generate the url from the remote and project.
310 # If not, use this manifestProject's url.
311 if self.project:
312 manifestUrl = remote.ToRemoteSpec(self.project).url
313 else:
314 manifestUrl = mp.GetRemote().url
315 manifestName = self.manifestName or "default.xml"
316 revision = self.revision or self.name
317 path = self.path or revision.split("/")[-1]
318 groups = self.groups or []
LaMont Jonescc879a92021-11-18 22:40:18 +0000319
Gavin Makea2e3302023-03-11 06:46:20 +0000320 return SubmanifestSpec(
321 self.name, manifestUrl, manifestName, revision, path, groups
322 )
LaMont Jonescc879a92021-11-18 22:40:18 +0000323
Gavin Makea2e3302023-03-11 06:46:20 +0000324 @property
325 def relpath(self):
326 """The path of this submanifest relative to the parent manifest."""
327 revision = self.revision or self.name
328 return self.path or revision.split("/")[-1]
LaMont Jonescc879a92021-11-18 22:40:18 +0000329
Gavin Makea2e3302023-03-11 06:46:20 +0000330 def GetGroupsStr(self):
331 """Returns the `groups` given for this submanifest."""
332 if self.groups:
333 return ",".join(self.groups)
334 return ""
LaMont Jones501733c2022-04-20 16:42:32 +0000335
Gavin Makea2e3302023-03-11 06:46:20 +0000336 def GetDefaultGroupsStr(self):
337 """Returns the `default-groups` given for this submanifest."""
338 return ",".join(self.default_groups or [])
339
340 def AddAnnotation(self, name, value, keep):
341 """Add annotations to the submanifest."""
342 self.annotations.append(Annotation(name, value, keep))
LaMont Jonescc879a92021-11-18 22:40:18 +0000343
344
345class SubmanifestSpec:
Gavin Makea2e3302023-03-11 06:46:20 +0000346 """The submanifest element, with all fields expanded."""
LaMont Jonescc879a92021-11-18 22:40:18 +0000347
Gavin Makea2e3302023-03-11 06:46:20 +0000348 def __init__(self, name, manifestUrl, manifestName, revision, path, groups):
349 self.name = name
350 self.manifestUrl = manifestUrl
351 self.manifestName = manifestName
352 self.revision = revision
353 self.path = path
354 self.groups = groups or []
LaMont Jonescc879a92021-11-18 22:40:18 +0000355
356
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700357class XmlManifest(object):
Gavin Makea2e3302023-03-11 06:46:20 +0000358 """manages the repo configuration file"""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700359
Gavin Makea2e3302023-03-11 06:46:20 +0000360 def __init__(
361 self,
362 repodir,
363 manifest_file,
364 local_manifests=None,
365 outer_client=None,
366 parent_groups="",
367 submanifest_path="",
368 default_groups=None,
369 ):
370 """Initialize.
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400371
Gavin Makea2e3302023-03-11 06:46:20 +0000372 Args:
373 repodir: Path to the .repo/ dir for holding all internal checkout
374 state. It must be in the top directory of the repo client
375 checkout.
376 manifest_file: Full path to the manifest file to parse. This will
377 usually be |repodir|/|MANIFEST_FILE_NAME|.
378 local_manifests: Full path to the directory of local override
379 manifests. This will usually be
380 |repodir|/|LOCAL_MANIFESTS_DIR_NAME|.
381 outer_client: RepoClient of the outer manifest.
382 parent_groups: a string, the groups to apply to this projects.
383 submanifest_path: The submanifest root relative to the repo root.
384 default_groups: a string, the default manifest groups to use.
385 """
386 # TODO(vapier): Move this out of this class.
387 self.globalConfig = GitConfig.ForUser()
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400388
Gavin Makea2e3302023-03-11 06:46:20 +0000389 self.repodir = os.path.abspath(repodir)
390 self._CheckLocalPath(submanifest_path)
391 self.topdir = os.path.dirname(self.repodir)
392 if submanifest_path:
393 # This avoids a trailing os.path.sep when submanifest_path is empty.
394 self.topdir = os.path.join(self.topdir, submanifest_path)
395 if manifest_file != os.path.abspath(manifest_file):
396 raise ManifestParseError("manifest_file must be abspath")
397 self.manifestFile = manifest_file
398 if not outer_client or outer_client == self:
399 # manifestFileOverrides only exists in the outer_client's manifest,
400 # since that is the only instance left when Unload() is called on
401 # the outer manifest.
402 self.manifestFileOverrides = {}
403 self.local_manifests = local_manifests
404 self._load_local_manifests = True
405 self.parent_groups = parent_groups
406 self.default_groups = default_groups
LaMont Jonescc879a92021-11-18 22:40:18 +0000407
Gavin Makea2e3302023-03-11 06:46:20 +0000408 if outer_client and self.isGitcClient:
409 raise ManifestParseError(
410 "Multi-manifest is incompatible with `gitc-init`"
411 )
LaMont Jonescc879a92021-11-18 22:40:18 +0000412
Gavin Makea2e3302023-03-11 06:46:20 +0000413 if submanifest_path and not outer_client:
414 # If passing a submanifest_path, there must be an outer_client.
415 raise ManifestParseError(f"Bad call to {self.__class__.__name__}")
LaMont Jonescc879a92021-11-18 22:40:18 +0000416
Gavin Makea2e3302023-03-11 06:46:20 +0000417 # If self._outer_client is None, this is not a checkout that supports
418 # multi-tree.
419 self._outer_client = outer_client or self
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700420
Gavin Makea2e3302023-03-11 06:46:20 +0000421 self.repoProject = RepoProject(
422 self,
423 "repo",
424 gitdir=os.path.join(repodir, "repo/.git"),
425 worktree=os.path.join(repodir, "repo"),
426 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700427
Gavin Makea2e3302023-03-11 06:46:20 +0000428 mp = self.SubmanifestProject(self.path_prefix)
429 self.manifestProject = mp
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500430
Gavin Makea2e3302023-03-11 06:46:20 +0000431 # This is a bit hacky, but we're in a chicken & egg situation: all the
432 # normal repo settings live in the manifestProject which we just setup
433 # above, so we couldn't easily query before that. We assume Project()
434 # init doesn't care if this changes afterwards.
435 if os.path.exists(mp.gitdir) and mp.use_worktree:
436 mp.use_git_worktrees = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700437
Gavin Makea2e3302023-03-11 06:46:20 +0000438 self.Unload()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700439
Gavin Makea2e3302023-03-11 06:46:20 +0000440 def Override(self, name, load_local_manifests=True):
441 """Use a different manifest, just for the current instantiation."""
442 path = None
Basil Gelloc7453502018-05-25 20:23:52 +0300443
Gavin Makea2e3302023-03-11 06:46:20 +0000444 # Look for a manifest by path in the filesystem (including the cwd).
445 if not load_local_manifests:
446 local_path = os.path.abspath(name)
447 if os.path.isfile(local_path):
448 path = local_path
Basil Gelloc7453502018-05-25 20:23:52 +0300449
Gavin Makea2e3302023-03-11 06:46:20 +0000450 # Look for manifests by name from the manifests repo.
451 if path is None:
452 path = os.path.join(self.manifestProject.worktree, name)
453 if not os.path.isfile(path):
454 raise ManifestParseError("manifest %s not found" % name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700455
Gavin Makea2e3302023-03-11 06:46:20 +0000456 self._load_local_manifests = load_local_manifests
457 self._outer_client.manifestFileOverrides[self.path_prefix] = path
458 self.Unload()
459 self._Load()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700460
Gavin Makea2e3302023-03-11 06:46:20 +0000461 def Link(self, name):
462 """Update the repo metadata to use a different manifest."""
463 self.Override(name)
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700464
Gavin Makea2e3302023-03-11 06:46:20 +0000465 # Old versions of repo would generate symlinks we need to clean up.
466 platform_utils.remove(self.manifestFile, missing_ok=True)
467 # This file is interpreted as if it existed inside the manifest repo.
468 # That allows us to use <include> with the relative file name.
469 with open(self.manifestFile, "w") as fp:
470 fp.write(
471 """<?xml version="1.0" encoding="UTF-8"?>
Mike Frysingera269b1c2020-02-21 00:49:41 -0500472<!--
473DO NOT EDIT THIS FILE! It is generated by repo and changes will be discarded.
474If you want to use a different manifest, use `repo init -m <file>` instead.
475
476If you want to customize your checkout by overriding manifest settings, use
477the local_manifests/ directory instead.
478
479For more information on repo manifests, check out:
480https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
481-->
482<manifest>
483 <include name="%s" />
484</manifest>
Gavin Makea2e3302023-03-11 06:46:20 +0000485"""
486 % (name,)
487 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700488
Gavin Makea2e3302023-03-11 06:46:20 +0000489 def _RemoteToXml(self, r, doc, root):
490 e = doc.createElement("remote")
491 root.appendChild(e)
492 e.setAttribute("name", r.name)
493 e.setAttribute("fetch", r.fetchUrl)
494 if r.pushUrl is not None:
495 e.setAttribute("pushurl", r.pushUrl)
496 if r.remoteAlias is not None:
497 e.setAttribute("alias", r.remoteAlias)
498 if r.reviewUrl is not None:
499 e.setAttribute("review", r.reviewUrl)
500 if r.revision is not None:
501 e.setAttribute("revision", r.revision)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800502
Gavin Makea2e3302023-03-11 06:46:20 +0000503 for a in r.annotations:
504 if a.keep == "true":
505 ae = doc.createElement("annotation")
506 ae.setAttribute("name", a.name)
507 ae.setAttribute("value", a.value)
508 e.appendChild(ae)
Jack Neus6ea0cae2021-07-20 20:52:33 +0000509
Gavin Makea2e3302023-03-11 06:46:20 +0000510 def _SubmanifestToXml(self, r, doc, root):
511 """Generate XML <submanifest/> node."""
512 e = doc.createElement("submanifest")
513 root.appendChild(e)
514 e.setAttribute("name", r.name)
515 if r.remote is not None:
516 e.setAttribute("remote", r.remote)
517 if r.project is not None:
518 e.setAttribute("project", r.project)
519 if r.manifestName is not None:
520 e.setAttribute("manifest-name", r.manifestName)
521 if r.revision is not None:
522 e.setAttribute("revision", r.revision)
523 if r.path is not None:
524 e.setAttribute("path", r.path)
525 if r.groups:
526 e.setAttribute("groups", r.GetGroupsStr())
527 if r.default_groups:
528 e.setAttribute("default-groups", r.GetDefaultGroupsStr())
LaMont Jonescc879a92021-11-18 22:40:18 +0000529
Gavin Makea2e3302023-03-11 06:46:20 +0000530 for a in r.annotations:
531 if a.keep == "true":
532 ae = doc.createElement("annotation")
533 ae.setAttribute("name", a.name)
534 ae.setAttribute("value", a.value)
535 e.appendChild(ae)
LaMont Jonescc879a92021-11-18 22:40:18 +0000536
Gavin Makea2e3302023-03-11 06:46:20 +0000537 def _ParseList(self, field):
538 """Parse fields that contain flattened lists.
Mike Frysinger51e39d52020-12-04 05:32:06 -0500539
Gavin Makea2e3302023-03-11 06:46:20 +0000540 These are whitespace & comma separated. Empty elements will be
541 discarded.
542 """
543 return [x for x in re.split(r"[,\s]+", field) if x]
Josh Triplett884a3872014-06-12 14:57:29 -0700544
Gavin Makea2e3302023-03-11 06:46:20 +0000545 def ToXml(
546 self,
547 peg_rev=False,
548 peg_rev_upstream=True,
549 peg_rev_dest_branch=True,
550 groups=None,
551 omit_local=False,
552 ):
553 """Return the current manifest XML."""
554 mp = self.manifestProject
Colin Cross5acde752012-03-28 20:15:45 -0700555
Gavin Makea2e3302023-03-11 06:46:20 +0000556 if groups is None:
557 groups = mp.manifest_groups
558 if groups:
559 groups = self._ParseList(groups)
Colin Cross5acde752012-03-28 20:15:45 -0700560
Gavin Makea2e3302023-03-11 06:46:20 +0000561 doc = xml.dom.minidom.Document()
562 root = doc.createElement("manifest")
563 if self.is_submanifest:
564 root.setAttribute("path", self.path_prefix)
565 doc.appendChild(root)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800566
Gavin Makea2e3302023-03-11 06:46:20 +0000567 # Save out the notice. There's a little bit of work here to give it the
568 # right whitespace, which assumes that the notice is automatically
569 # indented by 4 by minidom.
570 if self.notice:
571 notice_element = root.appendChild(doc.createElement("notice"))
572 notice_lines = self.notice.splitlines()
573 indented_notice = (
574 "\n".join(" " * 4 + line for line in notice_lines)
575 )[4:]
576 notice_element.appendChild(doc.createTextNode(indented_notice))
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700577
Gavin Makea2e3302023-03-11 06:46:20 +0000578 d = self.default
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800579
Gavin Makea2e3302023-03-11 06:46:20 +0000580 for r in sorted(self.remotes):
581 self._RemoteToXml(self.remotes[r], doc, root)
582 if self.remotes:
583 root.appendChild(doc.createTextNode(""))
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800584
Gavin Makea2e3302023-03-11 06:46:20 +0000585 have_default = False
586 e = doc.createElement("default")
587 if d.remote:
588 have_default = True
589 e.setAttribute("remote", d.remote.name)
590 if d.revisionExpr:
591 have_default = True
592 e.setAttribute("revision", d.revisionExpr)
593 if d.destBranchExpr:
594 have_default = True
595 e.setAttribute("dest-branch", d.destBranchExpr)
596 if d.upstreamExpr:
597 have_default = True
598 e.setAttribute("upstream", d.upstreamExpr)
599 if d.sync_j is not None:
600 have_default = True
601 e.setAttribute("sync-j", "%d" % d.sync_j)
602 if d.sync_c:
603 have_default = True
604 e.setAttribute("sync-c", "true")
605 if d.sync_s:
606 have_default = True
607 e.setAttribute("sync-s", "true")
608 if not d.sync_tags:
609 have_default = True
610 e.setAttribute("sync-tags", "false")
611 if have_default:
612 root.appendChild(e)
613 root.appendChild(doc.createTextNode(""))
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800614
Gavin Makea2e3302023-03-11 06:46:20 +0000615 if self._manifest_server:
616 e = doc.createElement("manifest-server")
617 e.setAttribute("url", self._manifest_server)
618 root.appendChild(e)
619 root.appendChild(doc.createTextNode(""))
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700620
Gavin Makea2e3302023-03-11 06:46:20 +0000621 for r in sorted(self.submanifests):
622 self._SubmanifestToXml(self.submanifests[r], doc, root)
623 if self.submanifests:
624 root.appendChild(doc.createTextNode(""))
LaMont Jonescc879a92021-11-18 22:40:18 +0000625
Gavin Makea2e3302023-03-11 06:46:20 +0000626 def output_projects(parent, parent_node, projects):
627 for project_name in projects:
628 for project in self._projects[project_name]:
629 output_project(parent, parent_node, project)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800630
Gavin Makea2e3302023-03-11 06:46:20 +0000631 def output_project(parent, parent_node, p):
632 if not p.MatchesGroups(groups):
633 return
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800634
Gavin Makea2e3302023-03-11 06:46:20 +0000635 if omit_local and self.IsFromLocalManifest(p):
636 return
LaMont Jonesa8cf5752022-07-15 20:31:33 +0000637
Gavin Makea2e3302023-03-11 06:46:20 +0000638 name = p.name
639 relpath = p.relpath
640 if parent:
641 name = self._UnjoinName(parent.name, name)
642 relpath = self._UnjoinRelpath(parent.relpath, relpath)
Colin Cross5acde752012-03-28 20:15:45 -0700643
Gavin Makea2e3302023-03-11 06:46:20 +0000644 e = doc.createElement("project")
645 parent_node.appendChild(e)
646 e.setAttribute("name", name)
647 if relpath != name:
648 e.setAttribute("path", relpath)
649 remoteName = None
650 if d.remote:
651 remoteName = d.remote.name
652 if not d.remote or p.remote.orig_name != remoteName:
653 remoteName = p.remote.orig_name
654 e.setAttribute("remote", remoteName)
655 if peg_rev:
656 if self.IsMirror:
657 value = p.bare_git.rev_parse(p.revisionExpr + "^0")
658 else:
659 value = p.work_git.rev_parse(HEAD + "^0")
660 e.setAttribute("revision", value)
661 if peg_rev_upstream:
662 if p.upstream:
663 e.setAttribute("upstream", p.upstream)
664 elif value != p.revisionExpr:
665 # Only save the origin if the origin is not a sha1, and
666 # the default isn't our value
667 e.setAttribute("upstream", p.revisionExpr)
668
669 if peg_rev_dest_branch:
670 if p.dest_branch:
671 e.setAttribute("dest-branch", p.dest_branch)
672 elif value != p.revisionExpr:
673 e.setAttribute("dest-branch", p.revisionExpr)
674
675 else:
676 revision = (
677 self.remotes[p.remote.orig_name].revision or d.revisionExpr
678 )
679 if not revision or revision != p.revisionExpr:
680 e.setAttribute("revision", p.revisionExpr)
681 elif p.revisionId:
682 e.setAttribute("revision", p.revisionId)
683 if p.upstream and (
684 p.upstream != p.revisionExpr or p.upstream != d.upstreamExpr
685 ):
686 e.setAttribute("upstream", p.upstream)
687
688 if p.dest_branch and p.dest_branch != d.destBranchExpr:
689 e.setAttribute("dest-branch", p.dest_branch)
690
691 for c in p.copyfiles:
692 ce = doc.createElement("copyfile")
693 ce.setAttribute("src", c.src)
694 ce.setAttribute("dest", c.dest)
695 e.appendChild(ce)
696
697 for lf in p.linkfiles:
698 le = doc.createElement("linkfile")
699 le.setAttribute("src", lf.src)
700 le.setAttribute("dest", lf.dest)
701 e.appendChild(le)
702
703 default_groups = ["all", "name:%s" % p.name, "path:%s" % p.relpath]
704 egroups = [g for g in p.groups if g not in default_groups]
705 if egroups:
706 e.setAttribute("groups", ",".join(egroups))
707
708 for a in p.annotations:
709 if a.keep == "true":
710 ae = doc.createElement("annotation")
711 ae.setAttribute("name", a.name)
712 ae.setAttribute("value", a.value)
713 e.appendChild(ae)
714
715 if p.sync_c:
716 e.setAttribute("sync-c", "true")
717
718 if p.sync_s:
719 e.setAttribute("sync-s", "true")
720
721 if not p.sync_tags:
722 e.setAttribute("sync-tags", "false")
723
724 if p.clone_depth:
725 e.setAttribute("clone-depth", str(p.clone_depth))
726
727 self._output_manifest_project_extras(p, e)
728
729 if p.subprojects:
730 subprojects = set(subp.name for subp in p.subprojects)
731 output_projects(p, e, list(sorted(subprojects)))
732
733 projects = set(p.name for p in self._paths.values() if not p.parent)
734 output_projects(None, root, list(sorted(projects)))
735
736 if self._repo_hooks_project:
737 root.appendChild(doc.createTextNode(""))
738 e = doc.createElement("repo-hooks")
739 e.setAttribute("in-project", self._repo_hooks_project.name)
740 e.setAttribute(
741 "enabled-list",
742 " ".join(self._repo_hooks_project.enabled_repo_hooks),
743 )
744 root.appendChild(e)
745
746 if self._superproject:
747 root.appendChild(doc.createTextNode(""))
748 e = doc.createElement("superproject")
749 e.setAttribute("name", self._superproject.name)
750 remoteName = None
751 if d.remote:
752 remoteName = d.remote.name
753 remote = self._superproject.remote
754 if not d.remote or remote.orig_name != remoteName:
755 remoteName = remote.orig_name
756 e.setAttribute("remote", remoteName)
757 revision = remote.revision or d.revisionExpr
758 if not revision or revision != self._superproject.revision:
759 e.setAttribute("revision", self._superproject.revision)
760 root.appendChild(e)
761
762 if self._contactinfo.bugurl != Wrapper().BUG_URL:
763 root.appendChild(doc.createTextNode(""))
764 e = doc.createElement("contactinfo")
765 e.setAttribute("bugurl", self._contactinfo.bugurl)
766 root.appendChild(e)
767
768 return doc
769
770 def ToDict(self, **kwargs):
771 """Return the current manifest as a dictionary."""
772 # Elements that may only appear once.
773 SINGLE_ELEMENTS = {
774 "notice",
775 "default",
776 "manifest-server",
777 "repo-hooks",
778 "superproject",
779 "contactinfo",
780 }
781 # Elements that may be repeated.
782 MULTI_ELEMENTS = {
783 "remote",
784 "remove-project",
785 "project",
786 "extend-project",
787 "include",
788 "submanifest",
789 # These are children of 'project' nodes.
790 "annotation",
791 "project",
792 "copyfile",
793 "linkfile",
794 }
795
796 doc = self.ToXml(**kwargs)
797 ret = {}
798
799 def append_children(ret, node):
800 for child in node.childNodes:
801 if child.nodeType == xml.dom.Node.ELEMENT_NODE:
802 attrs = child.attributes
803 element = dict(
804 (attrs.item(i).localName, attrs.item(i).value)
805 for i in range(attrs.length)
806 )
807 if child.nodeName in SINGLE_ELEMENTS:
808 ret[child.nodeName] = element
809 elif child.nodeName in MULTI_ELEMENTS:
810 ret.setdefault(child.nodeName, []).append(element)
811 else:
812 raise ManifestParseError(
813 'Unhandled element "%s"' % (child.nodeName,)
814 )
815
816 append_children(element, child)
817
818 append_children(ret, doc.firstChild)
819
820 return ret
821
822 def Save(self, fd, **kwargs):
823 """Write the current manifest out to the given file descriptor."""
824 doc = self.ToXml(**kwargs)
825 doc.writexml(fd, "", " ", "\n", "UTF-8")
826
827 def _output_manifest_project_extras(self, p, e):
828 """Manifests can modify e if they support extra project attributes."""
829
830 @property
831 def is_multimanifest(self):
832 """Whether this is a multimanifest checkout.
833
834 This is safe to use as long as the outermost manifest XML has been
835 parsed.
836 """
837 return bool(self._outer_client._submanifests)
838
839 @property
840 def is_submanifest(self):
841 """Whether this manifest is a submanifest.
842
843 This is safe to use as long as the outermost manifest XML has been
844 parsed.
845 """
846 return self._outer_client and self._outer_client != self
847
848 @property
849 def outer_client(self):
850 """The instance of the outermost manifest client."""
851 self._Load()
852 return self._outer_client
853
854 @property
855 def all_manifests(self):
856 """Generator yielding all (sub)manifests, in depth-first order."""
857 self._Load()
858 outer = self._outer_client
859 yield outer
860 for tree in outer.all_children:
861 yield tree
862
863 @property
864 def all_children(self):
865 """Generator yielding all (present) child submanifests."""
866 self._Load()
867 for child in self._submanifests.values():
868 if child.repo_client:
869 yield child.repo_client
870 for tree in child.repo_client.all_children:
871 yield tree
872
873 @property
874 def path_prefix(self):
875 """The path of this submanifest, relative to the outermost manifest."""
876 if not self._outer_client or self == self._outer_client:
877 return ""
878 return os.path.relpath(self.topdir, self._outer_client.topdir)
879
880 @property
881 def all_paths(self):
882 """All project paths for all (sub)manifests.
883
884 See also `paths`.
885
886 Returns:
887 A dictionary of {path: Project()}. `path` is relative to the outer
888 manifest.
889 """
890 ret = {}
891 for tree in self.all_manifests:
892 prefix = tree.path_prefix
893 ret.update(
894 {os.path.join(prefix, k): v for k, v in tree.paths.items()}
895 )
896 return ret
897
898 @property
899 def all_projects(self):
900 """All projects for all (sub)manifests. See `projects`."""
901 return list(
902 itertools.chain.from_iterable(
903 x._paths.values() for x in self.all_manifests
904 )
905 )
906
907 @property
908 def paths(self):
909 """Return all paths for this manifest.
910
911 Returns:
912 A dictionary of {path: Project()}. `path` is relative to this
913 manifest.
914 """
915 self._Load()
916 return self._paths
917
918 @property
919 def projects(self):
920 """Return a list of all Projects in this manifest."""
921 self._Load()
922 return list(self._paths.values())
923
924 @property
925 def remotes(self):
926 """Return a list of remotes for this manifest."""
927 self._Load()
928 return self._remotes
929
930 @property
931 def default(self):
932 """Return default values for this manifest."""
933 self._Load()
934 return self._default
935
936 @property
937 def submanifests(self):
938 """All submanifests in this manifest."""
939 self._Load()
940 return self._submanifests
941
942 @property
943 def repo_hooks_project(self):
944 self._Load()
945 return self._repo_hooks_project
946
947 @property
948 def superproject(self):
949 self._Load()
950 return self._superproject
951
952 @property
953 def contactinfo(self):
954 self._Load()
955 return self._contactinfo
956
957 @property
958 def notice(self):
959 self._Load()
960 return self._notice
961
962 @property
963 def manifest_server(self):
964 self._Load()
965 return self._manifest_server
966
967 @property
968 def CloneBundle(self):
969 clone_bundle = self.manifestProject.clone_bundle
970 if clone_bundle is None:
971 return False if self.manifestProject.partial_clone else True
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800972 else:
Gavin Makea2e3302023-03-11 06:46:20 +0000973 return clone_bundle
Sean McAllisteraf908cb2020-04-20 08:41:58 -0600974
Gavin Makea2e3302023-03-11 06:46:20 +0000975 @property
976 def CloneFilter(self):
977 if self.manifestProject.partial_clone:
978 return self.manifestProject.clone_filter
979 return None
Sean McAllisteraf908cb2020-04-20 08:41:58 -0600980
Gavin Makea2e3302023-03-11 06:46:20 +0000981 @property
Jason Chang17833322023-05-23 13:06:55 -0700982 def CloneFilterForDepth(self):
983 if self.manifestProject.clone_filter_for_depth:
984 return self.manifestProject.clone_filter_for_depth
985 return None
986
987 @property
Gavin Makea2e3302023-03-11 06:46:20 +0000988 def PartialCloneExclude(self):
989 exclude = self.manifest.manifestProject.partial_clone_exclude or ""
990 return set(x.strip() for x in exclude.split(","))
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800991
Gavin Makea2e3302023-03-11 06:46:20 +0000992 def SetManifestOverride(self, path):
993 """Override manifestFile. The caller must call Unload()"""
994 self._outer_client.manifest.manifestFileOverrides[
995 self.path_prefix
996 ] = path
Simon Ruggier7e59de22015-07-24 12:50:06 +0200997
Gavin Makea2e3302023-03-11 06:46:20 +0000998 @property
999 def UseLocalManifests(self):
1000 return self._load_local_manifests
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -08001001
Gavin Makea2e3302023-03-11 06:46:20 +00001002 def SetUseLocalManifests(self, value):
1003 self._load_local_manifests = value
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001004
Gavin Makea2e3302023-03-11 06:46:20 +00001005 @property
1006 def HasLocalManifests(self):
1007 return self._load_local_manifests and self.local_manifests
Colin Cross5acde752012-03-28 20:15:45 -07001008
Gavin Makea2e3302023-03-11 06:46:20 +00001009 def IsFromLocalManifest(self, project):
1010 """Is the project from a local manifest?"""
1011 return any(
1012 x.startswith(LOCAL_MANIFEST_GROUP_PREFIX) for x in project.groups
1013 )
James W. Mills24c13082012-04-12 15:04:13 -05001014
Gavin Makea2e3302023-03-11 06:46:20 +00001015 @property
1016 def IsMirror(self):
1017 return self.manifestProject.mirror
Anatol Pomazau79770d22012-04-20 14:41:59 -07001018
Gavin Makea2e3302023-03-11 06:46:20 +00001019 @property
1020 def UseGitWorktrees(self):
1021 return self.manifestProject.use_worktree
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001022
Gavin Makea2e3302023-03-11 06:46:20 +00001023 @property
1024 def IsArchive(self):
1025 return self.manifestProject.archive
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +09001026
Gavin Makea2e3302023-03-11 06:46:20 +00001027 @property
1028 def HasSubmodules(self):
1029 return self.manifestProject.submodules
Dan Willemsen88409222015-08-17 15:29:10 -07001030
Gavin Makea2e3302023-03-11 06:46:20 +00001031 @property
1032 def EnableGitLfs(self):
1033 return self.manifestProject.git_lfs
Simran Basib9a1b732015-08-20 12:19:28 -07001034
Gavin Makea2e3302023-03-11 06:46:20 +00001035 def FindManifestByPath(self, path):
1036 """Returns the manifest containing path."""
1037 path = os.path.abspath(path)
1038 manifest = self._outer_client or self
1039 old = None
1040 while manifest._submanifests and manifest != old:
1041 old = manifest
1042 for name in manifest._submanifests:
1043 tree = manifest._submanifests[name]
1044 if path.startswith(tree.repo_client.manifest.topdir):
1045 manifest = tree.repo_client
1046 break
1047 return manifest
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001048
Gavin Makea2e3302023-03-11 06:46:20 +00001049 @property
1050 def subdir(self):
1051 """Returns the path for per-submanifest objects for this manifest."""
1052 return self.SubmanifestInfoDir(self.path_prefix)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001053
Gavin Makea2e3302023-03-11 06:46:20 +00001054 def SubmanifestInfoDir(self, submanifest_path, object_path=""):
1055 """Return the path to submanifest-specific info for a submanifest.
Doug Anderson37282b42011-03-04 11:54:18 -08001056
Gavin Makea2e3302023-03-11 06:46:20 +00001057 Return the full path of the directory in which to put per-manifest
1058 objects.
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001059
Gavin Makea2e3302023-03-11 06:46:20 +00001060 Args:
1061 submanifest_path: a string, the path of the submanifest, relative to
1062 the outermost topdir. If empty, then repodir is returned.
1063 object_path: a string, relative path to append to the submanifest
1064 info directory path.
1065 """
1066 if submanifest_path:
1067 return os.path.join(
1068 self.repodir, SUBMANIFEST_DIR, submanifest_path, object_path
1069 )
1070 else:
1071 return os.path.join(self.repodir, object_path)
Raman Tenneti1c3f57e2021-05-04 12:32:13 -07001072
Gavin Makea2e3302023-03-11 06:46:20 +00001073 def SubmanifestProject(self, submanifest_path):
1074 """Return a manifestProject for a submanifest."""
1075 subdir = self.SubmanifestInfoDir(submanifest_path)
1076 mp = ManifestProject(
1077 self,
1078 "manifests",
1079 gitdir=os.path.join(subdir, "manifests.git"),
1080 worktree=os.path.join(subdir, "manifests"),
1081 )
1082 return mp
Mike Frysinger23411d32020-09-02 04:31:10 -04001083
Gavin Makea2e3302023-03-11 06:46:20 +00001084 def GetDefaultGroupsStr(self, with_platform=True):
1085 """Returns the default group string to use.
Mike Frysinger23411d32020-09-02 04:31:10 -04001086
Gavin Makea2e3302023-03-11 06:46:20 +00001087 Args:
1088 with_platform: a boolean, whether to include the group for the
1089 underlying platform.
1090 """
1091 groups = ",".join(self.default_groups or ["default"])
1092 if with_platform:
1093 groups += f",platform-{platform.system().lower()}"
1094 return groups
Mike Frysinger23411d32020-09-02 04:31:10 -04001095
Gavin Makea2e3302023-03-11 06:46:20 +00001096 def GetGroupsStr(self):
1097 """Returns the manifest group string that should be synced."""
1098 return (
1099 self.manifestProject.manifest_groups or self.GetDefaultGroupsStr()
1100 )
Mike Frysinger23411d32020-09-02 04:31:10 -04001101
Gavin Makea2e3302023-03-11 06:46:20 +00001102 def Unload(self):
1103 """Unload the manifest.
Mike Frysinger23411d32020-09-02 04:31:10 -04001104
Gavin Makea2e3302023-03-11 06:46:20 +00001105 If the manifest files have been changed since Load() was called, this
1106 will cause the new/updated manifest to be used.
Mike Frysinger23411d32020-09-02 04:31:10 -04001107
Gavin Makea2e3302023-03-11 06:46:20 +00001108 """
1109 self._loaded = False
1110 self._projects = {}
1111 self._paths = {}
1112 self._remotes = {}
1113 self._default = None
1114 self._submanifests = {}
1115 self._repo_hooks_project = None
1116 self._superproject = None
1117 self._contactinfo = ContactInfo(Wrapper().BUG_URL)
1118 self._notice = None
1119 self.branch = None
1120 self._manifest_server = None
Mike Frysinger23411d32020-09-02 04:31:10 -04001121
Gavin Makea2e3302023-03-11 06:46:20 +00001122 def Load(self):
1123 """Read the manifest into memory."""
1124 # Do not expose internal arguments.
1125 self._Load()
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -08001126
Gavin Makea2e3302023-03-11 06:46:20 +00001127 def _Load(self, initial_client=None, submanifest_depth=0):
1128 if submanifest_depth > MAX_SUBMANIFEST_DEPTH:
1129 raise ManifestParseError(
1130 "maximum submanifest depth %d exceeded." % MAX_SUBMANIFEST_DEPTH
1131 )
1132 if not self._loaded:
1133 if self._outer_client and self._outer_client != self:
1134 # This will load all clients.
1135 self._outer_client._Load(initial_client=self)
Simran Basib9a1b732015-08-20 12:19:28 -07001136
Gavin Makea2e3302023-03-11 06:46:20 +00001137 savedManifestFile = self.manifestFile
1138 override = self._outer_client.manifestFileOverrides.get(
1139 self.path_prefix
1140 )
1141 if override:
1142 self.manifestFile = override
Mike Frysinger1d00a7e2021-12-21 00:40:31 -05001143
Gavin Makea2e3302023-03-11 06:46:20 +00001144 try:
1145 m = self.manifestProject
1146 b = m.GetBranch(m.CurrentBranch).merge
1147 if b is not None and b.startswith(R_HEADS):
1148 b = b[len(R_HEADS) :]
1149 self.branch = b
LaMont Jonescc879a92021-11-18 22:40:18 +00001150
Gavin Makea2e3302023-03-11 06:46:20 +00001151 parent_groups = self.parent_groups
1152 if self.path_prefix:
1153 parent_groups = (
1154 f"{SUBMANIFEST_GROUP_PREFIX}:path:"
1155 f"{self.path_prefix},{parent_groups}"
1156 )
LaMont Jonesff6b1da2022-06-01 21:03:34 +00001157
Gavin Makea2e3302023-03-11 06:46:20 +00001158 # The manifestFile was specified by the user which is why we
1159 # allow include paths to point anywhere.
1160 nodes = []
1161 nodes.append(
1162 self._ParseManifestXml(
1163 self.manifestFile,
1164 self.manifestProject.worktree,
1165 parent_groups=parent_groups,
1166 restrict_includes=False,
1167 )
1168 )
LaMont Jonescc879a92021-11-18 22:40:18 +00001169
Gavin Makea2e3302023-03-11 06:46:20 +00001170 if self._load_local_manifests and self.local_manifests:
1171 try:
1172 for local_file in sorted(
1173 platform_utils.listdir(self.local_manifests)
1174 ):
1175 if local_file.endswith(".xml"):
1176 local = os.path.join(
1177 self.local_manifests, local_file
1178 )
1179 # Since local manifests are entirely managed by
1180 # the user, allow them to point anywhere the
1181 # user wants.
1182 local_group = (
1183 f"{LOCAL_MANIFEST_GROUP_PREFIX}:"
1184 f"{local_file[:-4]}"
1185 )
1186 nodes.append(
1187 self._ParseManifestXml(
1188 local,
1189 self.subdir,
1190 parent_groups=(
1191 f"{local_group},{parent_groups}"
1192 ),
1193 restrict_includes=False,
1194 )
1195 )
1196 except OSError:
1197 pass
Raman Tenneti080877e2021-03-09 15:19:06 -08001198
Gavin Makea2e3302023-03-11 06:46:20 +00001199 try:
1200 self._ParseManifest(nodes)
1201 except ManifestParseError as e:
1202 # There was a problem parsing, unload ourselves in case they
1203 # catch this error and try again later, we will show the
1204 # correct error
1205 self.Unload()
1206 raise e
Raman Tenneti080877e2021-03-09 15:19:06 -08001207
Gavin Makea2e3302023-03-11 06:46:20 +00001208 if self.IsMirror:
1209 self._AddMetaProjectMirror(self.repoProject)
1210 self._AddMetaProjectMirror(self.manifestProject)
LaMont Jonesa2ff20d2022-04-07 16:49:06 +00001211
Gavin Makea2e3302023-03-11 06:46:20 +00001212 self._loaded = True
1213 finally:
1214 if override:
1215 self.manifestFile = savedManifestFile
LaMont Jonesa2ff20d2022-04-07 16:49:06 +00001216
Gavin Makea2e3302023-03-11 06:46:20 +00001217 # Now that we have loaded this manifest, load any submanifests as
1218 # well. We need to do this after self._loaded is set to avoid
1219 # looping.
1220 for name in self._submanifests:
1221 tree = self._submanifests[name]
1222 tree.ToSubmanifestSpec()
1223 present = os.path.exists(
1224 os.path.join(self.subdir, MANIFEST_FILE_NAME)
1225 )
1226 if present and tree.present and not tree.repo_client:
1227 if initial_client and initial_client.topdir == self.topdir:
1228 tree.repo_client = self
1229 tree.present = present
1230 elif not os.path.exists(self.subdir):
1231 tree.present = False
1232 if present and tree.present:
1233 tree.repo_client._Load(
1234 initial_client=initial_client,
1235 submanifest_depth=submanifest_depth + 1,
1236 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001237
Gavin Makea2e3302023-03-11 06:46:20 +00001238 def _ParseManifestXml(
Shuchuan Zeng3e3340d2023-04-18 10:36:50 +08001239 self,
1240 path,
1241 include_root,
1242 parent_groups="",
1243 restrict_includes=True,
1244 parent_node=None,
Gavin Makea2e3302023-03-11 06:46:20 +00001245 ):
1246 """Parse a manifest XML and return the computed nodes.
LaMont Jonesa2ff20d2022-04-07 16:49:06 +00001247
Gavin Makea2e3302023-03-11 06:46:20 +00001248 Args:
1249 path: The XML file to read & parse.
1250 include_root: The path to interpret include "name"s relative to.
1251 parent_groups: The groups to apply to this projects.
1252 restrict_includes: Whether to constrain the "name" attribute of
1253 includes.
Shuchuan Zeng3e3340d2023-04-18 10:36:50 +08001254 parent_node: The parent include node, to apply attribute to this
1255 projects.
LaMont Jonescc879a92021-11-18 22:40:18 +00001256
Gavin Makea2e3302023-03-11 06:46:20 +00001257 Returns:
1258 List of XML nodes.
1259 """
1260 try:
1261 root = xml.dom.minidom.parse(path)
1262 except (OSError, xml.parsers.expat.ExpatError) as e:
1263 raise ManifestParseError(
1264 "error parsing manifest %s: %s" % (path, e)
1265 )
David Pursehouse2d5a0df2012-11-13 02:50:36 +09001266
Gavin Makea2e3302023-03-11 06:46:20 +00001267 if not root or not root.childNodes:
1268 raise ManifestParseError("no root node in %s" % (path,))
Shawn O. Pearce5cc66792008-10-23 16:19:27 -07001269
Gavin Makea2e3302023-03-11 06:46:20 +00001270 for manifest in root.childNodes:
1271 if manifest.nodeName == "manifest":
1272 break
1273 else:
1274 raise ManifestParseError("no <manifest> in %s" % (path,))
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001275
LaMont Jonesb90a4222022-04-14 15:00:09 +00001276 nodes = []
Gavin Makea2e3302023-03-11 06:46:20 +00001277 for node in manifest.childNodes:
1278 if node.nodeName == "include":
1279 name = self._reqatt(node, "name")
1280 if restrict_includes:
1281 msg = self._CheckLocalPath(name)
1282 if msg:
1283 raise ManifestInvalidPathError(
1284 '<include> invalid "name": %s: %s' % (name, msg)
1285 )
1286 include_groups = ""
1287 if parent_groups:
1288 include_groups = parent_groups
1289 if node.hasAttribute("groups"):
1290 include_groups = (
1291 node.getAttribute("groups") + "," + include_groups
1292 )
1293 fp = os.path.join(include_root, name)
1294 if not os.path.isfile(fp):
1295 raise ManifestParseError(
1296 "include [%s/]%s doesn't exist or isn't a file"
1297 % (include_root, name)
1298 )
1299 try:
1300 nodes.extend(
Shuchuan Zeng3e3340d2023-04-18 10:36:50 +08001301 self._ParseManifestXml(
1302 fp, include_root, include_groups, parent_node=node
1303 )
Gavin Makea2e3302023-03-11 06:46:20 +00001304 )
1305 # should isolate this to the exact exception, but that's
1306 # tricky. actual parsing implementation may vary.
1307 except (
1308 KeyboardInterrupt,
1309 RuntimeError,
1310 SystemExit,
1311 ManifestParseError,
1312 ):
1313 raise
1314 except Exception as e:
1315 raise ManifestParseError(
1316 "failed parsing included manifest %s: %s" % (name, e)
1317 )
1318 else:
1319 if parent_groups and node.nodeName == "project":
1320 nodeGroups = parent_groups
1321 if node.hasAttribute("groups"):
1322 nodeGroups = (
1323 node.getAttribute("groups") + "," + nodeGroups
1324 )
1325 node.setAttribute("groups", nodeGroups)
Shuchuan Zeng3e3340d2023-04-18 10:36:50 +08001326 if (
1327 parent_node
1328 and node.nodeName == "project"
1329 and not node.hasAttribute("revision")
1330 ):
1331 node.setAttribute(
1332 "revision", parent_node.getAttribute("revision")
1333 )
Gavin Makea2e3302023-03-11 06:46:20 +00001334 nodes.append(node)
1335 return nodes
LaMont Jonesb90a4222022-04-14 15:00:09 +00001336
Gavin Makea2e3302023-03-11 06:46:20 +00001337 def _ParseManifest(self, node_list):
1338 for node in itertools.chain(*node_list):
1339 if node.nodeName == "remote":
1340 remote = self._ParseRemote(node)
1341 if remote:
1342 if remote.name in self._remotes:
1343 if remote != self._remotes[remote.name]:
1344 raise ManifestParseError(
1345 "remote %s already exists with different "
1346 "attributes" % (remote.name)
1347 )
1348 else:
1349 self._remotes[remote.name] = remote
LaMont Jonesb90a4222022-04-14 15:00:09 +00001350
Gavin Makea2e3302023-03-11 06:46:20 +00001351 for node in itertools.chain(*node_list):
1352 if node.nodeName == "default":
1353 new_default = self._ParseDefault(node)
1354 emptyDefault = (
1355 not node.hasAttributes() and not node.hasChildNodes()
1356 )
1357 if self._default is None:
1358 self._default = new_default
1359 elif not emptyDefault and new_default != self._default:
1360 raise ManifestParseError(
1361 "duplicate default in %s" % (self.manifestFile)
1362 )
LaMont Jonesb90a4222022-04-14 15:00:09 +00001363
Julien Campergue74879922013-10-09 14:38:46 +02001364 if self._default is None:
Gavin Makea2e3302023-03-11 06:46:20 +00001365 self._default = _Default()
Julien Campergue74879922013-10-09 14:38:46 +02001366
Gavin Makea2e3302023-03-11 06:46:20 +00001367 submanifest_paths = set()
1368 for node in itertools.chain(*node_list):
1369 if node.nodeName == "submanifest":
1370 submanifest = self._ParseSubmanifest(node)
1371 if submanifest:
1372 if submanifest.name in self._submanifests:
1373 if submanifest != self._submanifests[submanifest.name]:
1374 raise ManifestParseError(
1375 "submanifest %s already exists with different "
1376 "attributes" % (submanifest.name)
1377 )
1378 else:
1379 self._submanifests[submanifest.name] = submanifest
1380 submanifest_paths.add(submanifest.relpath)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001381
Gavin Makea2e3302023-03-11 06:46:20 +00001382 for node in itertools.chain(*node_list):
1383 if node.nodeName == "notice":
1384 if self._notice is not None:
1385 raise ManifestParseError(
1386 "duplicate notice in %s" % (self.manifestFile)
1387 )
1388 self._notice = self._ParseNotice(node)
LaMont Jonescc879a92021-11-18 22:40:18 +00001389
Gavin Makea2e3302023-03-11 06:46:20 +00001390 for node in itertools.chain(*node_list):
1391 if node.nodeName == "manifest-server":
1392 url = self._reqatt(node, "url")
1393 if self._manifest_server is not None:
1394 raise ManifestParseError(
1395 "duplicate manifest-server in %s" % (self.manifestFile)
1396 )
1397 self._manifest_server = url
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001398
Gavin Makea2e3302023-03-11 06:46:20 +00001399 def recursively_add_projects(project):
1400 projects = self._projects.setdefault(project.name, [])
1401 if project.relpath is None:
1402 raise ManifestParseError(
1403 "missing path for %s in %s"
1404 % (project.name, self.manifestFile)
1405 )
1406 if project.relpath in self._paths:
1407 raise ManifestParseError(
1408 "duplicate path %s in %s"
1409 % (project.relpath, self.manifestFile)
1410 )
1411 for tree in submanifest_paths:
1412 if project.relpath.startswith(tree):
1413 raise ManifestParseError(
1414 "project %s conflicts with submanifest path %s"
1415 % (project.relpath, tree)
1416 )
1417 self._paths[project.relpath] = project
1418 projects.append(project)
1419 for subproject in project.subprojects:
1420 recursively_add_projects(subproject)
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001421
Gavin Makea2e3302023-03-11 06:46:20 +00001422 repo_hooks_project = None
1423 enabled_repo_hooks = None
1424 for node in itertools.chain(*node_list):
1425 if node.nodeName == "project":
1426 project = self._ParseProject(node)
1427 recursively_add_projects(project)
1428 if node.nodeName == "extend-project":
1429 name = self._reqatt(node, "name")
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001430
Gavin Makea2e3302023-03-11 06:46:20 +00001431 if name not in self._projects:
1432 raise ManifestParseError(
1433 "extend-project element specifies non-existent "
1434 "project: %s" % name
1435 )
1436
1437 path = node.getAttribute("path")
1438 dest_path = node.getAttribute("dest-path")
1439 groups = node.getAttribute("groups")
1440 if groups:
1441 groups = self._ParseList(groups)
1442 revision = node.getAttribute("revision")
1443 remote_name = node.getAttribute("remote")
1444 if not remote_name:
1445 remote = self._default.remote
1446 else:
1447 remote = self._get_remote(node)
1448 dest_branch = node.getAttribute("dest-branch")
1449 upstream = node.getAttribute("upstream")
1450
1451 named_projects = self._projects[name]
1452 if dest_path and not path and len(named_projects) > 1:
1453 raise ManifestParseError(
1454 "extend-project cannot use dest-path when "
1455 "matching multiple projects: %s" % name
1456 )
1457 for p in self._projects[name]:
1458 if path and p.relpath != path:
1459 continue
1460 if groups:
1461 p.groups.extend(groups)
1462 if revision:
1463 p.SetRevision(revision)
1464
1465 if remote_name:
1466 p.remote = remote.ToRemoteSpec(name)
1467 if dest_branch:
1468 p.dest_branch = dest_branch
1469 if upstream:
1470 p.upstream = upstream
1471
1472 if dest_path:
1473 del self._paths[p.relpath]
1474 (
1475 relpath,
1476 worktree,
1477 gitdir,
1478 objdir,
1479 _,
1480 ) = self.GetProjectPaths(name, dest_path, remote.name)
1481 p.UpdatePaths(relpath, worktree, gitdir, objdir)
1482 self._paths[p.relpath] = p
1483
1484 if node.nodeName == "repo-hooks":
1485 # Only one project can be the hooks project
1486 if repo_hooks_project is not None:
1487 raise ManifestParseError(
1488 "duplicate repo-hooks in %s" % (self.manifestFile)
1489 )
1490
1491 # Get the name of the project and the (space-separated) list of
1492 # enabled.
1493 repo_hooks_project = self._reqatt(node, "in-project")
1494 enabled_repo_hooks = self._ParseList(
1495 self._reqatt(node, "enabled-list")
1496 )
1497 if node.nodeName == "superproject":
1498 name = self._reqatt(node, "name")
1499 # There can only be one superproject.
1500 if self._superproject:
1501 raise ManifestParseError(
1502 "duplicate superproject in %s" % (self.manifestFile)
1503 )
1504 remote_name = node.getAttribute("remote")
1505 if not remote_name:
1506 remote = self._default.remote
1507 else:
1508 remote = self._get_remote(node)
1509 if remote is None:
1510 raise ManifestParseError(
1511 "no remote for superproject %s within %s"
1512 % (name, self.manifestFile)
1513 )
1514 revision = node.getAttribute("revision") or remote.revision
1515 if not revision:
1516 revision = self._default.revisionExpr
1517 if not revision:
1518 raise ManifestParseError(
1519 "no revision for superproject %s within %s"
1520 % (name, self.manifestFile)
1521 )
1522 self._superproject = Superproject(
1523 self,
1524 name=name,
1525 remote=remote.ToRemoteSpec(name),
1526 revision=revision,
1527 )
1528 if node.nodeName == "contactinfo":
1529 bugurl = self._reqatt(node, "bugurl")
1530 # This element can be repeated, later entries will clobber
1531 # earlier ones.
1532 self._contactinfo = ContactInfo(bugurl)
1533
1534 if node.nodeName == "remove-project":
Fredrik de Grootbe71c2f2023-05-31 16:56:34 +02001535 name = node.getAttribute("name")
1536 path = node.getAttribute("path")
Gavin Makea2e3302023-03-11 06:46:20 +00001537
Fredrik de Grootbe71c2f2023-05-31 16:56:34 +02001538 # Name or path needed.
1539 if not name and not path:
1540 raise ManifestParseError(
1541 "remove-project must have name and/or path"
1542 )
Gavin Makea2e3302023-03-11 06:46:20 +00001543
Fredrik de Grootbe71c2f2023-05-31 16:56:34 +02001544 removed_project = ""
1545
1546 # Find and remove projects based on name and/or path.
1547 for projname, projects in list(self._projects.items()):
1548 for p in projects:
1549 if name == projname and not path:
1550 del self._paths[p.relpath]
1551 if not removed_project:
1552 del self._projects[name]
1553 removed_project = name
1554 elif path == p.relpath and (
1555 name == projname or not name
1556 ):
1557 self._projects[projname].remove(p)
1558 del self._paths[p.relpath]
1559 removed_project = p.name
1560
1561 # If the manifest removes the hooks project, treat it as if
1562 # it deleted the repo-hooks element too.
1563 if (
1564 removed_project
1565 and removed_project not in self._projects
1566 and repo_hooks_project == removed_project
1567 ):
1568 repo_hooks_project = None
1569
1570 if not removed_project and not XmlBool(node, "optional", False):
Gavin Makea2e3302023-03-11 06:46:20 +00001571 raise ManifestParseError(
1572 "remove-project element specifies non-existent "
Fredrik de Grootbe71c2f2023-05-31 16:56:34 +02001573 "project: %s" % node.toxml()
Gavin Makea2e3302023-03-11 06:46:20 +00001574 )
1575
1576 # Store repo hooks project information.
1577 if repo_hooks_project:
1578 # Store a reference to the Project.
1579 try:
1580 repo_hooks_projects = self._projects[repo_hooks_project]
1581 except KeyError:
1582 raise ManifestParseError(
1583 "project %s not found for repo-hooks" % (repo_hooks_project)
1584 )
1585
1586 if len(repo_hooks_projects) != 1:
1587 raise ManifestParseError(
1588 "internal error parsing repo-hooks in %s"
1589 % (self.manifestFile)
1590 )
1591 self._repo_hooks_project = repo_hooks_projects[0]
1592 # Store the enabled hooks in the Project object.
1593 self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
1594
1595 def _AddMetaProjectMirror(self, m):
1596 name = None
1597 m_url = m.GetRemote().url
1598 if m_url.endswith("/.git"):
1599 raise ManifestParseError("refusing to mirror %s" % m_url)
1600
1601 if self._default and self._default.remote:
1602 url = self._default.remote.resolvedFetchUrl
1603 if not url.endswith("/"):
1604 url += "/"
1605 if m_url.startswith(url):
1606 remote = self._default.remote
1607 name = m_url[len(url) :]
1608
1609 if name is None:
1610 s = m_url.rindex("/") + 1
1611 manifestUrl = self.manifestProject.config.GetString(
1612 "remote.origin.url"
1613 )
1614 remote = _XmlRemote(
1615 "origin", fetch=m_url[:s], manifestUrl=manifestUrl
1616 )
1617 name = m_url[s:]
1618
1619 if name.endswith(".git"):
1620 name = name[:-4]
Josh Triplett884a3872014-06-12 14:57:29 -07001621
1622 if name not in self._projects:
Gavin Makea2e3302023-03-11 06:46:20 +00001623 m.PreSync()
1624 gitdir = os.path.join(self.topdir, "%s.git" % name)
1625 project = Project(
1626 manifest=self,
1627 name=name,
1628 remote=remote.ToRemoteSpec(name),
1629 gitdir=gitdir,
1630 objdir=gitdir,
1631 worktree=None,
1632 relpath=name or None,
1633 revisionExpr=m.revisionExpr,
1634 revisionId=None,
1635 )
1636 self._projects[project.name] = [project]
1637 self._paths[project.relpath] = project
Josh Triplett884a3872014-06-12 14:57:29 -07001638
Gavin Makea2e3302023-03-11 06:46:20 +00001639 def _ParseRemote(self, node):
1640 """
1641 reads a <remote> element from the manifest file
1642 """
1643 name = self._reqatt(node, "name")
1644 alias = node.getAttribute("alias")
1645 if alias == "":
1646 alias = None
1647 fetch = self._reqatt(node, "fetch")
1648 pushUrl = node.getAttribute("pushurl")
1649 if pushUrl == "":
1650 pushUrl = None
1651 review = node.getAttribute("review")
1652 if review == "":
1653 review = None
1654 revision = node.getAttribute("revision")
1655 if revision == "":
1656 revision = None
1657 manifestUrl = self.manifestProject.config.GetString("remote.origin.url")
1658
1659 remote = _XmlRemote(
1660 name, alias, fetch, pushUrl, manifestUrl, review, revision
1661 )
1662
1663 for n in node.childNodes:
1664 if n.nodeName == "annotation":
1665 self._ParseAnnotation(remote, n)
1666
1667 return remote
1668
1669 def _ParseDefault(self, node):
1670 """
1671 reads a <default> element from the manifest file
1672 """
1673 d = _Default()
1674 d.remote = self._get_remote(node)
1675 d.revisionExpr = node.getAttribute("revision")
1676 if d.revisionExpr == "":
1677 d.revisionExpr = None
1678
1679 d.destBranchExpr = node.getAttribute("dest-branch") or None
1680 d.upstreamExpr = node.getAttribute("upstream") or None
1681
1682 d.sync_j = XmlInt(node, "sync-j", None)
1683 if d.sync_j is not None and d.sync_j <= 0:
1684 raise ManifestParseError(
1685 '%s: sync-j must be greater than 0, not "%s"'
1686 % (self.manifestFile, d.sync_j)
1687 )
1688
1689 d.sync_c = XmlBool(node, "sync-c", False)
1690 d.sync_s = XmlBool(node, "sync-s", False)
1691 d.sync_tags = XmlBool(node, "sync-tags", True)
1692 return d
1693
1694 def _ParseNotice(self, node):
1695 """
1696 reads a <notice> element from the manifest file
1697
1698 The <notice> element is distinct from other tags in the XML in that the
1699 data is conveyed between the start and end tag (it's not an
1700 empty-element tag).
1701
1702 The white space (carriage returns, indentation) for the notice element
1703 is relevant and is parsed in a way that is based on how python
1704 docstrings work. In fact, the code is remarkably similar to here:
1705 http://www.python.org/dev/peps/pep-0257/
1706 """
1707 # Get the data out of the node...
1708 notice = node.childNodes[0].data
1709
1710 # Figure out minimum indentation, skipping the first line (the same line
1711 # as the <notice> tag)...
1712 minIndent = sys.maxsize
1713 lines = notice.splitlines()
1714 for line in lines[1:]:
1715 lstrippedLine = line.lstrip()
1716 if lstrippedLine:
1717 indent = len(line) - len(lstrippedLine)
1718 minIndent = min(indent, minIndent)
1719
1720 # Strip leading / trailing blank lines and also indentation.
1721 cleanLines = [lines[0].strip()]
1722 for line in lines[1:]:
1723 cleanLines.append(line[minIndent:].rstrip())
1724
1725 # Clear completely blank lines from front and back...
1726 while cleanLines and not cleanLines[0]:
1727 del cleanLines[0]
1728 while cleanLines and not cleanLines[-1]:
1729 del cleanLines[-1]
1730
1731 return "\n".join(cleanLines)
1732
1733 def _ParseSubmanifest(self, node):
1734 """Reads a <submanifest> element from the manifest file."""
1735 name = self._reqatt(node, "name")
1736 remote = node.getAttribute("remote")
1737 if remote == "":
1738 remote = None
1739 project = node.getAttribute("project")
1740 if project == "":
1741 project = None
1742 revision = node.getAttribute("revision")
1743 if revision == "":
1744 revision = None
1745 manifestName = node.getAttribute("manifest-name")
1746 if manifestName == "":
1747 manifestName = None
1748 groups = ""
1749 if node.hasAttribute("groups"):
1750 groups = node.getAttribute("groups")
1751 groups = self._ParseList(groups)
1752 default_groups = self._ParseList(node.getAttribute("default-groups"))
1753 path = node.getAttribute("path")
1754 if path == "":
1755 path = None
1756 if revision:
1757 msg = self._CheckLocalPath(revision.split("/")[-1])
1758 if msg:
1759 raise ManifestInvalidPathError(
1760 '<submanifest> invalid "revision": %s: %s'
1761 % (revision, msg)
1762 )
1763 else:
1764 msg = self._CheckLocalPath(name)
1765 if msg:
1766 raise ManifestInvalidPathError(
1767 '<submanifest> invalid "name": %s: %s' % (name, msg)
1768 )
LaMont Jonescc879a92021-11-18 22:40:18 +00001769 else:
Gavin Makea2e3302023-03-11 06:46:20 +00001770 msg = self._CheckLocalPath(path)
1771 if msg:
1772 raise ManifestInvalidPathError(
1773 '<submanifest> invalid "path": %s: %s' % (path, msg)
1774 )
Josh Triplett884a3872014-06-12 14:57:29 -07001775
Gavin Makea2e3302023-03-11 06:46:20 +00001776 submanifest = _XmlSubmanifest(
1777 name,
1778 remote,
1779 project,
1780 revision,
1781 manifestName,
1782 groups,
1783 default_groups,
1784 path,
1785 self,
1786 )
Michael Kelly2f3c3312020-07-21 19:40:38 -07001787
Gavin Makea2e3302023-03-11 06:46:20 +00001788 for n in node.childNodes:
1789 if n.nodeName == "annotation":
1790 self._ParseAnnotation(submanifest, n)
Michael Kelly2f3c3312020-07-21 19:40:38 -07001791
Gavin Makea2e3302023-03-11 06:46:20 +00001792 return submanifest
Michael Kelly37c21c22020-06-13 02:10:40 -07001793
Gavin Makea2e3302023-03-11 06:46:20 +00001794 def _JoinName(self, parent_name, name):
1795 return os.path.join(parent_name, name)
Doug Anderson37282b42011-03-04 11:54:18 -08001796
Gavin Makea2e3302023-03-11 06:46:20 +00001797 def _UnjoinName(self, parent_name, name):
1798 return os.path.relpath(name, parent_name)
1799
1800 def _ParseProject(self, node, parent=None, **extra_proj_attrs):
1801 """
1802 reads a <project> element from the manifest file
1803 """
1804 name = self._reqatt(node, "name")
1805 msg = self._CheckLocalPath(name, dir_ok=True)
1806 if msg:
1807 raise ManifestInvalidPathError(
1808 '<project> invalid "name": %s: %s' % (name, msg)
1809 )
1810 if parent:
1811 name = self._JoinName(parent.name, name)
1812
1813 remote = self._get_remote(node)
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001814 if remote is None:
Gavin Makea2e3302023-03-11 06:46:20 +00001815 remote = self._default.remote
1816 if remote is None:
1817 raise ManifestParseError(
1818 "no remote for project %s within %s" % (name, self.manifestFile)
1819 )
Raman Tenneti993af5e2021-05-12 12:00:31 -07001820
Gavin Makea2e3302023-03-11 06:46:20 +00001821 revisionExpr = node.getAttribute("revision") or remote.revision
1822 if not revisionExpr:
1823 revisionExpr = self._default.revisionExpr
1824 if not revisionExpr:
1825 raise ManifestParseError(
1826 "no revision for project %s within %s"
1827 % (name, self.manifestFile)
1828 )
David Jamesb8433df2014-01-30 10:11:17 -08001829
Gavin Makea2e3302023-03-11 06:46:20 +00001830 path = node.getAttribute("path")
1831 if not path:
1832 path = name
Julien Camperguedd654222014-01-09 16:21:37 +01001833 else:
Gavin Makea2e3302023-03-11 06:46:20 +00001834 # NB: The "." project is handled specially in
1835 # Project.Sync_LocalHalf.
1836 msg = self._CheckLocalPath(path, dir_ok=True, cwd_dot_ok=True)
1837 if msg:
1838 raise ManifestInvalidPathError(
1839 '<project> invalid "path": %s: %s' % (path, msg)
1840 )
Julien Camperguedd654222014-01-09 16:21:37 +01001841
Gavin Makea2e3302023-03-11 06:46:20 +00001842 rebase = XmlBool(node, "rebase", True)
1843 sync_c = XmlBool(node, "sync-c", False)
1844 sync_s = XmlBool(node, "sync-s", self._default.sync_s)
1845 sync_tags = XmlBool(node, "sync-tags", self._default.sync_tags)
Julien Camperguedd654222014-01-09 16:21:37 +01001846
Gavin Makea2e3302023-03-11 06:46:20 +00001847 clone_depth = XmlInt(node, "clone-depth")
1848 if clone_depth is not None and clone_depth <= 0:
1849 raise ManifestParseError(
1850 '%s: clone-depth must be greater than 0, not "%s"'
1851 % (self.manifestFile, clone_depth)
1852 )
1853
1854 dest_branch = (
1855 node.getAttribute("dest-branch") or self._default.destBranchExpr
1856 )
1857
1858 upstream = node.getAttribute("upstream") or self._default.upstreamExpr
1859
1860 groups = ""
1861 if node.hasAttribute("groups"):
1862 groups = node.getAttribute("groups")
1863 groups = self._ParseList(groups)
1864
1865 if parent is None:
1866 (
1867 relpath,
1868 worktree,
1869 gitdir,
1870 objdir,
1871 use_git_worktrees,
1872 ) = self.GetProjectPaths(name, path, remote.name)
1873 else:
1874 use_git_worktrees = False
1875 relpath, worktree, gitdir, objdir = self.GetSubprojectPaths(
1876 parent, name, path
1877 )
1878
1879 default_groups = ["all", "name:%s" % name, "path:%s" % relpath]
1880 groups.extend(set(default_groups).difference(groups))
1881
1882 if self.IsMirror and node.hasAttribute("force-path"):
1883 if XmlBool(node, "force-path", False):
1884 gitdir = os.path.join(self.topdir, "%s.git" % path)
1885
1886 project = Project(
1887 manifest=self,
1888 name=name,
1889 remote=remote.ToRemoteSpec(name),
1890 gitdir=gitdir,
1891 objdir=objdir,
1892 worktree=worktree,
1893 relpath=relpath,
1894 revisionExpr=revisionExpr,
1895 revisionId=None,
1896 rebase=rebase,
1897 groups=groups,
1898 sync_c=sync_c,
1899 sync_s=sync_s,
1900 sync_tags=sync_tags,
1901 clone_depth=clone_depth,
1902 upstream=upstream,
1903 parent=parent,
1904 dest_branch=dest_branch,
1905 use_git_worktrees=use_git_worktrees,
1906 **extra_proj_attrs,
1907 )
1908
1909 for n in node.childNodes:
1910 if n.nodeName == "copyfile":
1911 self._ParseCopyFile(project, n)
1912 if n.nodeName == "linkfile":
1913 self._ParseLinkFile(project, n)
1914 if n.nodeName == "annotation":
1915 self._ParseAnnotation(project, n)
1916 if n.nodeName == "project":
1917 project.subprojects.append(
1918 self._ParseProject(n, parent=project)
1919 )
1920
1921 return project
1922
1923 def GetProjectPaths(self, name, path, remote):
1924 """Return the paths for a project.
1925
1926 Args:
1927 name: a string, the name of the project.
1928 path: a string, the path of the project.
1929 remote: a string, the remote.name of the project.
1930
1931 Returns:
1932 A tuple of (relpath, worktree, gitdir, objdir, use_git_worktrees)
1933 for the project with |name| and |path|.
1934 """
1935 # The manifest entries might have trailing slashes. Normalize them to
1936 # avoid unexpected filesystem behavior since we do string concatenation
1937 # below.
1938 path = path.rstrip("/")
1939 name = name.rstrip("/")
1940 remote = remote.rstrip("/")
1941 use_git_worktrees = False
1942 use_remote_name = self.is_multimanifest
1943 relpath = path
1944 if self.IsMirror:
1945 worktree = None
1946 gitdir = os.path.join(self.topdir, "%s.git" % name)
1947 objdir = gitdir
1948 else:
1949 if use_remote_name:
1950 namepath = os.path.join(remote, f"{name}.git")
1951 else:
1952 namepath = f"{name}.git"
1953 worktree = os.path.join(self.topdir, path).replace("\\", "/")
1954 gitdir = os.path.join(self.subdir, "projects", "%s.git" % path)
1955 # We allow people to mix git worktrees & non-git worktrees for now.
1956 # This allows for in situ migration of repo clients.
1957 if os.path.exists(gitdir) or not self.UseGitWorktrees:
1958 objdir = os.path.join(self.repodir, "project-objects", namepath)
1959 else:
1960 use_git_worktrees = True
1961 gitdir = os.path.join(self.repodir, "worktrees", namepath)
1962 objdir = gitdir
1963 return relpath, worktree, gitdir, objdir, use_git_worktrees
1964
1965 def GetProjectsWithName(self, name, all_manifests=False):
1966 """All projects with |name|.
1967
1968 Args:
1969 name: a string, the name of the project.
1970 all_manifests: a boolean, if True, then all manifests are searched.
1971 If False, then only this manifest is searched.
1972
1973 Returns:
1974 A list of Project instances with name |name|.
1975 """
1976 if all_manifests:
1977 return list(
1978 itertools.chain.from_iterable(
1979 x._projects.get(name, []) for x in self.all_manifests
1980 )
1981 )
1982 return self._projects.get(name, [])
1983
1984 def GetSubprojectName(self, parent, submodule_path):
1985 return os.path.join(parent.name, submodule_path)
1986
1987 def _JoinRelpath(self, parent_relpath, relpath):
1988 return os.path.join(parent_relpath, relpath)
1989
1990 def _UnjoinRelpath(self, parent_relpath, relpath):
1991 return os.path.relpath(relpath, parent_relpath)
1992
1993 def GetSubprojectPaths(self, parent, name, path):
1994 # The manifest entries might have trailing slashes. Normalize them to
1995 # avoid unexpected filesystem behavior since we do string concatenation
1996 # below.
1997 path = path.rstrip("/")
1998 name = name.rstrip("/")
1999 relpath = self._JoinRelpath(parent.relpath, path)
2000 gitdir = os.path.join(parent.gitdir, "subprojects", "%s.git" % path)
2001 objdir = os.path.join(
2002 parent.gitdir, "subproject-objects", "%s.git" % name
2003 )
2004 if self.IsMirror:
2005 worktree = None
2006 else:
2007 worktree = os.path.join(parent.worktree, path).replace("\\", "/")
2008 return relpath, worktree, gitdir, objdir
2009
2010 @staticmethod
2011 def _CheckLocalPath(path, dir_ok=False, cwd_dot_ok=False):
2012 """Verify |path| is reasonable for use in filesystem paths.
2013
2014 Used with <copyfile> & <linkfile> & <project> elements.
2015
2016 This only validates the |path| in isolation: it does not check against
2017 the current filesystem state. Thus it is suitable as a first-past in a
2018 parser.
2019
2020 It enforces a number of constraints:
2021 * No empty paths.
2022 * No "~" in paths.
2023 * No Unicode codepoints that filesystems might elide when normalizing.
2024 * No relative path components like "." or "..".
2025 * No absolute paths.
2026 * No ".git" or ".repo*" path components.
2027
2028 Args:
2029 path: The path name to validate.
2030 dir_ok: Whether |path| may force a directory (e.g. end in a /).
2031 cwd_dot_ok: Whether |path| may be just ".".
2032
2033 Returns:
2034 None if |path| is OK, a failure message otherwise.
2035 """
2036 if not path:
2037 return "empty paths not allowed"
2038
2039 if "~" in path:
2040 return "~ not allowed (due to 8.3 filenames on Windows filesystems)"
2041
2042 path_codepoints = set(path)
2043
2044 # Some filesystems (like Apple's HFS+) try to normalize Unicode
2045 # codepoints which means there are alternative names for ".git". Reject
2046 # paths with these in it as there shouldn't be any reasonable need for
2047 # them here. The set of codepoints here was cribbed from jgit's
2048 # implementation:
2049 # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
2050 BAD_CODEPOINTS = {
2051 "\u200C", # ZERO WIDTH NON-JOINER
2052 "\u200D", # ZERO WIDTH JOINER
2053 "\u200E", # LEFT-TO-RIGHT MARK
2054 "\u200F", # RIGHT-TO-LEFT MARK
2055 "\u202A", # LEFT-TO-RIGHT EMBEDDING
2056 "\u202B", # RIGHT-TO-LEFT EMBEDDING
2057 "\u202C", # POP DIRECTIONAL FORMATTING
2058 "\u202D", # LEFT-TO-RIGHT OVERRIDE
2059 "\u202E", # RIGHT-TO-LEFT OVERRIDE
2060 "\u206A", # INHIBIT SYMMETRIC SWAPPING
2061 "\u206B", # ACTIVATE SYMMETRIC SWAPPING
2062 "\u206C", # INHIBIT ARABIC FORM SHAPING
2063 "\u206D", # ACTIVATE ARABIC FORM SHAPING
2064 "\u206E", # NATIONAL DIGIT SHAPES
2065 "\u206F", # NOMINAL DIGIT SHAPES
2066 "\uFEFF", # ZERO WIDTH NO-BREAK SPACE
2067 }
2068 if BAD_CODEPOINTS & path_codepoints:
2069 # This message is more expansive than reality, but should be fine.
2070 return "Unicode combining characters not allowed"
2071
2072 # Reject newlines as there shouldn't be any legitmate use for them,
2073 # they'll be confusing to users, and they can easily break tools that
2074 # expect to be able to iterate over newline delimited lists. This even
2075 # applies to our own code like .repo/project.list.
2076 if {"\r", "\n"} & path_codepoints:
2077 return "Newlines not allowed"
2078
2079 # Assume paths might be used on case-insensitive filesystems.
2080 path = path.lower()
2081
2082 # Split up the path by its components. We can't use os.path.sep
2083 # exclusively as some platforms (like Windows) will convert / to \ and
2084 # that bypasses all our constructed logic here. Especially since
2085 # manifest authors only use / in their paths.
2086 resep = re.compile(r"[/%s]" % re.escape(os.path.sep))
2087 # Strip off trailing slashes as those only produce '' elements, and we
2088 # use parts to look for individual bad components.
2089 parts = resep.split(path.rstrip("/"))
2090
2091 # Some people use src="." to create stable links to projects. Lets
2092 # allow that but reject all other uses of "." to keep things simple.
2093 if not cwd_dot_ok or parts != ["."]:
2094 for part in set(parts):
2095 if part in {".", "..", ".git"} or part.startswith(".repo"):
2096 return "bad component: %s" % (part,)
2097
2098 if not dir_ok and resep.match(path[-1]):
2099 return "dirs not allowed"
2100
2101 # NB: The two abspath checks here are to handle platforms with multiple
2102 # filesystem path styles (e.g. Windows).
2103 norm = os.path.normpath(path)
2104 if (
2105 norm == ".."
2106 or (
2107 len(norm) >= 3
2108 and norm.startswith("..")
2109 and resep.match(norm[0])
2110 )
2111 or os.path.isabs(norm)
2112 or norm.startswith("/")
2113 ):
2114 return "path cannot be outside"
2115
2116 @classmethod
2117 def _ValidateFilePaths(cls, element, src, dest):
2118 """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
2119
2120 We verify the path independent of any filesystem state as we won't have
2121 a checkout available to compare to. i.e. This is for parsing validation
2122 purposes only.
2123
2124 We'll do full/live sanity checking before we do the actual filesystem
2125 modifications in _CopyFile/_LinkFile/etc...
2126 """
2127 # |dest| is the file we write to or symlink we create.
2128 # It is relative to the top of the repo client checkout.
2129 msg = cls._CheckLocalPath(dest)
2130 if msg:
2131 raise ManifestInvalidPathError(
2132 '<%s> invalid "dest": %s: %s' % (element, dest, msg)
2133 )
2134
2135 # |src| is the file we read from or path we point to for symlinks.
2136 # It is relative to the top of the git project checkout.
2137 is_linkfile = element == "linkfile"
2138 msg = cls._CheckLocalPath(
2139 src, dir_ok=is_linkfile, cwd_dot_ok=is_linkfile
2140 )
2141 if msg:
2142 raise ManifestInvalidPathError(
2143 '<%s> invalid "src": %s: %s' % (element, src, msg)
2144 )
2145
2146 def _ParseCopyFile(self, project, node):
2147 src = self._reqatt(node, "src")
2148 dest = self._reqatt(node, "dest")
2149 if not self.IsMirror:
2150 # src is project relative;
2151 # dest is relative to the top of the tree.
2152 # We only validate paths if we actually plan to process them.
2153 self._ValidateFilePaths("copyfile", src, dest)
2154 project.AddCopyFile(src, dest, self.topdir)
2155
2156 def _ParseLinkFile(self, project, node):
2157 src = self._reqatt(node, "src")
2158 dest = self._reqatt(node, "dest")
2159 if not self.IsMirror:
2160 # src is project relative;
2161 # dest is relative to the top of the tree.
2162 # We only validate paths if we actually plan to process them.
2163 self._ValidateFilePaths("linkfile", src, dest)
2164 project.AddLinkFile(src, dest, self.topdir)
2165
2166 def _ParseAnnotation(self, element, node):
2167 name = self._reqatt(node, "name")
2168 value = self._reqatt(node, "value")
2169 try:
2170 keep = self._reqatt(node, "keep").lower()
2171 except ManifestParseError:
2172 keep = "true"
2173 if keep != "true" and keep != "false":
2174 raise ManifestParseError(
2175 'optional "keep" attribute must be ' '"true" or "false"'
2176 )
2177 element.AddAnnotation(name, value, keep)
2178
2179 def _get_remote(self, node):
2180 name = node.getAttribute("remote")
2181 if not name:
2182 return None
2183
2184 v = self._remotes.get(name)
2185 if not v:
2186 raise ManifestParseError(
2187 "remote %s not defined in %s" % (name, self.manifestFile)
2188 )
2189 return v
2190
2191 def _reqatt(self, node, attname):
2192 """
2193 reads a required attribute from the node.
2194 """
2195 v = node.getAttribute(attname)
2196 if not v:
2197 raise ManifestParseError(
2198 "no %s in <%s> within %s"
2199 % (attname, node.nodeName, self.manifestFile)
2200 )
2201 return v
2202
2203 def projectsDiff(self, manifest):
2204 """return the projects differences between two manifests.
2205
2206 The diff will be from self to given manifest.
2207
2208 """
2209 fromProjects = self.paths
2210 toProjects = manifest.paths
2211
2212 fromKeys = sorted(fromProjects.keys())
2213 toKeys = sorted(toProjects.keys())
2214
2215 diff = {
2216 "added": [],
2217 "removed": [],
2218 "missing": [],
2219 "changed": [],
2220 "unreachable": [],
2221 }
2222
2223 for proj in fromKeys:
2224 if proj not in toKeys:
2225 diff["removed"].append(fromProjects[proj])
2226 elif not fromProjects[proj].Exists:
2227 diff["missing"].append(toProjects[proj])
2228 toKeys.remove(proj)
2229 else:
2230 fromProj = fromProjects[proj]
2231 toProj = toProjects[proj]
2232 try:
2233 fromRevId = fromProj.GetCommitRevisionId()
2234 toRevId = toProj.GetCommitRevisionId()
2235 except ManifestInvalidRevisionError:
2236 diff["unreachable"].append((fromProj, toProj))
2237 else:
2238 if fromRevId != toRevId:
2239 diff["changed"].append((fromProj, toProj))
2240 toKeys.remove(proj)
2241
2242 for proj in toKeys:
2243 diff["added"].append(toProjects[proj])
2244
2245 return diff
Simran Basib9a1b732015-08-20 12:19:28 -07002246
2247
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04002248class RepoClient(XmlManifest):
Gavin Makea2e3302023-03-11 06:46:20 +00002249 """Manages a repo client checkout."""
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04002250
Gavin Makea2e3302023-03-11 06:46:20 +00002251 def __init__(
2252 self, repodir, manifest_file=None, submanifest_path="", **kwargs
2253 ):
2254 """Initialize.
LaMont Jonesff6b1da2022-06-01 21:03:34 +00002255
Gavin Makea2e3302023-03-11 06:46:20 +00002256 Args:
2257 repodir: Path to the .repo/ dir for holding all internal checkout
2258 state. It must be in the top directory of the repo client
2259 checkout.
2260 manifest_file: Full path to the manifest file to parse. This will
2261 usually be |repodir|/|MANIFEST_FILE_NAME|.
2262 submanifest_path: The submanifest root relative to the repo root.
2263 **kwargs: Additional keyword arguments, passed to XmlManifest.
2264 """
2265 self.isGitcClient = False
2266 submanifest_path = submanifest_path or ""
2267 if submanifest_path:
2268 self._CheckLocalPath(submanifest_path)
2269 prefix = os.path.join(repodir, SUBMANIFEST_DIR, submanifest_path)
2270 else:
2271 prefix = repodir
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04002272
Gavin Makea2e3302023-03-11 06:46:20 +00002273 if os.path.exists(os.path.join(prefix, LOCAL_MANIFEST_NAME)):
2274 print(
2275 "error: %s is not supported; put local manifests in `%s` "
2276 "instead"
2277 % (
2278 LOCAL_MANIFEST_NAME,
2279 os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME),
2280 ),
2281 file=sys.stderr,
2282 )
2283 sys.exit(1)
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04002284
Gavin Makea2e3302023-03-11 06:46:20 +00002285 if manifest_file is None:
2286 manifest_file = os.path.join(prefix, MANIFEST_FILE_NAME)
2287 local_manifests = os.path.abspath(
2288 os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME)
2289 )
2290 super().__init__(
2291 repodir,
2292 manifest_file,
2293 local_manifests,
2294 submanifest_path=submanifest_path,
2295 **kwargs,
2296 )
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04002297
Gavin Makea2e3302023-03-11 06:46:20 +00002298 # TODO: Completely separate manifest logic out of the client.
2299 self.manifest = self