blob: 80e563a5d6b14c0baa0938a8e36e95a5efb1d735 [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
David Pursehouse59bbb582013-05-17 10:49:33 +090021import xml.dom.minidom
Mike Frysingeracf63b22019-06-13 02:24:21 -040022import urllib.parse
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070023
Daniel Kutik035f22a2022-12-13 12:34:23 +010024from git_config import GitConfig
David Pursehousee00aa6b2012-09-11 14:33:51 +090025from git_refs import R_HEADS, HEAD
LaMont Jonesd56e2eb2022-04-07 18:14:46 +000026from git_superproject import Superproject
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070027import platform_utils
Gavin Makea2e3302023-03-11 06:46:20 +000028from project import (
29 Annotation,
30 RemoteSpec,
31 Project,
32 RepoProject,
33 ManifestProject,
34)
35from error import (
36 ManifestParseError,
37 ManifestInvalidPathError,
38 ManifestInvalidRevisionError,
39)
Raman Tenneti993af5e2021-05-12 12:00:31 -070040from wrapper import Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070041
Gavin Makea2e3302023-03-11 06:46:20 +000042MANIFEST_FILE_NAME = "manifest.xml"
43LOCAL_MANIFEST_NAME = "local_manifest.xml"
44LOCAL_MANIFESTS_DIR_NAME = "local_manifests"
45SUBMANIFEST_DIR = "submanifests"
LaMont Jonescc879a92021-11-18 22:40:18 +000046# Limit submanifests to an arbitrary depth for loop detection.
47MAX_SUBMANIFEST_DEPTH = 8
LaMont Jonesb308db12022-02-25 17:05:21 +000048# Add all projects from sub manifest into a group.
Gavin Makea2e3302023-03-11 06:46:20 +000049SUBMANIFEST_GROUP_PREFIX = "submanifest:"
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070050
Raman Tenneti78f4dd32021-06-07 13:27:37 -070051# Add all projects from local manifest into a group.
Gavin Makea2e3302023-03-11 06:46:20 +000052LOCAL_MANIFEST_GROUP_PREFIX = "local:"
Raman Tenneti78f4dd32021-06-07 13:27:37 -070053
Raman Tenneti993af5e2021-05-12 12:00:31 -070054# ContactInfo has the self-registered bug url, supplied by the manifest authors.
Gavin Makea2e3302023-03-11 06:46:20 +000055ContactInfo = collections.namedtuple("ContactInfo", "bugurl")
Raman Tenneti993af5e2021-05-12 12:00:31 -070056
Anthony Kingcb07ba72015-03-28 23:26:04 +000057# urljoin gets confused if the scheme is not known.
Gavin Makea2e3302023-03-11 06:46:20 +000058urllib.parse.uses_relative.extend(
59 ["ssh", "git", "persistent-https", "sso", "rpc"]
60)
61urllib.parse.uses_netloc.extend(
62 ["ssh", "git", "persistent-https", "sso", "rpc"]
63)
Conley Owensdb728cd2011-09-26 16:34:01 -070064
David Pursehouse819827a2020-02-12 15:20:19 +090065
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050066def XmlBool(node, attr, default=None):
Gavin Makea2e3302023-03-11 06:46:20 +000067 """Determine boolean value of |node|'s |attr|.
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050068
Gavin Makea2e3302023-03-11 06:46:20 +000069 Invalid values will issue a non-fatal warning.
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050070
Gavin Makea2e3302023-03-11 06:46:20 +000071 Args:
72 node: XML node whose attributes we access.
73 attr: The attribute to access.
74 default: If the attribute is not set (value is empty), then use this.
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050075
Gavin Makea2e3302023-03-11 06:46:20 +000076 Returns:
77 True if the attribute is a valid string representing true.
78 False if the attribute is a valid string representing false.
79 |default| otherwise.
80 """
81 value = node.getAttribute(attr)
82 s = value.lower()
83 if s == "":
84 return default
85 elif s in {"yes", "true", "1"}:
86 return True
87 elif s in {"no", "false", "0"}:
88 return False
89 else:
90 print(
91 'warning: manifest: %s="%s": ignoring invalid XML boolean'
92 % (attr, value),
93 file=sys.stderr,
94 )
95 return default
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050096
97
98def XmlInt(node, attr, default=None):
Gavin Makea2e3302023-03-11 06:46:20 +000099 """Determine integer value of |node|'s |attr|.
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500100
Gavin Makea2e3302023-03-11 06:46:20 +0000101 Args:
102 node: XML node whose attributes we access.
103 attr: The attribute to access.
104 default: If the attribute is not set (value is empty), then use this.
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500105
Gavin Makea2e3302023-03-11 06:46:20 +0000106 Returns:
107 The number if the attribute is a valid number.
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500108
Gavin Makea2e3302023-03-11 06:46:20 +0000109 Raises:
110 ManifestParseError: The number is invalid.
111 """
112 value = node.getAttribute(attr)
113 if not value:
114 return default
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500115
Gavin Makea2e3302023-03-11 06:46:20 +0000116 try:
117 return int(value)
118 except ValueError:
119 raise ManifestParseError(
120 'manifest: invalid %s="%s" integer' % (attr, value)
121 )
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500122
123
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700124class _Default(object):
Gavin Makea2e3302023-03-11 06:46:20 +0000125 """Project defaults within the manifest."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700126
Gavin Makea2e3302023-03-11 06:46:20 +0000127 revisionExpr = None
128 destBranchExpr = None
129 upstreamExpr = None
130 remote = None
131 sync_j = None
132 sync_c = False
133 sync_s = False
134 sync_tags = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700135
Gavin Makea2e3302023-03-11 06:46:20 +0000136 def __eq__(self, other):
137 if not isinstance(other, _Default):
138 return False
139 return self.__dict__ == other.__dict__
Julien Campergue74879922013-10-09 14:38:46 +0200140
Gavin Makea2e3302023-03-11 06:46:20 +0000141 def __ne__(self, other):
142 if not isinstance(other, _Default):
143 return True
144 return self.__dict__ != other.__dict__
Julien Campergue74879922013-10-09 14:38:46 +0200145
David Pursehouse819827a2020-02-12 15:20:19 +0900146
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700147class _XmlRemote(object):
Gavin Makea2e3302023-03-11 06:46:20 +0000148 def __init__(
149 self,
150 name,
151 alias=None,
152 fetch=None,
153 pushUrl=None,
154 manifestUrl=None,
155 review=None,
156 revision=None,
157 ):
158 self.name = name
159 self.fetchUrl = fetch
160 self.pushUrl = pushUrl
161 self.manifestUrl = manifestUrl
162 self.remoteAlias = alias
163 self.reviewUrl = review
164 self.revision = revision
165 self.resolvedFetchUrl = self._resolveFetchUrl()
166 self.annotations = []
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700167
Gavin Makea2e3302023-03-11 06:46:20 +0000168 def __eq__(self, other):
169 if not isinstance(other, _XmlRemote):
170 return False
171 return (
172 sorted(self.annotations) == sorted(other.annotations)
173 and self.name == other.name
174 and self.fetchUrl == other.fetchUrl
175 and self.pushUrl == other.pushUrl
176 and self.remoteAlias == other.remoteAlias
177 and self.reviewUrl == other.reviewUrl
178 and self.revision == other.revision
179 )
David Pursehouse717ece92012-11-13 08:49:16 +0900180
Gavin Makea2e3302023-03-11 06:46:20 +0000181 def __ne__(self, other):
182 return not self.__eq__(other)
David Pursehouse717ece92012-11-13 08:49:16 +0900183
Gavin Makea2e3302023-03-11 06:46:20 +0000184 def _resolveFetchUrl(self):
185 if self.fetchUrl is None:
186 return ""
187 url = self.fetchUrl.rstrip("/")
188 manifestUrl = self.manifestUrl.rstrip("/")
189 # urljoin will gets confused over quite a few things. The ones we care
190 # about here are:
191 # * no scheme in the base url, like <hostname:port>
192 # We handle no scheme by replacing it with an obscure protocol, gopher
193 # and then replacing it with the original when we are done.
Anthony Kingcb07ba72015-03-28 23:26:04 +0000194
Gavin Makea2e3302023-03-11 06:46:20 +0000195 if manifestUrl.find(":") != manifestUrl.find("/") - 1:
196 url = urllib.parse.urljoin("gopher://" + manifestUrl, url)
197 url = re.sub(r"^gopher://", "", url)
198 else:
199 url = urllib.parse.urljoin(manifestUrl, url)
200 return url
Conley Owensceea3682011-10-20 10:45:47 -0700201
Gavin Makea2e3302023-03-11 06:46:20 +0000202 def ToRemoteSpec(self, projectName):
203 fetchUrl = self.resolvedFetchUrl.rstrip("/")
204 url = fetchUrl + "/" + projectName
205 remoteName = self.name
206 if self.remoteAlias:
207 remoteName = self.remoteAlias
208 return RemoteSpec(
209 remoteName,
210 url=url,
211 pushUrl=self.pushUrl,
212 review=self.reviewUrl,
213 orig_name=self.name,
214 fetchUrl=self.fetchUrl,
215 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700216
Gavin Makea2e3302023-03-11 06:46:20 +0000217 def AddAnnotation(self, name, value, keep):
218 self.annotations.append(Annotation(name, value, keep))
Jack Neus6ea0cae2021-07-20 20:52:33 +0000219
David Pursehouse819827a2020-02-12 15:20:19 +0900220
LaMont Jonescc879a92021-11-18 22:40:18 +0000221class _XmlSubmanifest:
Gavin Makea2e3302023-03-11 06:46:20 +0000222 """Manage the <submanifest> element specified in the manifest.
LaMont Jonescc879a92021-11-18 22:40:18 +0000223
Gavin Makea2e3302023-03-11 06:46:20 +0000224 Attributes:
225 name: a string, the name for this submanifest.
226 remote: a string, the remote.name for this submanifest.
227 project: a string, the name of the manifest project.
228 revision: a string, the commitish.
229 manifestName: a string, the submanifest file name.
230 groups: a list of strings, the groups to add to all projects in the
231 submanifest.
232 default_groups: a list of strings, the default groups to sync.
233 path: a string, the relative path for the submanifest checkout.
234 parent: an XmlManifest, the parent manifest.
235 annotations: (derived) a list of annotations.
236 present: (derived) a boolean, whether the sub manifest file is present.
237 """
LaMont Jonescc879a92021-11-18 22:40:18 +0000238
Gavin Makea2e3302023-03-11 06:46:20 +0000239 def __init__(
240 self,
241 name,
242 remote=None,
243 project=None,
244 revision=None,
245 manifestName=None,
246 groups=None,
247 default_groups=None,
248 path=None,
249 parent=None,
250 ):
251 self.name = name
252 self.remote = remote
253 self.project = project
254 self.revision = revision
255 self.manifestName = manifestName
256 self.groups = groups
257 self.default_groups = default_groups
258 self.path = path
259 self.parent = parent
260 self.annotations = []
261 outer_client = parent._outer_client or parent
262 if self.remote and not self.project:
263 raise ManifestParseError(
264 f"Submanifest {name}: must specify project when remote is "
265 "given."
266 )
267 # Construct the absolute path to the manifest file using the parent's
268 # method, so that we can correctly create our repo_client.
269 manifestFile = parent.SubmanifestInfoDir(
270 os.path.join(parent.path_prefix, self.relpath),
271 os.path.join("manifests", manifestName or "default.xml"),
272 )
273 linkFile = parent.SubmanifestInfoDir(
274 os.path.join(parent.path_prefix, self.relpath), MANIFEST_FILE_NAME
275 )
276 self.repo_client = RepoClient(
277 parent.repodir,
278 linkFile,
279 parent_groups=",".join(groups) or "",
280 submanifest_path=self.relpath,
281 outer_client=outer_client,
282 default_groups=default_groups,
283 )
LaMont Jonescc879a92021-11-18 22:40:18 +0000284
Gavin Makea2e3302023-03-11 06:46:20 +0000285 self.present = os.path.exists(manifestFile)
LaMont Jonescc879a92021-11-18 22:40:18 +0000286
Gavin Makea2e3302023-03-11 06:46:20 +0000287 def __eq__(self, other):
288 if not isinstance(other, _XmlSubmanifest):
289 return False
290 return (
291 self.name == other.name
292 and self.remote == other.remote
293 and self.project == other.project
294 and self.revision == other.revision
295 and self.manifestName == other.manifestName
296 and self.groups == other.groups
297 and self.default_groups == other.default_groups
298 and self.path == other.path
299 and sorted(self.annotations) == sorted(other.annotations)
300 )
LaMont Jonescc879a92021-11-18 22:40:18 +0000301
Gavin Makea2e3302023-03-11 06:46:20 +0000302 def __ne__(self, other):
303 return not self.__eq__(other)
LaMont Jonescc879a92021-11-18 22:40:18 +0000304
Gavin Makea2e3302023-03-11 06:46:20 +0000305 def ToSubmanifestSpec(self):
306 """Return a SubmanifestSpec object, populating attributes"""
307 mp = self.parent.manifestProject
308 remote = self.parent.remotes[
309 self.remote or self.parent.default.remote.name
310 ]
311 # If a project was given, generate the url from the remote and project.
312 # If not, use this manifestProject's url.
313 if self.project:
314 manifestUrl = remote.ToRemoteSpec(self.project).url
315 else:
316 manifestUrl = mp.GetRemote().url
317 manifestName = self.manifestName or "default.xml"
318 revision = self.revision or self.name
319 path = self.path or revision.split("/")[-1]
320 groups = self.groups or []
LaMont Jonescc879a92021-11-18 22:40:18 +0000321
Gavin Makea2e3302023-03-11 06:46:20 +0000322 return SubmanifestSpec(
323 self.name, manifestUrl, manifestName, revision, path, groups
324 )
LaMont Jonescc879a92021-11-18 22:40:18 +0000325
Gavin Makea2e3302023-03-11 06:46:20 +0000326 @property
327 def relpath(self):
328 """The path of this submanifest relative to the parent manifest."""
329 revision = self.revision or self.name
330 return self.path or revision.split("/")[-1]
LaMont Jonescc879a92021-11-18 22:40:18 +0000331
Gavin Makea2e3302023-03-11 06:46:20 +0000332 def GetGroupsStr(self):
333 """Returns the `groups` given for this submanifest."""
334 if self.groups:
335 return ",".join(self.groups)
336 return ""
LaMont Jones501733c2022-04-20 16:42:32 +0000337
Gavin Makea2e3302023-03-11 06:46:20 +0000338 def GetDefaultGroupsStr(self):
339 """Returns the `default-groups` given for this submanifest."""
340 return ",".join(self.default_groups or [])
341
342 def AddAnnotation(self, name, value, keep):
343 """Add annotations to the submanifest."""
344 self.annotations.append(Annotation(name, value, keep))
LaMont Jonescc879a92021-11-18 22:40:18 +0000345
346
347class SubmanifestSpec:
Gavin Makea2e3302023-03-11 06:46:20 +0000348 """The submanifest element, with all fields expanded."""
LaMont Jonescc879a92021-11-18 22:40:18 +0000349
Gavin Makea2e3302023-03-11 06:46:20 +0000350 def __init__(self, name, manifestUrl, manifestName, revision, path, groups):
351 self.name = name
352 self.manifestUrl = manifestUrl
353 self.manifestName = manifestName
354 self.revision = revision
355 self.path = path
356 self.groups = groups or []
LaMont Jonescc879a92021-11-18 22:40:18 +0000357
358
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700359class XmlManifest(object):
Gavin Makea2e3302023-03-11 06:46:20 +0000360 """manages the repo configuration file"""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700361
Gavin Makea2e3302023-03-11 06:46:20 +0000362 def __init__(
363 self,
364 repodir,
365 manifest_file,
366 local_manifests=None,
367 outer_client=None,
368 parent_groups="",
369 submanifest_path="",
370 default_groups=None,
371 ):
372 """Initialize.
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400373
Gavin Makea2e3302023-03-11 06:46:20 +0000374 Args:
375 repodir: Path to the .repo/ dir for holding all internal checkout
376 state. It must be in the top directory of the repo client
377 checkout.
378 manifest_file: Full path to the manifest file to parse. This will
379 usually be |repodir|/|MANIFEST_FILE_NAME|.
380 local_manifests: Full path to the directory of local override
381 manifests. This will usually be
382 |repodir|/|LOCAL_MANIFESTS_DIR_NAME|.
383 outer_client: RepoClient of the outer manifest.
384 parent_groups: a string, the groups to apply to this projects.
385 submanifest_path: The submanifest root relative to the repo root.
386 default_groups: a string, the default manifest groups to use.
387 """
388 # TODO(vapier): Move this out of this class.
389 self.globalConfig = GitConfig.ForUser()
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400390
Gavin Makea2e3302023-03-11 06:46:20 +0000391 self.repodir = os.path.abspath(repodir)
392 self._CheckLocalPath(submanifest_path)
393 self.topdir = os.path.dirname(self.repodir)
394 if submanifest_path:
395 # This avoids a trailing os.path.sep when submanifest_path is empty.
396 self.topdir = os.path.join(self.topdir, submanifest_path)
397 if manifest_file != os.path.abspath(manifest_file):
398 raise ManifestParseError("manifest_file must be abspath")
399 self.manifestFile = manifest_file
400 if not outer_client or outer_client == self:
401 # manifestFileOverrides only exists in the outer_client's manifest,
402 # since that is the only instance left when Unload() is called on
403 # the outer manifest.
404 self.manifestFileOverrides = {}
405 self.local_manifests = local_manifests
406 self._load_local_manifests = True
407 self.parent_groups = parent_groups
408 self.default_groups = default_groups
LaMont Jonescc879a92021-11-18 22:40:18 +0000409
Gavin Makea2e3302023-03-11 06:46:20 +0000410 if outer_client and self.isGitcClient:
411 raise ManifestParseError(
412 "Multi-manifest is incompatible with `gitc-init`"
413 )
LaMont Jonescc879a92021-11-18 22:40:18 +0000414
Gavin Makea2e3302023-03-11 06:46:20 +0000415 if submanifest_path and not outer_client:
416 # If passing a submanifest_path, there must be an outer_client.
417 raise ManifestParseError(f"Bad call to {self.__class__.__name__}")
LaMont Jonescc879a92021-11-18 22:40:18 +0000418
Gavin Makea2e3302023-03-11 06:46:20 +0000419 # If self._outer_client is None, this is not a checkout that supports
420 # multi-tree.
421 self._outer_client = outer_client or self
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700422
Gavin Makea2e3302023-03-11 06:46:20 +0000423 self.repoProject = RepoProject(
424 self,
425 "repo",
426 gitdir=os.path.join(repodir, "repo/.git"),
427 worktree=os.path.join(repodir, "repo"),
428 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700429
Gavin Makea2e3302023-03-11 06:46:20 +0000430 mp = self.SubmanifestProject(self.path_prefix)
431 self.manifestProject = mp
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500432
Gavin Makea2e3302023-03-11 06:46:20 +0000433 # This is a bit hacky, but we're in a chicken & egg situation: all the
434 # normal repo settings live in the manifestProject which we just setup
435 # above, so we couldn't easily query before that. We assume Project()
436 # init doesn't care if this changes afterwards.
437 if os.path.exists(mp.gitdir) and mp.use_worktree:
438 mp.use_git_worktrees = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700439
Gavin Makea2e3302023-03-11 06:46:20 +0000440 self.Unload()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700441
Gavin Makea2e3302023-03-11 06:46:20 +0000442 def Override(self, name, load_local_manifests=True):
443 """Use a different manifest, just for the current instantiation."""
444 path = None
Basil Gelloc7453502018-05-25 20:23:52 +0300445
Gavin Makea2e3302023-03-11 06:46:20 +0000446 # Look for a manifest by path in the filesystem (including the cwd).
447 if not load_local_manifests:
448 local_path = os.path.abspath(name)
449 if os.path.isfile(local_path):
450 path = local_path
Basil Gelloc7453502018-05-25 20:23:52 +0300451
Gavin Makea2e3302023-03-11 06:46:20 +0000452 # Look for manifests by name from the manifests repo.
453 if path is None:
454 path = os.path.join(self.manifestProject.worktree, name)
455 if not os.path.isfile(path):
456 raise ManifestParseError("manifest %s not found" % name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700457
Gavin Makea2e3302023-03-11 06:46:20 +0000458 self._load_local_manifests = load_local_manifests
459 self._outer_client.manifestFileOverrides[self.path_prefix] = path
460 self.Unload()
461 self._Load()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700462
Gavin Makea2e3302023-03-11 06:46:20 +0000463 def Link(self, name):
464 """Update the repo metadata to use a different manifest."""
465 self.Override(name)
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700466
Gavin Makea2e3302023-03-11 06:46:20 +0000467 # Old versions of repo would generate symlinks we need to clean up.
468 platform_utils.remove(self.manifestFile, missing_ok=True)
469 # This file is interpreted as if it existed inside the manifest repo.
470 # That allows us to use <include> with the relative file name.
471 with open(self.manifestFile, "w") as fp:
472 fp.write(
473 """<?xml version="1.0" encoding="UTF-8"?>
Mike Frysingera269b1c2020-02-21 00:49:41 -0500474<!--
475DO NOT EDIT THIS FILE! It is generated by repo and changes will be discarded.
476If you want to use a different manifest, use `repo init -m <file>` instead.
477
478If you want to customize your checkout by overriding manifest settings, use
479the local_manifests/ directory instead.
480
481For more information on repo manifests, check out:
482https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
483-->
484<manifest>
485 <include name="%s" />
486</manifest>
Gavin Makea2e3302023-03-11 06:46:20 +0000487"""
488 % (name,)
489 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700490
Gavin Makea2e3302023-03-11 06:46:20 +0000491 def _RemoteToXml(self, r, doc, root):
492 e = doc.createElement("remote")
493 root.appendChild(e)
494 e.setAttribute("name", r.name)
495 e.setAttribute("fetch", r.fetchUrl)
496 if r.pushUrl is not None:
497 e.setAttribute("pushurl", r.pushUrl)
498 if r.remoteAlias is not None:
499 e.setAttribute("alias", r.remoteAlias)
500 if r.reviewUrl is not None:
501 e.setAttribute("review", r.reviewUrl)
502 if r.revision is not None:
503 e.setAttribute("revision", r.revision)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800504
Gavin Makea2e3302023-03-11 06:46:20 +0000505 for a in r.annotations:
506 if a.keep == "true":
507 ae = doc.createElement("annotation")
508 ae.setAttribute("name", a.name)
509 ae.setAttribute("value", a.value)
510 e.appendChild(ae)
Jack Neus6ea0cae2021-07-20 20:52:33 +0000511
Gavin Makea2e3302023-03-11 06:46:20 +0000512 def _SubmanifestToXml(self, r, doc, root):
513 """Generate XML <submanifest/> node."""
514 e = doc.createElement("submanifest")
515 root.appendChild(e)
516 e.setAttribute("name", r.name)
517 if r.remote is not None:
518 e.setAttribute("remote", r.remote)
519 if r.project is not None:
520 e.setAttribute("project", r.project)
521 if r.manifestName is not None:
522 e.setAttribute("manifest-name", r.manifestName)
523 if r.revision is not None:
524 e.setAttribute("revision", r.revision)
525 if r.path is not None:
526 e.setAttribute("path", r.path)
527 if r.groups:
528 e.setAttribute("groups", r.GetGroupsStr())
529 if r.default_groups:
530 e.setAttribute("default-groups", r.GetDefaultGroupsStr())
LaMont Jonescc879a92021-11-18 22:40:18 +0000531
Gavin Makea2e3302023-03-11 06:46:20 +0000532 for a in r.annotations:
533 if a.keep == "true":
534 ae = doc.createElement("annotation")
535 ae.setAttribute("name", a.name)
536 ae.setAttribute("value", a.value)
537 e.appendChild(ae)
LaMont Jonescc879a92021-11-18 22:40:18 +0000538
Gavin Makea2e3302023-03-11 06:46:20 +0000539 def _ParseList(self, field):
540 """Parse fields that contain flattened lists.
Mike Frysinger51e39d52020-12-04 05:32:06 -0500541
Gavin Makea2e3302023-03-11 06:46:20 +0000542 These are whitespace & comma separated. Empty elements will be
543 discarded.
544 """
545 return [x for x in re.split(r"[,\s]+", field) if x]
Josh Triplett884a3872014-06-12 14:57:29 -0700546
Gavin Makea2e3302023-03-11 06:46:20 +0000547 def ToXml(
548 self,
549 peg_rev=False,
550 peg_rev_upstream=True,
551 peg_rev_dest_branch=True,
552 groups=None,
553 omit_local=False,
554 ):
555 """Return the current manifest XML."""
556 mp = self.manifestProject
Colin Cross5acde752012-03-28 20:15:45 -0700557
Gavin Makea2e3302023-03-11 06:46:20 +0000558 if groups is None:
559 groups = mp.manifest_groups
560 if groups:
561 groups = self._ParseList(groups)
Colin Cross5acde752012-03-28 20:15:45 -0700562
Gavin Makea2e3302023-03-11 06:46:20 +0000563 doc = xml.dom.minidom.Document()
564 root = doc.createElement("manifest")
565 if self.is_submanifest:
566 root.setAttribute("path", self.path_prefix)
567 doc.appendChild(root)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800568
Gavin Makea2e3302023-03-11 06:46:20 +0000569 # Save out the notice. There's a little bit of work here to give it the
570 # right whitespace, which assumes that the notice is automatically
571 # indented by 4 by minidom.
572 if self.notice:
573 notice_element = root.appendChild(doc.createElement("notice"))
574 notice_lines = self.notice.splitlines()
575 indented_notice = (
576 "\n".join(" " * 4 + line for line in notice_lines)
577 )[4:]
578 notice_element.appendChild(doc.createTextNode(indented_notice))
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700579
Gavin Makea2e3302023-03-11 06:46:20 +0000580 d = self.default
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800581
Gavin Makea2e3302023-03-11 06:46:20 +0000582 for r in sorted(self.remotes):
583 self._RemoteToXml(self.remotes[r], doc, root)
584 if self.remotes:
585 root.appendChild(doc.createTextNode(""))
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800586
Gavin Makea2e3302023-03-11 06:46:20 +0000587 have_default = False
588 e = doc.createElement("default")
589 if d.remote:
590 have_default = True
591 e.setAttribute("remote", d.remote.name)
592 if d.revisionExpr:
593 have_default = True
594 e.setAttribute("revision", d.revisionExpr)
595 if d.destBranchExpr:
596 have_default = True
597 e.setAttribute("dest-branch", d.destBranchExpr)
598 if d.upstreamExpr:
599 have_default = True
600 e.setAttribute("upstream", d.upstreamExpr)
601 if d.sync_j is not None:
602 have_default = True
603 e.setAttribute("sync-j", "%d" % d.sync_j)
604 if d.sync_c:
605 have_default = True
606 e.setAttribute("sync-c", "true")
607 if d.sync_s:
608 have_default = True
609 e.setAttribute("sync-s", "true")
610 if not d.sync_tags:
611 have_default = True
612 e.setAttribute("sync-tags", "false")
613 if have_default:
614 root.appendChild(e)
615 root.appendChild(doc.createTextNode(""))
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800616
Gavin Makea2e3302023-03-11 06:46:20 +0000617 if self._manifest_server:
618 e = doc.createElement("manifest-server")
619 e.setAttribute("url", self._manifest_server)
620 root.appendChild(e)
621 root.appendChild(doc.createTextNode(""))
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700622
Gavin Makea2e3302023-03-11 06:46:20 +0000623 for r in sorted(self.submanifests):
624 self._SubmanifestToXml(self.submanifests[r], doc, root)
625 if self.submanifests:
626 root.appendChild(doc.createTextNode(""))
LaMont Jonescc879a92021-11-18 22:40:18 +0000627
Gavin Makea2e3302023-03-11 06:46:20 +0000628 def output_projects(parent, parent_node, projects):
629 for project_name in projects:
630 for project in self._projects[project_name]:
631 output_project(parent, parent_node, project)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800632
Gavin Makea2e3302023-03-11 06:46:20 +0000633 def output_project(parent, parent_node, p):
634 if not p.MatchesGroups(groups):
635 return
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800636
Gavin Makea2e3302023-03-11 06:46:20 +0000637 if omit_local and self.IsFromLocalManifest(p):
638 return
LaMont Jonesa8cf5752022-07-15 20:31:33 +0000639
Gavin Makea2e3302023-03-11 06:46:20 +0000640 name = p.name
641 relpath = p.relpath
642 if parent:
643 name = self._UnjoinName(parent.name, name)
644 relpath = self._UnjoinRelpath(parent.relpath, relpath)
Colin Cross5acde752012-03-28 20:15:45 -0700645
Gavin Makea2e3302023-03-11 06:46:20 +0000646 e = doc.createElement("project")
647 parent_node.appendChild(e)
648 e.setAttribute("name", name)
649 if relpath != name:
650 e.setAttribute("path", relpath)
651 remoteName = None
652 if d.remote:
653 remoteName = d.remote.name
654 if not d.remote or p.remote.orig_name != remoteName:
655 remoteName = p.remote.orig_name
656 e.setAttribute("remote", remoteName)
657 if peg_rev:
658 if self.IsMirror:
659 value = p.bare_git.rev_parse(p.revisionExpr + "^0")
660 else:
661 value = p.work_git.rev_parse(HEAD + "^0")
662 e.setAttribute("revision", value)
663 if peg_rev_upstream:
664 if p.upstream:
665 e.setAttribute("upstream", p.upstream)
666 elif value != p.revisionExpr:
667 # Only save the origin if the origin is not a sha1, and
668 # the default isn't our value
669 e.setAttribute("upstream", p.revisionExpr)
670
671 if peg_rev_dest_branch:
672 if p.dest_branch:
673 e.setAttribute("dest-branch", p.dest_branch)
674 elif value != p.revisionExpr:
675 e.setAttribute("dest-branch", p.revisionExpr)
676
677 else:
678 revision = (
679 self.remotes[p.remote.orig_name].revision or d.revisionExpr
680 )
681 if not revision or revision != p.revisionExpr:
682 e.setAttribute("revision", p.revisionExpr)
683 elif p.revisionId:
684 e.setAttribute("revision", p.revisionId)
685 if p.upstream and (
686 p.upstream != p.revisionExpr or p.upstream != d.upstreamExpr
687 ):
688 e.setAttribute("upstream", p.upstream)
689
690 if p.dest_branch and p.dest_branch != d.destBranchExpr:
691 e.setAttribute("dest-branch", p.dest_branch)
692
693 for c in p.copyfiles:
694 ce = doc.createElement("copyfile")
695 ce.setAttribute("src", c.src)
696 ce.setAttribute("dest", c.dest)
697 e.appendChild(ce)
698
699 for lf in p.linkfiles:
700 le = doc.createElement("linkfile")
701 le.setAttribute("src", lf.src)
702 le.setAttribute("dest", lf.dest)
703 e.appendChild(le)
704
705 default_groups = ["all", "name:%s" % p.name, "path:%s" % p.relpath]
706 egroups = [g for g in p.groups if g not in default_groups]
707 if egroups:
708 e.setAttribute("groups", ",".join(egroups))
709
710 for a in p.annotations:
711 if a.keep == "true":
712 ae = doc.createElement("annotation")
713 ae.setAttribute("name", a.name)
714 ae.setAttribute("value", a.value)
715 e.appendChild(ae)
716
717 if p.sync_c:
718 e.setAttribute("sync-c", "true")
719
720 if p.sync_s:
721 e.setAttribute("sync-s", "true")
722
723 if not p.sync_tags:
724 e.setAttribute("sync-tags", "false")
725
726 if p.clone_depth:
727 e.setAttribute("clone-depth", str(p.clone_depth))
728
729 self._output_manifest_project_extras(p, e)
730
731 if p.subprojects:
732 subprojects = set(subp.name for subp in p.subprojects)
733 output_projects(p, e, list(sorted(subprojects)))
734
735 projects = set(p.name for p in self._paths.values() if not p.parent)
736 output_projects(None, root, list(sorted(projects)))
737
738 if self._repo_hooks_project:
739 root.appendChild(doc.createTextNode(""))
740 e = doc.createElement("repo-hooks")
741 e.setAttribute("in-project", self._repo_hooks_project.name)
742 e.setAttribute(
743 "enabled-list",
744 " ".join(self._repo_hooks_project.enabled_repo_hooks),
745 )
746 root.appendChild(e)
747
748 if self._superproject:
749 root.appendChild(doc.createTextNode(""))
750 e = doc.createElement("superproject")
751 e.setAttribute("name", self._superproject.name)
752 remoteName = None
753 if d.remote:
754 remoteName = d.remote.name
755 remote = self._superproject.remote
756 if not d.remote or remote.orig_name != remoteName:
757 remoteName = remote.orig_name
758 e.setAttribute("remote", remoteName)
759 revision = remote.revision or d.revisionExpr
760 if not revision or revision != self._superproject.revision:
761 e.setAttribute("revision", self._superproject.revision)
762 root.appendChild(e)
763
764 if self._contactinfo.bugurl != Wrapper().BUG_URL:
765 root.appendChild(doc.createTextNode(""))
766 e = doc.createElement("contactinfo")
767 e.setAttribute("bugurl", self._contactinfo.bugurl)
768 root.appendChild(e)
769
770 return doc
771
772 def ToDict(self, **kwargs):
773 """Return the current manifest as a dictionary."""
774 # Elements that may only appear once.
775 SINGLE_ELEMENTS = {
776 "notice",
777 "default",
778 "manifest-server",
779 "repo-hooks",
780 "superproject",
781 "contactinfo",
782 }
783 # Elements that may be repeated.
784 MULTI_ELEMENTS = {
785 "remote",
786 "remove-project",
787 "project",
788 "extend-project",
789 "include",
790 "submanifest",
791 # These are children of 'project' nodes.
792 "annotation",
793 "project",
794 "copyfile",
795 "linkfile",
796 }
797
798 doc = self.ToXml(**kwargs)
799 ret = {}
800
801 def append_children(ret, node):
802 for child in node.childNodes:
803 if child.nodeType == xml.dom.Node.ELEMENT_NODE:
804 attrs = child.attributes
805 element = dict(
806 (attrs.item(i).localName, attrs.item(i).value)
807 for i in range(attrs.length)
808 )
809 if child.nodeName in SINGLE_ELEMENTS:
810 ret[child.nodeName] = element
811 elif child.nodeName in MULTI_ELEMENTS:
812 ret.setdefault(child.nodeName, []).append(element)
813 else:
814 raise ManifestParseError(
815 'Unhandled element "%s"' % (child.nodeName,)
816 )
817
818 append_children(element, child)
819
820 append_children(ret, doc.firstChild)
821
822 return ret
823
824 def Save(self, fd, **kwargs):
825 """Write the current manifest out to the given file descriptor."""
826 doc = self.ToXml(**kwargs)
827 doc.writexml(fd, "", " ", "\n", "UTF-8")
828
829 def _output_manifest_project_extras(self, p, e):
830 """Manifests can modify e if they support extra project attributes."""
831
832 @property
833 def is_multimanifest(self):
834 """Whether this is a multimanifest checkout.
835
836 This is safe to use as long as the outermost manifest XML has been
837 parsed.
838 """
839 return bool(self._outer_client._submanifests)
840
841 @property
842 def is_submanifest(self):
843 """Whether this manifest is a submanifest.
844
845 This is safe to use as long as the outermost manifest XML has been
846 parsed.
847 """
848 return self._outer_client and self._outer_client != self
849
850 @property
851 def outer_client(self):
852 """The instance of the outermost manifest client."""
853 self._Load()
854 return self._outer_client
855
856 @property
857 def all_manifests(self):
858 """Generator yielding all (sub)manifests, in depth-first order."""
859 self._Load()
860 outer = self._outer_client
861 yield outer
862 for tree in outer.all_children:
863 yield tree
864
865 @property
866 def all_children(self):
867 """Generator yielding all (present) child submanifests."""
868 self._Load()
869 for child in self._submanifests.values():
870 if child.repo_client:
871 yield child.repo_client
872 for tree in child.repo_client.all_children:
873 yield tree
874
875 @property
876 def path_prefix(self):
877 """The path of this submanifest, relative to the outermost manifest."""
878 if not self._outer_client or self == self._outer_client:
879 return ""
880 return os.path.relpath(self.topdir, self._outer_client.topdir)
881
882 @property
883 def all_paths(self):
884 """All project paths for all (sub)manifests.
885
886 See also `paths`.
887
888 Returns:
889 A dictionary of {path: Project()}. `path` is relative to the outer
890 manifest.
891 """
892 ret = {}
893 for tree in self.all_manifests:
894 prefix = tree.path_prefix
895 ret.update(
896 {os.path.join(prefix, k): v for k, v in tree.paths.items()}
897 )
898 return ret
899
900 @property
901 def all_projects(self):
902 """All projects for all (sub)manifests. See `projects`."""
903 return list(
904 itertools.chain.from_iterable(
905 x._paths.values() for x in self.all_manifests
906 )
907 )
908
909 @property
910 def paths(self):
911 """Return all paths for this manifest.
912
913 Returns:
914 A dictionary of {path: Project()}. `path` is relative to this
915 manifest.
916 """
917 self._Load()
918 return self._paths
919
920 @property
921 def projects(self):
922 """Return a list of all Projects in this manifest."""
923 self._Load()
924 return list(self._paths.values())
925
926 @property
927 def remotes(self):
928 """Return a list of remotes for this manifest."""
929 self._Load()
930 return self._remotes
931
932 @property
933 def default(self):
934 """Return default values for this manifest."""
935 self._Load()
936 return self._default
937
938 @property
939 def submanifests(self):
940 """All submanifests in this manifest."""
941 self._Load()
942 return self._submanifests
943
944 @property
945 def repo_hooks_project(self):
946 self._Load()
947 return self._repo_hooks_project
948
949 @property
950 def superproject(self):
951 self._Load()
952 return self._superproject
953
954 @property
955 def contactinfo(self):
956 self._Load()
957 return self._contactinfo
958
959 @property
960 def notice(self):
961 self._Load()
962 return self._notice
963
964 @property
965 def manifest_server(self):
966 self._Load()
967 return self._manifest_server
968
969 @property
970 def CloneBundle(self):
971 clone_bundle = self.manifestProject.clone_bundle
972 if clone_bundle is None:
973 return False if self.manifestProject.partial_clone else True
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800974 else:
Gavin Makea2e3302023-03-11 06:46:20 +0000975 return clone_bundle
Sean McAllisteraf908cb2020-04-20 08:41:58 -0600976
Gavin Makea2e3302023-03-11 06:46:20 +0000977 @property
978 def CloneFilter(self):
979 if self.manifestProject.partial_clone:
980 return self.manifestProject.clone_filter
981 return None
Sean McAllisteraf908cb2020-04-20 08:41:58 -0600982
Gavin Makea2e3302023-03-11 06:46:20 +0000983 @property
Jason Chang17833322023-05-23 13:06:55 -0700984 def CloneFilterForDepth(self):
985 if self.manifestProject.clone_filter_for_depth:
986 return self.manifestProject.clone_filter_for_depth
987 return None
988
989 @property
Gavin Makea2e3302023-03-11 06:46:20 +0000990 def PartialCloneExclude(self):
991 exclude = self.manifest.manifestProject.partial_clone_exclude or ""
992 return set(x.strip() for x in exclude.split(","))
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800993
Gavin Makea2e3302023-03-11 06:46:20 +0000994 def SetManifestOverride(self, path):
995 """Override manifestFile. The caller must call Unload()"""
996 self._outer_client.manifest.manifestFileOverrides[
997 self.path_prefix
998 ] = path
Simon Ruggier7e59de22015-07-24 12:50:06 +0200999
Gavin Makea2e3302023-03-11 06:46:20 +00001000 @property
1001 def UseLocalManifests(self):
1002 return self._load_local_manifests
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -08001003
Gavin Makea2e3302023-03-11 06:46:20 +00001004 def SetUseLocalManifests(self, value):
1005 self._load_local_manifests = value
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001006
Gavin Makea2e3302023-03-11 06:46:20 +00001007 @property
1008 def HasLocalManifests(self):
1009 return self._load_local_manifests and self.local_manifests
Colin Cross5acde752012-03-28 20:15:45 -07001010
Gavin Makea2e3302023-03-11 06:46:20 +00001011 def IsFromLocalManifest(self, project):
1012 """Is the project from a local manifest?"""
1013 return any(
1014 x.startswith(LOCAL_MANIFEST_GROUP_PREFIX) for x in project.groups
1015 )
James W. Mills24c13082012-04-12 15:04:13 -05001016
Gavin Makea2e3302023-03-11 06:46:20 +00001017 @property
1018 def IsMirror(self):
1019 return self.manifestProject.mirror
Anatol Pomazau79770d22012-04-20 14:41:59 -07001020
Gavin Makea2e3302023-03-11 06:46:20 +00001021 @property
1022 def UseGitWorktrees(self):
1023 return self.manifestProject.use_worktree
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001024
Gavin Makea2e3302023-03-11 06:46:20 +00001025 @property
1026 def IsArchive(self):
1027 return self.manifestProject.archive
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +09001028
Gavin Makea2e3302023-03-11 06:46:20 +00001029 @property
1030 def HasSubmodules(self):
1031 return self.manifestProject.submodules
Dan Willemsen88409222015-08-17 15:29:10 -07001032
Gavin Makea2e3302023-03-11 06:46:20 +00001033 @property
1034 def EnableGitLfs(self):
1035 return self.manifestProject.git_lfs
Simran Basib9a1b732015-08-20 12:19:28 -07001036
Gavin Makea2e3302023-03-11 06:46:20 +00001037 def FindManifestByPath(self, path):
1038 """Returns the manifest containing path."""
1039 path = os.path.abspath(path)
1040 manifest = self._outer_client or self
1041 old = None
1042 while manifest._submanifests and manifest != old:
1043 old = manifest
1044 for name in manifest._submanifests:
1045 tree = manifest._submanifests[name]
1046 if path.startswith(tree.repo_client.manifest.topdir):
1047 manifest = tree.repo_client
1048 break
1049 return manifest
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001050
Gavin Makea2e3302023-03-11 06:46:20 +00001051 @property
1052 def subdir(self):
1053 """Returns the path for per-submanifest objects for this manifest."""
1054 return self.SubmanifestInfoDir(self.path_prefix)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001055
Gavin Makea2e3302023-03-11 06:46:20 +00001056 def SubmanifestInfoDir(self, submanifest_path, object_path=""):
1057 """Return the path to submanifest-specific info for a submanifest.
Doug Anderson37282b42011-03-04 11:54:18 -08001058
Gavin Makea2e3302023-03-11 06:46:20 +00001059 Return the full path of the directory in which to put per-manifest
1060 objects.
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001061
Gavin Makea2e3302023-03-11 06:46:20 +00001062 Args:
1063 submanifest_path: a string, the path of the submanifest, relative to
1064 the outermost topdir. If empty, then repodir is returned.
1065 object_path: a string, relative path to append to the submanifest
1066 info directory path.
1067 """
1068 if submanifest_path:
1069 return os.path.join(
1070 self.repodir, SUBMANIFEST_DIR, submanifest_path, object_path
1071 )
1072 else:
1073 return os.path.join(self.repodir, object_path)
Raman Tenneti1c3f57e2021-05-04 12:32:13 -07001074
Gavin Makea2e3302023-03-11 06:46:20 +00001075 def SubmanifestProject(self, submanifest_path):
1076 """Return a manifestProject for a submanifest."""
1077 subdir = self.SubmanifestInfoDir(submanifest_path)
1078 mp = ManifestProject(
1079 self,
1080 "manifests",
1081 gitdir=os.path.join(subdir, "manifests.git"),
1082 worktree=os.path.join(subdir, "manifests"),
1083 )
1084 return mp
Mike Frysinger23411d32020-09-02 04:31:10 -04001085
Gavin Makea2e3302023-03-11 06:46:20 +00001086 def GetDefaultGroupsStr(self, with_platform=True):
1087 """Returns the default group string to use.
Mike Frysinger23411d32020-09-02 04:31:10 -04001088
Gavin Makea2e3302023-03-11 06:46:20 +00001089 Args:
1090 with_platform: a boolean, whether to include the group for the
1091 underlying platform.
1092 """
1093 groups = ",".join(self.default_groups or ["default"])
1094 if with_platform:
1095 groups += f",platform-{platform.system().lower()}"
1096 return groups
Mike Frysinger23411d32020-09-02 04:31:10 -04001097
Gavin Makea2e3302023-03-11 06:46:20 +00001098 def GetGroupsStr(self):
1099 """Returns the manifest group string that should be synced."""
1100 return (
1101 self.manifestProject.manifest_groups or self.GetDefaultGroupsStr()
1102 )
Mike Frysinger23411d32020-09-02 04:31:10 -04001103
Gavin Makea2e3302023-03-11 06:46:20 +00001104 def Unload(self):
1105 """Unload the manifest.
Mike Frysinger23411d32020-09-02 04:31:10 -04001106
Gavin Makea2e3302023-03-11 06:46:20 +00001107 If the manifest files have been changed since Load() was called, this
1108 will cause the new/updated manifest to be used.
Mike Frysinger23411d32020-09-02 04:31:10 -04001109
Gavin Makea2e3302023-03-11 06:46:20 +00001110 """
1111 self._loaded = False
1112 self._projects = {}
1113 self._paths = {}
1114 self._remotes = {}
1115 self._default = None
1116 self._submanifests = {}
1117 self._repo_hooks_project = None
1118 self._superproject = None
1119 self._contactinfo = ContactInfo(Wrapper().BUG_URL)
1120 self._notice = None
1121 self.branch = None
1122 self._manifest_server = None
Mike Frysinger23411d32020-09-02 04:31:10 -04001123
Gavin Makea2e3302023-03-11 06:46:20 +00001124 def Load(self):
1125 """Read the manifest into memory."""
1126 # Do not expose internal arguments.
1127 self._Load()
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -08001128
Gavin Makea2e3302023-03-11 06:46:20 +00001129 def _Load(self, initial_client=None, submanifest_depth=0):
1130 if submanifest_depth > MAX_SUBMANIFEST_DEPTH:
1131 raise ManifestParseError(
1132 "maximum submanifest depth %d exceeded." % MAX_SUBMANIFEST_DEPTH
1133 )
1134 if not self._loaded:
1135 if self._outer_client and self._outer_client != self:
1136 # This will load all clients.
1137 self._outer_client._Load(initial_client=self)
Simran Basib9a1b732015-08-20 12:19:28 -07001138
Gavin Makea2e3302023-03-11 06:46:20 +00001139 savedManifestFile = self.manifestFile
1140 override = self._outer_client.manifestFileOverrides.get(
1141 self.path_prefix
1142 )
1143 if override:
1144 self.manifestFile = override
Mike Frysinger1d00a7e2021-12-21 00:40:31 -05001145
Gavin Makea2e3302023-03-11 06:46:20 +00001146 try:
1147 m = self.manifestProject
1148 b = m.GetBranch(m.CurrentBranch).merge
1149 if b is not None and b.startswith(R_HEADS):
1150 b = b[len(R_HEADS) :]
1151 self.branch = b
LaMont Jonescc879a92021-11-18 22:40:18 +00001152
Gavin Makea2e3302023-03-11 06:46:20 +00001153 parent_groups = self.parent_groups
1154 if self.path_prefix:
1155 parent_groups = (
1156 f"{SUBMANIFEST_GROUP_PREFIX}:path:"
1157 f"{self.path_prefix},{parent_groups}"
1158 )
LaMont Jonesff6b1da2022-06-01 21:03:34 +00001159
Gavin Makea2e3302023-03-11 06:46:20 +00001160 # The manifestFile was specified by the user which is why we
1161 # allow include paths to point anywhere.
1162 nodes = []
1163 nodes.append(
1164 self._ParseManifestXml(
1165 self.manifestFile,
1166 self.manifestProject.worktree,
1167 parent_groups=parent_groups,
1168 restrict_includes=False,
1169 )
1170 )
LaMont Jonescc879a92021-11-18 22:40:18 +00001171
Gavin Makea2e3302023-03-11 06:46:20 +00001172 if self._load_local_manifests and self.local_manifests:
1173 try:
1174 for local_file in sorted(
1175 platform_utils.listdir(self.local_manifests)
1176 ):
1177 if local_file.endswith(".xml"):
1178 local = os.path.join(
1179 self.local_manifests, local_file
1180 )
1181 # Since local manifests are entirely managed by
1182 # the user, allow them to point anywhere the
1183 # user wants.
1184 local_group = (
1185 f"{LOCAL_MANIFEST_GROUP_PREFIX}:"
1186 f"{local_file[:-4]}"
1187 )
1188 nodes.append(
1189 self._ParseManifestXml(
1190 local,
1191 self.subdir,
1192 parent_groups=(
1193 f"{local_group},{parent_groups}"
1194 ),
1195 restrict_includes=False,
1196 )
1197 )
1198 except OSError:
1199 pass
Raman Tenneti080877e2021-03-09 15:19:06 -08001200
Gavin Makea2e3302023-03-11 06:46:20 +00001201 try:
1202 self._ParseManifest(nodes)
1203 except ManifestParseError as e:
1204 # There was a problem parsing, unload ourselves in case they
1205 # catch this error and try again later, we will show the
1206 # correct error
1207 self.Unload()
1208 raise e
Raman Tenneti080877e2021-03-09 15:19:06 -08001209
Gavin Makea2e3302023-03-11 06:46:20 +00001210 if self.IsMirror:
1211 self._AddMetaProjectMirror(self.repoProject)
1212 self._AddMetaProjectMirror(self.manifestProject)
LaMont Jonesa2ff20d2022-04-07 16:49:06 +00001213
Gavin Makea2e3302023-03-11 06:46:20 +00001214 self._loaded = True
1215 finally:
1216 if override:
1217 self.manifestFile = savedManifestFile
LaMont Jonesa2ff20d2022-04-07 16:49:06 +00001218
Gavin Makea2e3302023-03-11 06:46:20 +00001219 # Now that we have loaded this manifest, load any submanifests as
1220 # well. We need to do this after self._loaded is set to avoid
1221 # looping.
1222 for name in self._submanifests:
1223 tree = self._submanifests[name]
1224 tree.ToSubmanifestSpec()
1225 present = os.path.exists(
1226 os.path.join(self.subdir, MANIFEST_FILE_NAME)
1227 )
1228 if present and tree.present and not tree.repo_client:
1229 if initial_client and initial_client.topdir == self.topdir:
1230 tree.repo_client = self
1231 tree.present = present
1232 elif not os.path.exists(self.subdir):
1233 tree.present = False
1234 if present and tree.present:
1235 tree.repo_client._Load(
1236 initial_client=initial_client,
1237 submanifest_depth=submanifest_depth + 1,
1238 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001239
Gavin Makea2e3302023-03-11 06:46:20 +00001240 def _ParseManifestXml(
Shuchuan Zeng3e3340d2023-04-18 10:36:50 +08001241 self,
1242 path,
1243 include_root,
1244 parent_groups="",
1245 restrict_includes=True,
1246 parent_node=None,
Gavin Makea2e3302023-03-11 06:46:20 +00001247 ):
1248 """Parse a manifest XML and return the computed nodes.
LaMont Jonesa2ff20d2022-04-07 16:49:06 +00001249
Gavin Makea2e3302023-03-11 06:46:20 +00001250 Args:
1251 path: The XML file to read & parse.
1252 include_root: The path to interpret include "name"s relative to.
1253 parent_groups: The groups to apply to this projects.
1254 restrict_includes: Whether to constrain the "name" attribute of
1255 includes.
Shuchuan Zeng3e3340d2023-04-18 10:36:50 +08001256 parent_node: The parent include node, to apply attribute to this
1257 projects.
LaMont Jonescc879a92021-11-18 22:40:18 +00001258
Gavin Makea2e3302023-03-11 06:46:20 +00001259 Returns:
1260 List of XML nodes.
1261 """
1262 try:
1263 root = xml.dom.minidom.parse(path)
1264 except (OSError, xml.parsers.expat.ExpatError) as e:
1265 raise ManifestParseError(
1266 "error parsing manifest %s: %s" % (path, e)
1267 )
David Pursehouse2d5a0df2012-11-13 02:50:36 +09001268
Gavin Makea2e3302023-03-11 06:46:20 +00001269 if not root or not root.childNodes:
1270 raise ManifestParseError("no root node in %s" % (path,))
Shawn O. Pearce5cc66792008-10-23 16:19:27 -07001271
Gavin Makea2e3302023-03-11 06:46:20 +00001272 for manifest in root.childNodes:
1273 if manifest.nodeName == "manifest":
1274 break
1275 else:
1276 raise ManifestParseError("no <manifest> in %s" % (path,))
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001277
LaMont Jonesb90a4222022-04-14 15:00:09 +00001278 nodes = []
Gavin Makea2e3302023-03-11 06:46:20 +00001279 for node in manifest.childNodes:
1280 if node.nodeName == "include":
1281 name = self._reqatt(node, "name")
1282 if restrict_includes:
1283 msg = self._CheckLocalPath(name)
1284 if msg:
1285 raise ManifestInvalidPathError(
1286 '<include> invalid "name": %s: %s' % (name, msg)
1287 )
1288 include_groups = ""
1289 if parent_groups:
1290 include_groups = parent_groups
1291 if node.hasAttribute("groups"):
1292 include_groups = (
1293 node.getAttribute("groups") + "," + include_groups
1294 )
1295 fp = os.path.join(include_root, name)
1296 if not os.path.isfile(fp):
1297 raise ManifestParseError(
1298 "include [%s/]%s doesn't exist or isn't a file"
1299 % (include_root, name)
1300 )
1301 try:
1302 nodes.extend(
Shuchuan Zeng3e3340d2023-04-18 10:36:50 +08001303 self._ParseManifestXml(
1304 fp, include_root, include_groups, parent_node=node
1305 )
Gavin Makea2e3302023-03-11 06:46:20 +00001306 )
1307 # should isolate this to the exact exception, but that's
1308 # tricky. actual parsing implementation may vary.
1309 except (
1310 KeyboardInterrupt,
1311 RuntimeError,
1312 SystemExit,
1313 ManifestParseError,
1314 ):
1315 raise
1316 except Exception as e:
1317 raise ManifestParseError(
1318 "failed parsing included manifest %s: %s" % (name, e)
1319 )
1320 else:
1321 if parent_groups and node.nodeName == "project":
1322 nodeGroups = parent_groups
1323 if node.hasAttribute("groups"):
1324 nodeGroups = (
1325 node.getAttribute("groups") + "," + nodeGroups
1326 )
1327 node.setAttribute("groups", nodeGroups)
Shuchuan Zeng3e3340d2023-04-18 10:36:50 +08001328 if (
1329 parent_node
1330 and node.nodeName == "project"
1331 and not node.hasAttribute("revision")
1332 ):
1333 node.setAttribute(
1334 "revision", parent_node.getAttribute("revision")
1335 )
Gavin Makea2e3302023-03-11 06:46:20 +00001336 nodes.append(node)
1337 return nodes
LaMont Jonesb90a4222022-04-14 15:00:09 +00001338
Gavin Makea2e3302023-03-11 06:46:20 +00001339 def _ParseManifest(self, node_list):
1340 for node in itertools.chain(*node_list):
1341 if node.nodeName == "remote":
1342 remote = self._ParseRemote(node)
1343 if remote:
1344 if remote.name in self._remotes:
1345 if remote != self._remotes[remote.name]:
1346 raise ManifestParseError(
1347 "remote %s already exists with different "
1348 "attributes" % (remote.name)
1349 )
1350 else:
1351 self._remotes[remote.name] = remote
LaMont Jonesb90a4222022-04-14 15:00:09 +00001352
Gavin Makea2e3302023-03-11 06:46:20 +00001353 for node in itertools.chain(*node_list):
1354 if node.nodeName == "default":
1355 new_default = self._ParseDefault(node)
1356 emptyDefault = (
1357 not node.hasAttributes() and not node.hasChildNodes()
1358 )
1359 if self._default is None:
1360 self._default = new_default
1361 elif not emptyDefault and new_default != self._default:
1362 raise ManifestParseError(
1363 "duplicate default in %s" % (self.manifestFile)
1364 )
LaMont Jonesb90a4222022-04-14 15:00:09 +00001365
Julien Campergue74879922013-10-09 14:38:46 +02001366 if self._default is None:
Gavin Makea2e3302023-03-11 06:46:20 +00001367 self._default = _Default()
Julien Campergue74879922013-10-09 14:38:46 +02001368
Gavin Makea2e3302023-03-11 06:46:20 +00001369 submanifest_paths = set()
1370 for node in itertools.chain(*node_list):
1371 if node.nodeName == "submanifest":
1372 submanifest = self._ParseSubmanifest(node)
1373 if submanifest:
1374 if submanifest.name in self._submanifests:
1375 if submanifest != self._submanifests[submanifest.name]:
1376 raise ManifestParseError(
1377 "submanifest %s already exists with different "
1378 "attributes" % (submanifest.name)
1379 )
1380 else:
1381 self._submanifests[submanifest.name] = submanifest
1382 submanifest_paths.add(submanifest.relpath)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001383
Gavin Makea2e3302023-03-11 06:46:20 +00001384 for node in itertools.chain(*node_list):
1385 if node.nodeName == "notice":
1386 if self._notice is not None:
1387 raise ManifestParseError(
1388 "duplicate notice in %s" % (self.manifestFile)
1389 )
1390 self._notice = self._ParseNotice(node)
LaMont Jonescc879a92021-11-18 22:40:18 +00001391
Gavin Makea2e3302023-03-11 06:46:20 +00001392 for node in itertools.chain(*node_list):
1393 if node.nodeName == "manifest-server":
1394 url = self._reqatt(node, "url")
1395 if self._manifest_server is not None:
1396 raise ManifestParseError(
1397 "duplicate manifest-server in %s" % (self.manifestFile)
1398 )
1399 self._manifest_server = url
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001400
Gavin Makea2e3302023-03-11 06:46:20 +00001401 def recursively_add_projects(project):
1402 projects = self._projects.setdefault(project.name, [])
1403 if project.relpath is None:
1404 raise ManifestParseError(
1405 "missing path for %s in %s"
1406 % (project.name, self.manifestFile)
1407 )
1408 if project.relpath in self._paths:
1409 raise ManifestParseError(
1410 "duplicate path %s in %s"
1411 % (project.relpath, self.manifestFile)
1412 )
1413 for tree in submanifest_paths:
1414 if project.relpath.startswith(tree):
1415 raise ManifestParseError(
1416 "project %s conflicts with submanifest path %s"
1417 % (project.relpath, tree)
1418 )
1419 self._paths[project.relpath] = project
1420 projects.append(project)
1421 for subproject in project.subprojects:
1422 recursively_add_projects(subproject)
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001423
Gavin Makea2e3302023-03-11 06:46:20 +00001424 repo_hooks_project = None
1425 enabled_repo_hooks = None
1426 for node in itertools.chain(*node_list):
1427 if node.nodeName == "project":
1428 project = self._ParseProject(node)
1429 recursively_add_projects(project)
1430 if node.nodeName == "extend-project":
1431 name = self._reqatt(node, "name")
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001432
Gavin Makea2e3302023-03-11 06:46:20 +00001433 if name not in self._projects:
1434 raise ManifestParseError(
1435 "extend-project element specifies non-existent "
1436 "project: %s" % name
1437 )
1438
1439 path = node.getAttribute("path")
1440 dest_path = node.getAttribute("dest-path")
1441 groups = node.getAttribute("groups")
1442 if groups:
1443 groups = self._ParseList(groups)
1444 revision = node.getAttribute("revision")
1445 remote_name = node.getAttribute("remote")
1446 if not remote_name:
1447 remote = self._default.remote
1448 else:
1449 remote = self._get_remote(node)
1450 dest_branch = node.getAttribute("dest-branch")
1451 upstream = node.getAttribute("upstream")
1452
1453 named_projects = self._projects[name]
1454 if dest_path and not path and len(named_projects) > 1:
1455 raise ManifestParseError(
1456 "extend-project cannot use dest-path when "
1457 "matching multiple projects: %s" % name
1458 )
1459 for p in self._projects[name]:
1460 if path and p.relpath != path:
1461 continue
1462 if groups:
1463 p.groups.extend(groups)
1464 if revision:
1465 p.SetRevision(revision)
1466
1467 if remote_name:
1468 p.remote = remote.ToRemoteSpec(name)
1469 if dest_branch:
1470 p.dest_branch = dest_branch
1471 if upstream:
1472 p.upstream = upstream
1473
1474 if dest_path:
1475 del self._paths[p.relpath]
1476 (
1477 relpath,
1478 worktree,
1479 gitdir,
1480 objdir,
1481 _,
1482 ) = self.GetProjectPaths(name, dest_path, remote.name)
1483 p.UpdatePaths(relpath, worktree, gitdir, objdir)
1484 self._paths[p.relpath] = p
1485
1486 if node.nodeName == "repo-hooks":
1487 # Only one project can be the hooks project
1488 if repo_hooks_project is not None:
1489 raise ManifestParseError(
1490 "duplicate repo-hooks in %s" % (self.manifestFile)
1491 )
1492
1493 # Get the name of the project and the (space-separated) list of
1494 # enabled.
1495 repo_hooks_project = self._reqatt(node, "in-project")
1496 enabled_repo_hooks = self._ParseList(
1497 self._reqatt(node, "enabled-list")
1498 )
1499 if node.nodeName == "superproject":
1500 name = self._reqatt(node, "name")
1501 # There can only be one superproject.
1502 if self._superproject:
1503 raise ManifestParseError(
1504 "duplicate superproject in %s" % (self.manifestFile)
1505 )
1506 remote_name = node.getAttribute("remote")
1507 if not remote_name:
1508 remote = self._default.remote
1509 else:
1510 remote = self._get_remote(node)
1511 if remote is None:
1512 raise ManifestParseError(
1513 "no remote for superproject %s within %s"
1514 % (name, self.manifestFile)
1515 )
1516 revision = node.getAttribute("revision") or remote.revision
1517 if not revision:
1518 revision = self._default.revisionExpr
1519 if not revision:
1520 raise ManifestParseError(
1521 "no revision for superproject %s within %s"
1522 % (name, self.manifestFile)
1523 )
1524 self._superproject = Superproject(
1525 self,
1526 name=name,
1527 remote=remote.ToRemoteSpec(name),
1528 revision=revision,
1529 )
1530 if node.nodeName == "contactinfo":
1531 bugurl = self._reqatt(node, "bugurl")
1532 # This element can be repeated, later entries will clobber
1533 # earlier ones.
1534 self._contactinfo = ContactInfo(bugurl)
1535
1536 if node.nodeName == "remove-project":
Fredrik de Grootbe71c2f2023-05-31 16:56:34 +02001537 name = node.getAttribute("name")
1538 path = node.getAttribute("path")
Gavin Makea2e3302023-03-11 06:46:20 +00001539
Fredrik de Grootbe71c2f2023-05-31 16:56:34 +02001540 # Name or path needed.
1541 if not name and not path:
1542 raise ManifestParseError(
1543 "remove-project must have name and/or path"
1544 )
Gavin Makea2e3302023-03-11 06:46:20 +00001545
Fredrik de Grootbe71c2f2023-05-31 16:56:34 +02001546 removed_project = ""
1547
1548 # Find and remove projects based on name and/or path.
1549 for projname, projects in list(self._projects.items()):
1550 for p in projects:
1551 if name == projname and not path:
1552 del self._paths[p.relpath]
1553 if not removed_project:
1554 del self._projects[name]
1555 removed_project = name
1556 elif path == p.relpath and (
1557 name == projname or not name
1558 ):
1559 self._projects[projname].remove(p)
1560 del self._paths[p.relpath]
1561 removed_project = p.name
1562
1563 # If the manifest removes the hooks project, treat it as if
1564 # it deleted the repo-hooks element too.
1565 if (
1566 removed_project
1567 and removed_project not in self._projects
1568 and repo_hooks_project == removed_project
1569 ):
1570 repo_hooks_project = None
1571
1572 if not removed_project and not XmlBool(node, "optional", False):
Gavin Makea2e3302023-03-11 06:46:20 +00001573 raise ManifestParseError(
1574 "remove-project element specifies non-existent "
Fredrik de Grootbe71c2f2023-05-31 16:56:34 +02001575 "project: %s" % node.toxml()
Gavin Makea2e3302023-03-11 06:46:20 +00001576 )
1577
1578 # Store repo hooks project information.
1579 if repo_hooks_project:
1580 # Store a reference to the Project.
1581 try:
1582 repo_hooks_projects = self._projects[repo_hooks_project]
1583 except KeyError:
1584 raise ManifestParseError(
1585 "project %s not found for repo-hooks" % (repo_hooks_project)
1586 )
1587
1588 if len(repo_hooks_projects) != 1:
1589 raise ManifestParseError(
1590 "internal error parsing repo-hooks in %s"
1591 % (self.manifestFile)
1592 )
1593 self._repo_hooks_project = repo_hooks_projects[0]
1594 # Store the enabled hooks in the Project object.
1595 self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
1596
1597 def _AddMetaProjectMirror(self, m):
1598 name = None
1599 m_url = m.GetRemote().url
1600 if m_url.endswith("/.git"):
1601 raise ManifestParseError("refusing to mirror %s" % m_url)
1602
1603 if self._default and self._default.remote:
1604 url = self._default.remote.resolvedFetchUrl
1605 if not url.endswith("/"):
1606 url += "/"
1607 if m_url.startswith(url):
1608 remote = self._default.remote
1609 name = m_url[len(url) :]
1610
1611 if name is None:
1612 s = m_url.rindex("/") + 1
1613 manifestUrl = self.manifestProject.config.GetString(
1614 "remote.origin.url"
1615 )
1616 remote = _XmlRemote(
1617 "origin", fetch=m_url[:s], manifestUrl=manifestUrl
1618 )
1619 name = m_url[s:]
1620
1621 if name.endswith(".git"):
1622 name = name[:-4]
Josh Triplett884a3872014-06-12 14:57:29 -07001623
1624 if name not in self._projects:
Gavin Makea2e3302023-03-11 06:46:20 +00001625 m.PreSync()
1626 gitdir = os.path.join(self.topdir, "%s.git" % name)
1627 project = Project(
1628 manifest=self,
1629 name=name,
1630 remote=remote.ToRemoteSpec(name),
1631 gitdir=gitdir,
1632 objdir=gitdir,
1633 worktree=None,
1634 relpath=name or None,
1635 revisionExpr=m.revisionExpr,
1636 revisionId=None,
1637 )
1638 self._projects[project.name] = [project]
1639 self._paths[project.relpath] = project
Josh Triplett884a3872014-06-12 14:57:29 -07001640
Gavin Makea2e3302023-03-11 06:46:20 +00001641 def _ParseRemote(self, node):
1642 """
1643 reads a <remote> element from the manifest file
1644 """
1645 name = self._reqatt(node, "name")
1646 alias = node.getAttribute("alias")
1647 if alias == "":
1648 alias = None
1649 fetch = self._reqatt(node, "fetch")
1650 pushUrl = node.getAttribute("pushurl")
1651 if pushUrl == "":
1652 pushUrl = None
1653 review = node.getAttribute("review")
1654 if review == "":
1655 review = None
1656 revision = node.getAttribute("revision")
1657 if revision == "":
1658 revision = None
1659 manifestUrl = self.manifestProject.config.GetString("remote.origin.url")
1660
1661 remote = _XmlRemote(
1662 name, alias, fetch, pushUrl, manifestUrl, review, revision
1663 )
1664
1665 for n in node.childNodes:
1666 if n.nodeName == "annotation":
1667 self._ParseAnnotation(remote, n)
1668
1669 return remote
1670
1671 def _ParseDefault(self, node):
1672 """
1673 reads a <default> element from the manifest file
1674 """
1675 d = _Default()
1676 d.remote = self._get_remote(node)
1677 d.revisionExpr = node.getAttribute("revision")
1678 if d.revisionExpr == "":
1679 d.revisionExpr = None
1680
1681 d.destBranchExpr = node.getAttribute("dest-branch") or None
1682 d.upstreamExpr = node.getAttribute("upstream") or None
1683
1684 d.sync_j = XmlInt(node, "sync-j", None)
1685 if d.sync_j is not None and d.sync_j <= 0:
1686 raise ManifestParseError(
1687 '%s: sync-j must be greater than 0, not "%s"'
1688 % (self.manifestFile, d.sync_j)
1689 )
1690
1691 d.sync_c = XmlBool(node, "sync-c", False)
1692 d.sync_s = XmlBool(node, "sync-s", False)
1693 d.sync_tags = XmlBool(node, "sync-tags", True)
1694 return d
1695
1696 def _ParseNotice(self, node):
1697 """
1698 reads a <notice> element from the manifest file
1699
1700 The <notice> element is distinct from other tags in the XML in that the
1701 data is conveyed between the start and end tag (it's not an
1702 empty-element tag).
1703
1704 The white space (carriage returns, indentation) for the notice element
1705 is relevant and is parsed in a way that is based on how python
1706 docstrings work. In fact, the code is remarkably similar to here:
1707 http://www.python.org/dev/peps/pep-0257/
1708 """
1709 # Get the data out of the node...
1710 notice = node.childNodes[0].data
1711
1712 # Figure out minimum indentation, skipping the first line (the same line
1713 # as the <notice> tag)...
1714 minIndent = sys.maxsize
1715 lines = notice.splitlines()
1716 for line in lines[1:]:
1717 lstrippedLine = line.lstrip()
1718 if lstrippedLine:
1719 indent = len(line) - len(lstrippedLine)
1720 minIndent = min(indent, minIndent)
1721
1722 # Strip leading / trailing blank lines and also indentation.
1723 cleanLines = [lines[0].strip()]
1724 for line in lines[1:]:
1725 cleanLines.append(line[minIndent:].rstrip())
1726
1727 # Clear completely blank lines from front and back...
1728 while cleanLines and not cleanLines[0]:
1729 del cleanLines[0]
1730 while cleanLines and not cleanLines[-1]:
1731 del cleanLines[-1]
1732
1733 return "\n".join(cleanLines)
1734
1735 def _ParseSubmanifest(self, node):
1736 """Reads a <submanifest> element from the manifest file."""
1737 name = self._reqatt(node, "name")
1738 remote = node.getAttribute("remote")
1739 if remote == "":
1740 remote = None
1741 project = node.getAttribute("project")
1742 if project == "":
1743 project = None
1744 revision = node.getAttribute("revision")
1745 if revision == "":
1746 revision = None
1747 manifestName = node.getAttribute("manifest-name")
1748 if manifestName == "":
1749 manifestName = None
1750 groups = ""
1751 if node.hasAttribute("groups"):
1752 groups = node.getAttribute("groups")
1753 groups = self._ParseList(groups)
1754 default_groups = self._ParseList(node.getAttribute("default-groups"))
1755 path = node.getAttribute("path")
1756 if path == "":
1757 path = None
1758 if revision:
1759 msg = self._CheckLocalPath(revision.split("/")[-1])
1760 if msg:
1761 raise ManifestInvalidPathError(
1762 '<submanifest> invalid "revision": %s: %s'
1763 % (revision, msg)
1764 )
1765 else:
1766 msg = self._CheckLocalPath(name)
1767 if msg:
1768 raise ManifestInvalidPathError(
1769 '<submanifest> invalid "name": %s: %s' % (name, msg)
1770 )
LaMont Jonescc879a92021-11-18 22:40:18 +00001771 else:
Gavin Makea2e3302023-03-11 06:46:20 +00001772 msg = self._CheckLocalPath(path)
1773 if msg:
1774 raise ManifestInvalidPathError(
1775 '<submanifest> invalid "path": %s: %s' % (path, msg)
1776 )
Josh Triplett884a3872014-06-12 14:57:29 -07001777
Gavin Makea2e3302023-03-11 06:46:20 +00001778 submanifest = _XmlSubmanifest(
1779 name,
1780 remote,
1781 project,
1782 revision,
1783 manifestName,
1784 groups,
1785 default_groups,
1786 path,
1787 self,
1788 )
Michael Kelly2f3c3312020-07-21 19:40:38 -07001789
Gavin Makea2e3302023-03-11 06:46:20 +00001790 for n in node.childNodes:
1791 if n.nodeName == "annotation":
1792 self._ParseAnnotation(submanifest, n)
Michael Kelly2f3c3312020-07-21 19:40:38 -07001793
Gavin Makea2e3302023-03-11 06:46:20 +00001794 return submanifest
Michael Kelly37c21c22020-06-13 02:10:40 -07001795
Gavin Makea2e3302023-03-11 06:46:20 +00001796 def _JoinName(self, parent_name, name):
1797 return os.path.join(parent_name, name)
Doug Anderson37282b42011-03-04 11:54:18 -08001798
Gavin Makea2e3302023-03-11 06:46:20 +00001799 def _UnjoinName(self, parent_name, name):
1800 return os.path.relpath(name, parent_name)
1801
1802 def _ParseProject(self, node, parent=None, **extra_proj_attrs):
1803 """
1804 reads a <project> element from the manifest file
1805 """
1806 name = self._reqatt(node, "name")
1807 msg = self._CheckLocalPath(name, dir_ok=True)
1808 if msg:
1809 raise ManifestInvalidPathError(
1810 '<project> invalid "name": %s: %s' % (name, msg)
1811 )
1812 if parent:
1813 name = self._JoinName(parent.name, name)
1814
1815 remote = self._get_remote(node)
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001816 if remote is None:
Gavin Makea2e3302023-03-11 06:46:20 +00001817 remote = self._default.remote
1818 if remote is None:
1819 raise ManifestParseError(
1820 "no remote for project %s within %s" % (name, self.manifestFile)
1821 )
Raman Tenneti993af5e2021-05-12 12:00:31 -07001822
Gavin Makea2e3302023-03-11 06:46:20 +00001823 revisionExpr = node.getAttribute("revision") or remote.revision
1824 if not revisionExpr:
1825 revisionExpr = self._default.revisionExpr
1826 if not revisionExpr:
1827 raise ManifestParseError(
1828 "no revision for project %s within %s"
1829 % (name, self.manifestFile)
1830 )
David Jamesb8433df2014-01-30 10:11:17 -08001831
Gavin Makea2e3302023-03-11 06:46:20 +00001832 path = node.getAttribute("path")
1833 if not path:
1834 path = name
Julien Camperguedd654222014-01-09 16:21:37 +01001835 else:
Gavin Makea2e3302023-03-11 06:46:20 +00001836 # NB: The "." project is handled specially in
1837 # Project.Sync_LocalHalf.
1838 msg = self._CheckLocalPath(path, dir_ok=True, cwd_dot_ok=True)
1839 if msg:
1840 raise ManifestInvalidPathError(
1841 '<project> invalid "path": %s: %s' % (path, msg)
1842 )
Julien Camperguedd654222014-01-09 16:21:37 +01001843
Gavin Makea2e3302023-03-11 06:46:20 +00001844 rebase = XmlBool(node, "rebase", True)
1845 sync_c = XmlBool(node, "sync-c", False)
1846 sync_s = XmlBool(node, "sync-s", self._default.sync_s)
1847 sync_tags = XmlBool(node, "sync-tags", self._default.sync_tags)
Julien Camperguedd654222014-01-09 16:21:37 +01001848
Gavin Makea2e3302023-03-11 06:46:20 +00001849 clone_depth = XmlInt(node, "clone-depth")
1850 if clone_depth is not None and clone_depth <= 0:
1851 raise ManifestParseError(
1852 '%s: clone-depth must be greater than 0, not "%s"'
1853 % (self.manifestFile, clone_depth)
1854 )
1855
1856 dest_branch = (
1857 node.getAttribute("dest-branch") or self._default.destBranchExpr
1858 )
1859
1860 upstream = node.getAttribute("upstream") or self._default.upstreamExpr
1861
1862 groups = ""
1863 if node.hasAttribute("groups"):
1864 groups = node.getAttribute("groups")
1865 groups = self._ParseList(groups)
1866
1867 if parent is None:
1868 (
1869 relpath,
1870 worktree,
1871 gitdir,
1872 objdir,
1873 use_git_worktrees,
1874 ) = self.GetProjectPaths(name, path, remote.name)
1875 else:
1876 use_git_worktrees = False
1877 relpath, worktree, gitdir, objdir = self.GetSubprojectPaths(
1878 parent, name, path
1879 )
1880
1881 default_groups = ["all", "name:%s" % name, "path:%s" % relpath]
1882 groups.extend(set(default_groups).difference(groups))
1883
1884 if self.IsMirror and node.hasAttribute("force-path"):
1885 if XmlBool(node, "force-path", False):
1886 gitdir = os.path.join(self.topdir, "%s.git" % path)
1887
1888 project = Project(
1889 manifest=self,
1890 name=name,
1891 remote=remote.ToRemoteSpec(name),
1892 gitdir=gitdir,
1893 objdir=objdir,
1894 worktree=worktree,
1895 relpath=relpath,
1896 revisionExpr=revisionExpr,
1897 revisionId=None,
1898 rebase=rebase,
1899 groups=groups,
1900 sync_c=sync_c,
1901 sync_s=sync_s,
1902 sync_tags=sync_tags,
1903 clone_depth=clone_depth,
1904 upstream=upstream,
1905 parent=parent,
1906 dest_branch=dest_branch,
1907 use_git_worktrees=use_git_worktrees,
1908 **extra_proj_attrs,
1909 )
1910
1911 for n in node.childNodes:
1912 if n.nodeName == "copyfile":
1913 self._ParseCopyFile(project, n)
1914 if n.nodeName == "linkfile":
1915 self._ParseLinkFile(project, n)
1916 if n.nodeName == "annotation":
1917 self._ParseAnnotation(project, n)
1918 if n.nodeName == "project":
1919 project.subprojects.append(
1920 self._ParseProject(n, parent=project)
1921 )
1922
1923 return project
1924
1925 def GetProjectPaths(self, name, path, remote):
1926 """Return the paths for a project.
1927
1928 Args:
1929 name: a string, the name of the project.
1930 path: a string, the path of the project.
1931 remote: a string, the remote.name of the project.
1932
1933 Returns:
1934 A tuple of (relpath, worktree, gitdir, objdir, use_git_worktrees)
1935 for the project with |name| and |path|.
1936 """
1937 # The manifest entries might have trailing slashes. Normalize them to
1938 # avoid unexpected filesystem behavior since we do string concatenation
1939 # below.
1940 path = path.rstrip("/")
1941 name = name.rstrip("/")
1942 remote = remote.rstrip("/")
1943 use_git_worktrees = False
1944 use_remote_name = self.is_multimanifest
1945 relpath = path
1946 if self.IsMirror:
1947 worktree = None
1948 gitdir = os.path.join(self.topdir, "%s.git" % name)
1949 objdir = gitdir
1950 else:
1951 if use_remote_name:
1952 namepath = os.path.join(remote, f"{name}.git")
1953 else:
1954 namepath = f"{name}.git"
1955 worktree = os.path.join(self.topdir, path).replace("\\", "/")
1956 gitdir = os.path.join(self.subdir, "projects", "%s.git" % path)
1957 # We allow people to mix git worktrees & non-git worktrees for now.
1958 # This allows for in situ migration of repo clients.
1959 if os.path.exists(gitdir) or not self.UseGitWorktrees:
1960 objdir = os.path.join(self.repodir, "project-objects", namepath)
1961 else:
1962 use_git_worktrees = True
1963 gitdir = os.path.join(self.repodir, "worktrees", namepath)
1964 objdir = gitdir
1965 return relpath, worktree, gitdir, objdir, use_git_worktrees
1966
1967 def GetProjectsWithName(self, name, all_manifests=False):
1968 """All projects with |name|.
1969
1970 Args:
1971 name: a string, the name of the project.
1972 all_manifests: a boolean, if True, then all manifests are searched.
1973 If False, then only this manifest is searched.
1974
1975 Returns:
1976 A list of Project instances with name |name|.
1977 """
1978 if all_manifests:
1979 return list(
1980 itertools.chain.from_iterable(
1981 x._projects.get(name, []) for x in self.all_manifests
1982 )
1983 )
1984 return self._projects.get(name, [])
1985
1986 def GetSubprojectName(self, parent, submodule_path):
1987 return os.path.join(parent.name, submodule_path)
1988
1989 def _JoinRelpath(self, parent_relpath, relpath):
1990 return os.path.join(parent_relpath, relpath)
1991
1992 def _UnjoinRelpath(self, parent_relpath, relpath):
1993 return os.path.relpath(relpath, parent_relpath)
1994
1995 def GetSubprojectPaths(self, parent, name, path):
1996 # The manifest entries might have trailing slashes. Normalize them to
1997 # avoid unexpected filesystem behavior since we do string concatenation
1998 # below.
1999 path = path.rstrip("/")
2000 name = name.rstrip("/")
2001 relpath = self._JoinRelpath(parent.relpath, path)
2002 gitdir = os.path.join(parent.gitdir, "subprojects", "%s.git" % path)
2003 objdir = os.path.join(
2004 parent.gitdir, "subproject-objects", "%s.git" % name
2005 )
2006 if self.IsMirror:
2007 worktree = None
2008 else:
2009 worktree = os.path.join(parent.worktree, path).replace("\\", "/")
2010 return relpath, worktree, gitdir, objdir
2011
2012 @staticmethod
2013 def _CheckLocalPath(path, dir_ok=False, cwd_dot_ok=False):
2014 """Verify |path| is reasonable for use in filesystem paths.
2015
2016 Used with <copyfile> & <linkfile> & <project> elements.
2017
2018 This only validates the |path| in isolation: it does not check against
2019 the current filesystem state. Thus it is suitable as a first-past in a
2020 parser.
2021
2022 It enforces a number of constraints:
2023 * No empty paths.
2024 * No "~" in paths.
2025 * No Unicode codepoints that filesystems might elide when normalizing.
2026 * No relative path components like "." or "..".
2027 * No absolute paths.
2028 * No ".git" or ".repo*" path components.
2029
2030 Args:
2031 path: The path name to validate.
2032 dir_ok: Whether |path| may force a directory (e.g. end in a /).
2033 cwd_dot_ok: Whether |path| may be just ".".
2034
2035 Returns:
2036 None if |path| is OK, a failure message otherwise.
2037 """
2038 if not path:
2039 return "empty paths not allowed"
2040
2041 if "~" in path:
2042 return "~ not allowed (due to 8.3 filenames on Windows filesystems)"
2043
2044 path_codepoints = set(path)
2045
2046 # Some filesystems (like Apple's HFS+) try to normalize Unicode
2047 # codepoints which means there are alternative names for ".git". Reject
2048 # paths with these in it as there shouldn't be any reasonable need for
2049 # them here. The set of codepoints here was cribbed from jgit's
2050 # implementation:
2051 # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
2052 BAD_CODEPOINTS = {
2053 "\u200C", # ZERO WIDTH NON-JOINER
2054 "\u200D", # ZERO WIDTH JOINER
2055 "\u200E", # LEFT-TO-RIGHT MARK
2056 "\u200F", # RIGHT-TO-LEFT MARK
2057 "\u202A", # LEFT-TO-RIGHT EMBEDDING
2058 "\u202B", # RIGHT-TO-LEFT EMBEDDING
2059 "\u202C", # POP DIRECTIONAL FORMATTING
2060 "\u202D", # LEFT-TO-RIGHT OVERRIDE
2061 "\u202E", # RIGHT-TO-LEFT OVERRIDE
2062 "\u206A", # INHIBIT SYMMETRIC SWAPPING
2063 "\u206B", # ACTIVATE SYMMETRIC SWAPPING
2064 "\u206C", # INHIBIT ARABIC FORM SHAPING
2065 "\u206D", # ACTIVATE ARABIC FORM SHAPING
2066 "\u206E", # NATIONAL DIGIT SHAPES
2067 "\u206F", # NOMINAL DIGIT SHAPES
2068 "\uFEFF", # ZERO WIDTH NO-BREAK SPACE
2069 }
2070 if BAD_CODEPOINTS & path_codepoints:
2071 # This message is more expansive than reality, but should be fine.
2072 return "Unicode combining characters not allowed"
2073
2074 # Reject newlines as there shouldn't be any legitmate use for them,
2075 # they'll be confusing to users, and they can easily break tools that
2076 # expect to be able to iterate over newline delimited lists. This even
2077 # applies to our own code like .repo/project.list.
2078 if {"\r", "\n"} & path_codepoints:
2079 return "Newlines not allowed"
2080
2081 # Assume paths might be used on case-insensitive filesystems.
2082 path = path.lower()
2083
2084 # Split up the path by its components. We can't use os.path.sep
2085 # exclusively as some platforms (like Windows) will convert / to \ and
2086 # that bypasses all our constructed logic here. Especially since
2087 # manifest authors only use / in their paths.
2088 resep = re.compile(r"[/%s]" % re.escape(os.path.sep))
2089 # Strip off trailing slashes as those only produce '' elements, and we
2090 # use parts to look for individual bad components.
2091 parts = resep.split(path.rstrip("/"))
2092
2093 # Some people use src="." to create stable links to projects. Lets
2094 # allow that but reject all other uses of "." to keep things simple.
2095 if not cwd_dot_ok or parts != ["."]:
2096 for part in set(parts):
2097 if part in {".", "..", ".git"} or part.startswith(".repo"):
2098 return "bad component: %s" % (part,)
2099
2100 if not dir_ok and resep.match(path[-1]):
2101 return "dirs not allowed"
2102
2103 # NB: The two abspath checks here are to handle platforms with multiple
2104 # filesystem path styles (e.g. Windows).
2105 norm = os.path.normpath(path)
2106 if (
2107 norm == ".."
2108 or (
2109 len(norm) >= 3
2110 and norm.startswith("..")
2111 and resep.match(norm[0])
2112 )
2113 or os.path.isabs(norm)
2114 or norm.startswith("/")
2115 ):
2116 return "path cannot be outside"
2117
2118 @classmethod
2119 def _ValidateFilePaths(cls, element, src, dest):
2120 """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
2121
2122 We verify the path independent of any filesystem state as we won't have
2123 a checkout available to compare to. i.e. This is for parsing validation
2124 purposes only.
2125
2126 We'll do full/live sanity checking before we do the actual filesystem
2127 modifications in _CopyFile/_LinkFile/etc...
2128 """
2129 # |dest| is the file we write to or symlink we create.
2130 # It is relative to the top of the repo client checkout.
2131 msg = cls._CheckLocalPath(dest)
2132 if msg:
2133 raise ManifestInvalidPathError(
2134 '<%s> invalid "dest": %s: %s' % (element, dest, msg)
2135 )
2136
2137 # |src| is the file we read from or path we point to for symlinks.
2138 # It is relative to the top of the git project checkout.
2139 is_linkfile = element == "linkfile"
2140 msg = cls._CheckLocalPath(
2141 src, dir_ok=is_linkfile, cwd_dot_ok=is_linkfile
2142 )
2143 if msg:
2144 raise ManifestInvalidPathError(
2145 '<%s> invalid "src": %s: %s' % (element, src, msg)
2146 )
2147
2148 def _ParseCopyFile(self, project, node):
2149 src = self._reqatt(node, "src")
2150 dest = self._reqatt(node, "dest")
2151 if not self.IsMirror:
2152 # src is project relative;
2153 # dest is relative to the top of the tree.
2154 # We only validate paths if we actually plan to process them.
2155 self._ValidateFilePaths("copyfile", src, dest)
2156 project.AddCopyFile(src, dest, self.topdir)
2157
2158 def _ParseLinkFile(self, project, node):
2159 src = self._reqatt(node, "src")
2160 dest = self._reqatt(node, "dest")
2161 if not self.IsMirror:
2162 # src is project relative;
2163 # dest is relative to the top of the tree.
2164 # We only validate paths if we actually plan to process them.
2165 self._ValidateFilePaths("linkfile", src, dest)
2166 project.AddLinkFile(src, dest, self.topdir)
2167
2168 def _ParseAnnotation(self, element, node):
2169 name = self._reqatt(node, "name")
2170 value = self._reqatt(node, "value")
2171 try:
2172 keep = self._reqatt(node, "keep").lower()
2173 except ManifestParseError:
2174 keep = "true"
2175 if keep != "true" and keep != "false":
2176 raise ManifestParseError(
2177 'optional "keep" attribute must be ' '"true" or "false"'
2178 )
2179 element.AddAnnotation(name, value, keep)
2180
2181 def _get_remote(self, node):
2182 name = node.getAttribute("remote")
2183 if not name:
2184 return None
2185
2186 v = self._remotes.get(name)
2187 if not v:
2188 raise ManifestParseError(
2189 "remote %s not defined in %s" % (name, self.manifestFile)
2190 )
2191 return v
2192
2193 def _reqatt(self, node, attname):
2194 """
2195 reads a required attribute from the node.
2196 """
2197 v = node.getAttribute(attname)
2198 if not v:
2199 raise ManifestParseError(
2200 "no %s in <%s> within %s"
2201 % (attname, node.nodeName, self.manifestFile)
2202 )
2203 return v
2204
2205 def projectsDiff(self, manifest):
2206 """return the projects differences between two manifests.
2207
2208 The diff will be from self to given manifest.
2209
2210 """
2211 fromProjects = self.paths
2212 toProjects = manifest.paths
2213
2214 fromKeys = sorted(fromProjects.keys())
2215 toKeys = sorted(toProjects.keys())
2216
2217 diff = {
2218 "added": [],
2219 "removed": [],
2220 "missing": [],
2221 "changed": [],
2222 "unreachable": [],
2223 }
2224
2225 for proj in fromKeys:
2226 if proj not in toKeys:
2227 diff["removed"].append(fromProjects[proj])
2228 elif not fromProjects[proj].Exists:
2229 diff["missing"].append(toProjects[proj])
2230 toKeys.remove(proj)
2231 else:
2232 fromProj = fromProjects[proj]
2233 toProj = toProjects[proj]
2234 try:
2235 fromRevId = fromProj.GetCommitRevisionId()
2236 toRevId = toProj.GetCommitRevisionId()
2237 except ManifestInvalidRevisionError:
2238 diff["unreachable"].append((fromProj, toProj))
2239 else:
2240 if fromRevId != toRevId:
2241 diff["changed"].append((fromProj, toProj))
2242 toKeys.remove(proj)
2243
2244 for proj in toKeys:
2245 diff["added"].append(toProjects[proj])
2246
2247 return diff
Simran Basib9a1b732015-08-20 12:19:28 -07002248
2249
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04002250class RepoClient(XmlManifest):
Gavin Makea2e3302023-03-11 06:46:20 +00002251 """Manages a repo client checkout."""
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04002252
Gavin Makea2e3302023-03-11 06:46:20 +00002253 def __init__(
2254 self, repodir, manifest_file=None, submanifest_path="", **kwargs
2255 ):
2256 """Initialize.
LaMont Jonesff6b1da2022-06-01 21:03:34 +00002257
Gavin Makea2e3302023-03-11 06:46:20 +00002258 Args:
2259 repodir: Path to the .repo/ dir for holding all internal checkout
2260 state. It must be in the top directory of the repo client
2261 checkout.
2262 manifest_file: Full path to the manifest file to parse. This will
2263 usually be |repodir|/|MANIFEST_FILE_NAME|.
2264 submanifest_path: The submanifest root relative to the repo root.
2265 **kwargs: Additional keyword arguments, passed to XmlManifest.
2266 """
2267 self.isGitcClient = False
2268 submanifest_path = submanifest_path or ""
2269 if submanifest_path:
2270 self._CheckLocalPath(submanifest_path)
2271 prefix = os.path.join(repodir, SUBMANIFEST_DIR, submanifest_path)
2272 else:
2273 prefix = repodir
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04002274
Gavin Makea2e3302023-03-11 06:46:20 +00002275 if os.path.exists(os.path.join(prefix, LOCAL_MANIFEST_NAME)):
2276 print(
2277 "error: %s is not supported; put local manifests in `%s` "
2278 "instead"
2279 % (
2280 LOCAL_MANIFEST_NAME,
2281 os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME),
2282 ),
2283 file=sys.stderr,
2284 )
2285 sys.exit(1)
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04002286
Gavin Makea2e3302023-03-11 06:46:20 +00002287 if manifest_file is None:
2288 manifest_file = os.path.join(prefix, MANIFEST_FILE_NAME)
2289 local_manifests = os.path.abspath(
2290 os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME)
2291 )
2292 super().__init__(
2293 repodir,
2294 manifest_file,
2295 local_manifests,
2296 submanifest_path=submanifest_path,
2297 **kwargs,
2298 )
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04002299
Gavin Makea2e3302023-03-11 06:46:20 +00002300 # TODO: Completely separate manifest logic out of the client.
2301 self.manifest = self