blob: 9603906fb98464f2b59783c91098e457c0245160 [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
Simran Basib9a1b732015-08-20 12:19:28 -070024import gitc_utils
Daniel Kutik035f22a2022-12-13 12:34:23 +010025from git_config import GitConfig
David Pursehousee00aa6b2012-09-11 14:33:51 +090026from git_refs import R_HEADS, HEAD
LaMont Jonesd56e2eb2022-04-07 18:14:46 +000027from git_superproject import Superproject
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070028import platform_utils
Gavin Makea2e3302023-03-11 06:46:20 +000029from project import (
30 Annotation,
31 RemoteSpec,
32 Project,
33 RepoProject,
34 ManifestProject,
35)
36from error import (
37 ManifestParseError,
38 ManifestInvalidPathError,
39 ManifestInvalidRevisionError,
40)
Raman Tenneti993af5e2021-05-12 12:00:31 -070041from wrapper import Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070042
Gavin Makea2e3302023-03-11 06:46:20 +000043MANIFEST_FILE_NAME = "manifest.xml"
44LOCAL_MANIFEST_NAME = "local_manifest.xml"
45LOCAL_MANIFESTS_DIR_NAME = "local_manifests"
46SUBMANIFEST_DIR = "submanifests"
LaMont Jonescc879a92021-11-18 22:40:18 +000047# Limit submanifests to an arbitrary depth for loop detection.
48MAX_SUBMANIFEST_DEPTH = 8
LaMont Jonesb308db12022-02-25 17:05:21 +000049# Add all projects from sub manifest into a group.
Gavin Makea2e3302023-03-11 06:46:20 +000050SUBMANIFEST_GROUP_PREFIX = "submanifest:"
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070051
Raman Tenneti78f4dd32021-06-07 13:27:37 -070052# Add all projects from local manifest into a group.
Gavin Makea2e3302023-03-11 06:46:20 +000053LOCAL_MANIFEST_GROUP_PREFIX = "local:"
Raman Tenneti78f4dd32021-06-07 13:27:37 -070054
Raman Tenneti993af5e2021-05-12 12:00:31 -070055# ContactInfo has the self-registered bug url, supplied by the manifest authors.
Gavin Makea2e3302023-03-11 06:46:20 +000056ContactInfo = collections.namedtuple("ContactInfo", "bugurl")
Raman Tenneti993af5e2021-05-12 12:00:31 -070057
Anthony Kingcb07ba72015-03-28 23:26:04 +000058# urljoin gets confused if the scheme is not known.
Gavin Makea2e3302023-03-11 06:46:20 +000059urllib.parse.uses_relative.extend(
60 ["ssh", "git", "persistent-https", "sso", "rpc"]
61)
62urllib.parse.uses_netloc.extend(
63 ["ssh", "git", "persistent-https", "sso", "rpc"]
64)
Conley Owensdb728cd2011-09-26 16:34:01 -070065
David Pursehouse819827a2020-02-12 15:20:19 +090066
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050067def XmlBool(node, attr, default=None):
Gavin Makea2e3302023-03-11 06:46:20 +000068 """Determine boolean value of |node|'s |attr|.
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050069
Gavin Makea2e3302023-03-11 06:46:20 +000070 Invalid values will issue a non-fatal warning.
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050071
Gavin Makea2e3302023-03-11 06:46:20 +000072 Args:
73 node: XML node whose attributes we access.
74 attr: The attribute to access.
75 default: If the attribute is not set (value is empty), then use this.
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050076
Gavin Makea2e3302023-03-11 06:46:20 +000077 Returns:
78 True if the attribute is a valid string representing true.
79 False if the attribute is a valid string representing false.
80 |default| otherwise.
81 """
82 value = node.getAttribute(attr)
83 s = value.lower()
84 if s == "":
85 return default
86 elif s in {"yes", "true", "1"}:
87 return True
88 elif s in {"no", "false", "0"}:
89 return False
90 else:
91 print(
92 'warning: manifest: %s="%s": ignoring invalid XML boolean'
93 % (attr, value),
94 file=sys.stderr,
95 )
96 return default
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050097
98
99def XmlInt(node, attr, default=None):
Gavin Makea2e3302023-03-11 06:46:20 +0000100 """Determine integer value of |node|'s |attr|.
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500101
Gavin Makea2e3302023-03-11 06:46:20 +0000102 Args:
103 node: XML node whose attributes we access.
104 attr: The attribute to access.
105 default: If the attribute is not set (value is empty), then use this.
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500106
Gavin Makea2e3302023-03-11 06:46:20 +0000107 Returns:
108 The number if the attribute is a valid number.
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500109
Gavin Makea2e3302023-03-11 06:46:20 +0000110 Raises:
111 ManifestParseError: The number is invalid.
112 """
113 value = node.getAttribute(attr)
114 if not value:
115 return default
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500116
Gavin Makea2e3302023-03-11 06:46:20 +0000117 try:
118 return int(value)
119 except ValueError:
120 raise ManifestParseError(
121 'manifest: invalid %s="%s" integer' % (attr, value)
122 )
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500123
124
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700125class _Default(object):
Gavin Makea2e3302023-03-11 06:46:20 +0000126 """Project defaults within the manifest."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700127
Gavin Makea2e3302023-03-11 06:46:20 +0000128 revisionExpr = None
129 destBranchExpr = None
130 upstreamExpr = None
131 remote = None
132 sync_j = None
133 sync_c = False
134 sync_s = False
135 sync_tags = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700136
Gavin Makea2e3302023-03-11 06:46:20 +0000137 def __eq__(self, other):
138 if not isinstance(other, _Default):
139 return False
140 return self.__dict__ == other.__dict__
Julien Campergue74879922013-10-09 14:38:46 +0200141
Gavin Makea2e3302023-03-11 06:46:20 +0000142 def __ne__(self, other):
143 if not isinstance(other, _Default):
144 return True
145 return self.__dict__ != other.__dict__
Julien Campergue74879922013-10-09 14:38:46 +0200146
David Pursehouse819827a2020-02-12 15:20:19 +0900147
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700148class _XmlRemote(object):
Gavin Makea2e3302023-03-11 06:46:20 +0000149 def __init__(
150 self,
151 name,
152 alias=None,
153 fetch=None,
154 pushUrl=None,
155 manifestUrl=None,
156 review=None,
157 revision=None,
158 ):
159 self.name = name
160 self.fetchUrl = fetch
161 self.pushUrl = pushUrl
162 self.manifestUrl = manifestUrl
163 self.remoteAlias = alias
164 self.reviewUrl = review
165 self.revision = revision
166 self.resolvedFetchUrl = self._resolveFetchUrl()
167 self.annotations = []
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700168
Gavin Makea2e3302023-03-11 06:46:20 +0000169 def __eq__(self, other):
170 if not isinstance(other, _XmlRemote):
171 return False
172 return (
173 sorted(self.annotations) == sorted(other.annotations)
174 and self.name == other.name
175 and self.fetchUrl == other.fetchUrl
176 and self.pushUrl == other.pushUrl
177 and self.remoteAlias == other.remoteAlias
178 and self.reviewUrl == other.reviewUrl
179 and self.revision == other.revision
180 )
David Pursehouse717ece92012-11-13 08:49:16 +0900181
Gavin Makea2e3302023-03-11 06:46:20 +0000182 def __ne__(self, other):
183 return not self.__eq__(other)
David Pursehouse717ece92012-11-13 08:49:16 +0900184
Gavin Makea2e3302023-03-11 06:46:20 +0000185 def _resolveFetchUrl(self):
186 if self.fetchUrl is None:
187 return ""
188 url = self.fetchUrl.rstrip("/")
189 manifestUrl = self.manifestUrl.rstrip("/")
190 # urljoin will gets confused over quite a few things. The ones we care
191 # about here are:
192 # * no scheme in the base url, like <hostname:port>
193 # We handle no scheme by replacing it with an obscure protocol, gopher
194 # and then replacing it with the original when we are done.
Anthony Kingcb07ba72015-03-28 23:26:04 +0000195
Gavin Makea2e3302023-03-11 06:46:20 +0000196 if manifestUrl.find(":") != manifestUrl.find("/") - 1:
197 url = urllib.parse.urljoin("gopher://" + manifestUrl, url)
198 url = re.sub(r"^gopher://", "", url)
199 else:
200 url = urllib.parse.urljoin(manifestUrl, url)
201 return url
Conley Owensceea3682011-10-20 10:45:47 -0700202
Gavin Makea2e3302023-03-11 06:46:20 +0000203 def ToRemoteSpec(self, projectName):
204 fetchUrl = self.resolvedFetchUrl.rstrip("/")
205 url = fetchUrl + "/" + projectName
206 remoteName = self.name
207 if self.remoteAlias:
208 remoteName = self.remoteAlias
209 return RemoteSpec(
210 remoteName,
211 url=url,
212 pushUrl=self.pushUrl,
213 review=self.reviewUrl,
214 orig_name=self.name,
215 fetchUrl=self.fetchUrl,
216 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700217
Gavin Makea2e3302023-03-11 06:46:20 +0000218 def AddAnnotation(self, name, value, keep):
219 self.annotations.append(Annotation(name, value, keep))
Jack Neus6ea0cae2021-07-20 20:52:33 +0000220
David Pursehouse819827a2020-02-12 15:20:19 +0900221
LaMont Jonescc879a92021-11-18 22:40:18 +0000222class _XmlSubmanifest:
Gavin Makea2e3302023-03-11 06:46:20 +0000223 """Manage the <submanifest> element specified in the manifest.
LaMont Jonescc879a92021-11-18 22:40:18 +0000224
Gavin Makea2e3302023-03-11 06:46:20 +0000225 Attributes:
226 name: a string, the name for this submanifest.
227 remote: a string, the remote.name for this submanifest.
228 project: a string, the name of the manifest project.
229 revision: a string, the commitish.
230 manifestName: a string, the submanifest file name.
231 groups: a list of strings, the groups to add to all projects in the
232 submanifest.
233 default_groups: a list of strings, the default groups to sync.
234 path: a string, the relative path for the submanifest checkout.
235 parent: an XmlManifest, the parent manifest.
236 annotations: (derived) a list of annotations.
237 present: (derived) a boolean, whether the sub manifest file is present.
238 """
LaMont Jonescc879a92021-11-18 22:40:18 +0000239
Gavin Makea2e3302023-03-11 06:46:20 +0000240 def __init__(
241 self,
242 name,
243 remote=None,
244 project=None,
245 revision=None,
246 manifestName=None,
247 groups=None,
248 default_groups=None,
249 path=None,
250 parent=None,
251 ):
252 self.name = name
253 self.remote = remote
254 self.project = project
255 self.revision = revision
256 self.manifestName = manifestName
257 self.groups = groups
258 self.default_groups = default_groups
259 self.path = path
260 self.parent = parent
261 self.annotations = []
262 outer_client = parent._outer_client or parent
263 if self.remote and not self.project:
264 raise ManifestParseError(
265 f"Submanifest {name}: must specify project when remote is "
266 "given."
267 )
268 # Construct the absolute path to the manifest file using the parent's
269 # method, so that we can correctly create our repo_client.
270 manifestFile = parent.SubmanifestInfoDir(
271 os.path.join(parent.path_prefix, self.relpath),
272 os.path.join("manifests", manifestName or "default.xml"),
273 )
274 linkFile = parent.SubmanifestInfoDir(
275 os.path.join(parent.path_prefix, self.relpath), MANIFEST_FILE_NAME
276 )
277 self.repo_client = RepoClient(
278 parent.repodir,
279 linkFile,
280 parent_groups=",".join(groups) or "",
281 submanifest_path=self.relpath,
282 outer_client=outer_client,
283 default_groups=default_groups,
284 )
LaMont Jonescc879a92021-11-18 22:40:18 +0000285
Gavin Makea2e3302023-03-11 06:46:20 +0000286 self.present = os.path.exists(manifestFile)
LaMont Jonescc879a92021-11-18 22:40:18 +0000287
Gavin Makea2e3302023-03-11 06:46:20 +0000288 def __eq__(self, other):
289 if not isinstance(other, _XmlSubmanifest):
290 return False
291 return (
292 self.name == other.name
293 and self.remote == other.remote
294 and self.project == other.project
295 and self.revision == other.revision
296 and self.manifestName == other.manifestName
297 and self.groups == other.groups
298 and self.default_groups == other.default_groups
299 and self.path == other.path
300 and sorted(self.annotations) == sorted(other.annotations)
301 )
LaMont Jonescc879a92021-11-18 22:40:18 +0000302
Gavin Makea2e3302023-03-11 06:46:20 +0000303 def __ne__(self, other):
304 return not self.__eq__(other)
LaMont Jonescc879a92021-11-18 22:40:18 +0000305
Gavin Makea2e3302023-03-11 06:46:20 +0000306 def ToSubmanifestSpec(self):
307 """Return a SubmanifestSpec object, populating attributes"""
308 mp = self.parent.manifestProject
309 remote = self.parent.remotes[
310 self.remote or self.parent.default.remote.name
311 ]
312 # If a project was given, generate the url from the remote and project.
313 # If not, use this manifestProject's url.
314 if self.project:
315 manifestUrl = remote.ToRemoteSpec(self.project).url
316 else:
317 manifestUrl = mp.GetRemote().url
318 manifestName = self.manifestName or "default.xml"
319 revision = self.revision or self.name
320 path = self.path or revision.split("/")[-1]
321 groups = self.groups or []
LaMont Jonescc879a92021-11-18 22:40:18 +0000322
Gavin Makea2e3302023-03-11 06:46:20 +0000323 return SubmanifestSpec(
324 self.name, manifestUrl, manifestName, revision, path, groups
325 )
LaMont Jonescc879a92021-11-18 22:40:18 +0000326
Gavin Makea2e3302023-03-11 06:46:20 +0000327 @property
328 def relpath(self):
329 """The path of this submanifest relative to the parent manifest."""
330 revision = self.revision or self.name
331 return self.path or revision.split("/")[-1]
LaMont Jonescc879a92021-11-18 22:40:18 +0000332
Gavin Makea2e3302023-03-11 06:46:20 +0000333 def GetGroupsStr(self):
334 """Returns the `groups` given for this submanifest."""
335 if self.groups:
336 return ",".join(self.groups)
337 return ""
LaMont Jones501733c2022-04-20 16:42:32 +0000338
Gavin Makea2e3302023-03-11 06:46:20 +0000339 def GetDefaultGroupsStr(self):
340 """Returns the `default-groups` given for this submanifest."""
341 return ",".join(self.default_groups or [])
342
343 def AddAnnotation(self, name, value, keep):
344 """Add annotations to the submanifest."""
345 self.annotations.append(Annotation(name, value, keep))
LaMont Jonescc879a92021-11-18 22:40:18 +0000346
347
348class SubmanifestSpec:
Gavin Makea2e3302023-03-11 06:46:20 +0000349 """The submanifest element, with all fields expanded."""
LaMont Jonescc879a92021-11-18 22:40:18 +0000350
Gavin Makea2e3302023-03-11 06:46:20 +0000351 def __init__(self, name, manifestUrl, manifestName, revision, path, groups):
352 self.name = name
353 self.manifestUrl = manifestUrl
354 self.manifestName = manifestName
355 self.revision = revision
356 self.path = path
357 self.groups = groups or []
LaMont Jonescc879a92021-11-18 22:40:18 +0000358
359
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700360class XmlManifest(object):
Gavin Makea2e3302023-03-11 06:46:20 +0000361 """manages the repo configuration file"""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700362
Gavin Makea2e3302023-03-11 06:46:20 +0000363 def __init__(
364 self,
365 repodir,
366 manifest_file,
367 local_manifests=None,
368 outer_client=None,
369 parent_groups="",
370 submanifest_path="",
371 default_groups=None,
372 ):
373 """Initialize.
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400374
Gavin Makea2e3302023-03-11 06:46:20 +0000375 Args:
376 repodir: Path to the .repo/ dir for holding all internal checkout
377 state. It must be in the top directory of the repo client
378 checkout.
379 manifest_file: Full path to the manifest file to parse. This will
380 usually be |repodir|/|MANIFEST_FILE_NAME|.
381 local_manifests: Full path to the directory of local override
382 manifests. This will usually be
383 |repodir|/|LOCAL_MANIFESTS_DIR_NAME|.
384 outer_client: RepoClient of the outer manifest.
385 parent_groups: a string, the groups to apply to this projects.
386 submanifest_path: The submanifest root relative to the repo root.
387 default_groups: a string, the default manifest groups to use.
388 """
389 # TODO(vapier): Move this out of this class.
390 self.globalConfig = GitConfig.ForUser()
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400391
Gavin Makea2e3302023-03-11 06:46:20 +0000392 self.repodir = os.path.abspath(repodir)
393 self._CheckLocalPath(submanifest_path)
394 self.topdir = os.path.dirname(self.repodir)
395 if submanifest_path:
396 # This avoids a trailing os.path.sep when submanifest_path is empty.
397 self.topdir = os.path.join(self.topdir, submanifest_path)
398 if manifest_file != os.path.abspath(manifest_file):
399 raise ManifestParseError("manifest_file must be abspath")
400 self.manifestFile = manifest_file
401 if not outer_client or outer_client == self:
402 # manifestFileOverrides only exists in the outer_client's manifest,
403 # since that is the only instance left when Unload() is called on
404 # the outer manifest.
405 self.manifestFileOverrides = {}
406 self.local_manifests = local_manifests
407 self._load_local_manifests = True
408 self.parent_groups = parent_groups
409 self.default_groups = default_groups
LaMont Jonescc879a92021-11-18 22:40:18 +0000410
Gavin Makea2e3302023-03-11 06:46:20 +0000411 if outer_client and self.isGitcClient:
412 raise ManifestParseError(
413 "Multi-manifest is incompatible with `gitc-init`"
414 )
LaMont Jonescc879a92021-11-18 22:40:18 +0000415
Gavin Makea2e3302023-03-11 06:46:20 +0000416 if submanifest_path and not outer_client:
417 # If passing a submanifest_path, there must be an outer_client.
418 raise ManifestParseError(f"Bad call to {self.__class__.__name__}")
LaMont Jonescc879a92021-11-18 22:40:18 +0000419
Gavin Makea2e3302023-03-11 06:46:20 +0000420 # If self._outer_client is None, this is not a checkout that supports
421 # multi-tree.
422 self._outer_client = outer_client or self
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700423
Gavin Makea2e3302023-03-11 06:46:20 +0000424 self.repoProject = RepoProject(
425 self,
426 "repo",
427 gitdir=os.path.join(repodir, "repo/.git"),
428 worktree=os.path.join(repodir, "repo"),
429 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700430
Gavin Makea2e3302023-03-11 06:46:20 +0000431 mp = self.SubmanifestProject(self.path_prefix)
432 self.manifestProject = mp
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500433
Gavin Makea2e3302023-03-11 06:46:20 +0000434 # This is a bit hacky, but we're in a chicken & egg situation: all the
435 # normal repo settings live in the manifestProject which we just setup
436 # above, so we couldn't easily query before that. We assume Project()
437 # init doesn't care if this changes afterwards.
438 if os.path.exists(mp.gitdir) and mp.use_worktree:
439 mp.use_git_worktrees = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700440
Gavin Makea2e3302023-03-11 06:46:20 +0000441 self.Unload()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700442
Gavin Makea2e3302023-03-11 06:46:20 +0000443 def Override(self, name, load_local_manifests=True):
444 """Use a different manifest, just for the current instantiation."""
445 path = None
Basil Gelloc7453502018-05-25 20:23:52 +0300446
Gavin Makea2e3302023-03-11 06:46:20 +0000447 # Look for a manifest by path in the filesystem (including the cwd).
448 if not load_local_manifests:
449 local_path = os.path.abspath(name)
450 if os.path.isfile(local_path):
451 path = local_path
Basil Gelloc7453502018-05-25 20:23:52 +0300452
Gavin Makea2e3302023-03-11 06:46:20 +0000453 # Look for manifests by name from the manifests repo.
454 if path is None:
455 path = os.path.join(self.manifestProject.worktree, name)
456 if not os.path.isfile(path):
457 raise ManifestParseError("manifest %s not found" % name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700458
Gavin Makea2e3302023-03-11 06:46:20 +0000459 self._load_local_manifests = load_local_manifests
460 self._outer_client.manifestFileOverrides[self.path_prefix] = path
461 self.Unload()
462 self._Load()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700463
Gavin Makea2e3302023-03-11 06:46:20 +0000464 def Link(self, name):
465 """Update the repo metadata to use a different manifest."""
466 self.Override(name)
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700467
Gavin Makea2e3302023-03-11 06:46:20 +0000468 # Old versions of repo would generate symlinks we need to clean up.
469 platform_utils.remove(self.manifestFile, missing_ok=True)
470 # This file is interpreted as if it existed inside the manifest repo.
471 # That allows us to use <include> with the relative file name.
472 with open(self.manifestFile, "w") as fp:
473 fp.write(
474 """<?xml version="1.0" encoding="UTF-8"?>
Mike Frysingera269b1c2020-02-21 00:49:41 -0500475<!--
476DO NOT EDIT THIS FILE! It is generated by repo and changes will be discarded.
477If you want to use a different manifest, use `repo init -m <file>` instead.
478
479If you want to customize your checkout by overriding manifest settings, use
480the local_manifests/ directory instead.
481
482For more information on repo manifests, check out:
483https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
484-->
485<manifest>
486 <include name="%s" />
487</manifest>
Gavin Makea2e3302023-03-11 06:46:20 +0000488"""
489 % (name,)
490 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700491
Gavin Makea2e3302023-03-11 06:46:20 +0000492 def _RemoteToXml(self, r, doc, root):
493 e = doc.createElement("remote")
494 root.appendChild(e)
495 e.setAttribute("name", r.name)
496 e.setAttribute("fetch", r.fetchUrl)
497 if r.pushUrl is not None:
498 e.setAttribute("pushurl", r.pushUrl)
499 if r.remoteAlias is not None:
500 e.setAttribute("alias", r.remoteAlias)
501 if r.reviewUrl is not None:
502 e.setAttribute("review", r.reviewUrl)
503 if r.revision is not None:
504 e.setAttribute("revision", r.revision)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800505
Gavin Makea2e3302023-03-11 06:46:20 +0000506 for a in r.annotations:
507 if a.keep == "true":
508 ae = doc.createElement("annotation")
509 ae.setAttribute("name", a.name)
510 ae.setAttribute("value", a.value)
511 e.appendChild(ae)
Jack Neus6ea0cae2021-07-20 20:52:33 +0000512
Gavin Makea2e3302023-03-11 06:46:20 +0000513 def _SubmanifestToXml(self, r, doc, root):
514 """Generate XML <submanifest/> node."""
515 e = doc.createElement("submanifest")
516 root.appendChild(e)
517 e.setAttribute("name", r.name)
518 if r.remote is not None:
519 e.setAttribute("remote", r.remote)
520 if r.project is not None:
521 e.setAttribute("project", r.project)
522 if r.manifestName is not None:
523 e.setAttribute("manifest-name", r.manifestName)
524 if r.revision is not None:
525 e.setAttribute("revision", r.revision)
526 if r.path is not None:
527 e.setAttribute("path", r.path)
528 if r.groups:
529 e.setAttribute("groups", r.GetGroupsStr())
530 if r.default_groups:
531 e.setAttribute("default-groups", r.GetDefaultGroupsStr())
LaMont Jonescc879a92021-11-18 22:40:18 +0000532
Gavin Makea2e3302023-03-11 06:46:20 +0000533 for a in r.annotations:
534 if a.keep == "true":
535 ae = doc.createElement("annotation")
536 ae.setAttribute("name", a.name)
537 ae.setAttribute("value", a.value)
538 e.appendChild(ae)
LaMont Jonescc879a92021-11-18 22:40:18 +0000539
Gavin Makea2e3302023-03-11 06:46:20 +0000540 def _ParseList(self, field):
541 """Parse fields that contain flattened lists.
Mike Frysinger51e39d52020-12-04 05:32:06 -0500542
Gavin Makea2e3302023-03-11 06:46:20 +0000543 These are whitespace & comma separated. Empty elements will be
544 discarded.
545 """
546 return [x for x in re.split(r"[,\s]+", field) if x]
Josh Triplett884a3872014-06-12 14:57:29 -0700547
Gavin Makea2e3302023-03-11 06:46:20 +0000548 def ToXml(
549 self,
550 peg_rev=False,
551 peg_rev_upstream=True,
552 peg_rev_dest_branch=True,
553 groups=None,
554 omit_local=False,
555 ):
556 """Return the current manifest XML."""
557 mp = self.manifestProject
Colin Cross5acde752012-03-28 20:15:45 -0700558
Gavin Makea2e3302023-03-11 06:46:20 +0000559 if groups is None:
560 groups = mp.manifest_groups
561 if groups:
562 groups = self._ParseList(groups)
Colin Cross5acde752012-03-28 20:15:45 -0700563
Gavin Makea2e3302023-03-11 06:46:20 +0000564 doc = xml.dom.minidom.Document()
565 root = doc.createElement("manifest")
566 if self.is_submanifest:
567 root.setAttribute("path", self.path_prefix)
568 doc.appendChild(root)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800569
Gavin Makea2e3302023-03-11 06:46:20 +0000570 # Save out the notice. There's a little bit of work here to give it the
571 # right whitespace, which assumes that the notice is automatically
572 # indented by 4 by minidom.
573 if self.notice:
574 notice_element = root.appendChild(doc.createElement("notice"))
575 notice_lines = self.notice.splitlines()
576 indented_notice = (
577 "\n".join(" " * 4 + line for line in notice_lines)
578 )[4:]
579 notice_element.appendChild(doc.createTextNode(indented_notice))
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700580
Gavin Makea2e3302023-03-11 06:46:20 +0000581 d = self.default
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800582
Gavin Makea2e3302023-03-11 06:46:20 +0000583 for r in sorted(self.remotes):
584 self._RemoteToXml(self.remotes[r], doc, root)
585 if self.remotes:
586 root.appendChild(doc.createTextNode(""))
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800587
Gavin Makea2e3302023-03-11 06:46:20 +0000588 have_default = False
589 e = doc.createElement("default")
590 if d.remote:
591 have_default = True
592 e.setAttribute("remote", d.remote.name)
593 if d.revisionExpr:
594 have_default = True
595 e.setAttribute("revision", d.revisionExpr)
596 if d.destBranchExpr:
597 have_default = True
598 e.setAttribute("dest-branch", d.destBranchExpr)
599 if d.upstreamExpr:
600 have_default = True
601 e.setAttribute("upstream", d.upstreamExpr)
602 if d.sync_j is not None:
603 have_default = True
604 e.setAttribute("sync-j", "%d" % d.sync_j)
605 if d.sync_c:
606 have_default = True
607 e.setAttribute("sync-c", "true")
608 if d.sync_s:
609 have_default = True
610 e.setAttribute("sync-s", "true")
611 if not d.sync_tags:
612 have_default = True
613 e.setAttribute("sync-tags", "false")
614 if have_default:
615 root.appendChild(e)
616 root.appendChild(doc.createTextNode(""))
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800617
Gavin Makea2e3302023-03-11 06:46:20 +0000618 if self._manifest_server:
619 e = doc.createElement("manifest-server")
620 e.setAttribute("url", self._manifest_server)
621 root.appendChild(e)
622 root.appendChild(doc.createTextNode(""))
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700623
Gavin Makea2e3302023-03-11 06:46:20 +0000624 for r in sorted(self.submanifests):
625 self._SubmanifestToXml(self.submanifests[r], doc, root)
626 if self.submanifests:
627 root.appendChild(doc.createTextNode(""))
LaMont Jonescc879a92021-11-18 22:40:18 +0000628
Gavin Makea2e3302023-03-11 06:46:20 +0000629 def output_projects(parent, parent_node, projects):
630 for project_name in projects:
631 for project in self._projects[project_name]:
632 output_project(parent, parent_node, project)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800633
Gavin Makea2e3302023-03-11 06:46:20 +0000634 def output_project(parent, parent_node, p):
635 if not p.MatchesGroups(groups):
636 return
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800637
Gavin Makea2e3302023-03-11 06:46:20 +0000638 if omit_local and self.IsFromLocalManifest(p):
639 return
LaMont Jonesa8cf5752022-07-15 20:31:33 +0000640
Gavin Makea2e3302023-03-11 06:46:20 +0000641 name = p.name
642 relpath = p.relpath
643 if parent:
644 name = self._UnjoinName(parent.name, name)
645 relpath = self._UnjoinRelpath(parent.relpath, relpath)
Colin Cross5acde752012-03-28 20:15:45 -0700646
Gavin Makea2e3302023-03-11 06:46:20 +0000647 e = doc.createElement("project")
648 parent_node.appendChild(e)
649 e.setAttribute("name", name)
650 if relpath != name:
651 e.setAttribute("path", relpath)
652 remoteName = None
653 if d.remote:
654 remoteName = d.remote.name
655 if not d.remote or p.remote.orig_name != remoteName:
656 remoteName = p.remote.orig_name
657 e.setAttribute("remote", remoteName)
658 if peg_rev:
659 if self.IsMirror:
660 value = p.bare_git.rev_parse(p.revisionExpr + "^0")
661 else:
662 value = p.work_git.rev_parse(HEAD + "^0")
663 e.setAttribute("revision", value)
664 if peg_rev_upstream:
665 if p.upstream:
666 e.setAttribute("upstream", p.upstream)
667 elif value != p.revisionExpr:
668 # Only save the origin if the origin is not a sha1, and
669 # the default isn't our value
670 e.setAttribute("upstream", p.revisionExpr)
671
672 if peg_rev_dest_branch:
673 if p.dest_branch:
674 e.setAttribute("dest-branch", p.dest_branch)
675 elif value != p.revisionExpr:
676 e.setAttribute("dest-branch", p.revisionExpr)
677
678 else:
679 revision = (
680 self.remotes[p.remote.orig_name].revision or d.revisionExpr
681 )
682 if not revision or revision != p.revisionExpr:
683 e.setAttribute("revision", p.revisionExpr)
684 elif p.revisionId:
685 e.setAttribute("revision", p.revisionId)
686 if p.upstream and (
687 p.upstream != p.revisionExpr or p.upstream != d.upstreamExpr
688 ):
689 e.setAttribute("upstream", p.upstream)
690
691 if p.dest_branch and p.dest_branch != d.destBranchExpr:
692 e.setAttribute("dest-branch", p.dest_branch)
693
694 for c in p.copyfiles:
695 ce = doc.createElement("copyfile")
696 ce.setAttribute("src", c.src)
697 ce.setAttribute("dest", c.dest)
698 e.appendChild(ce)
699
700 for lf in p.linkfiles:
701 le = doc.createElement("linkfile")
702 le.setAttribute("src", lf.src)
703 le.setAttribute("dest", lf.dest)
704 e.appendChild(le)
705
706 default_groups = ["all", "name:%s" % p.name, "path:%s" % p.relpath]
707 egroups = [g for g in p.groups if g not in default_groups]
708 if egroups:
709 e.setAttribute("groups", ",".join(egroups))
710
711 for a in p.annotations:
712 if a.keep == "true":
713 ae = doc.createElement("annotation")
714 ae.setAttribute("name", a.name)
715 ae.setAttribute("value", a.value)
716 e.appendChild(ae)
717
718 if p.sync_c:
719 e.setAttribute("sync-c", "true")
720
721 if p.sync_s:
722 e.setAttribute("sync-s", "true")
723
724 if not p.sync_tags:
725 e.setAttribute("sync-tags", "false")
726
727 if p.clone_depth:
728 e.setAttribute("clone-depth", str(p.clone_depth))
729
730 self._output_manifest_project_extras(p, e)
731
732 if p.subprojects:
733 subprojects = set(subp.name for subp in p.subprojects)
734 output_projects(p, e, list(sorted(subprojects)))
735
736 projects = set(p.name for p in self._paths.values() if not p.parent)
737 output_projects(None, root, list(sorted(projects)))
738
739 if self._repo_hooks_project:
740 root.appendChild(doc.createTextNode(""))
741 e = doc.createElement("repo-hooks")
742 e.setAttribute("in-project", self._repo_hooks_project.name)
743 e.setAttribute(
744 "enabled-list",
745 " ".join(self._repo_hooks_project.enabled_repo_hooks),
746 )
747 root.appendChild(e)
748
749 if self._superproject:
750 root.appendChild(doc.createTextNode(""))
751 e = doc.createElement("superproject")
752 e.setAttribute("name", self._superproject.name)
753 remoteName = None
754 if d.remote:
755 remoteName = d.remote.name
756 remote = self._superproject.remote
757 if not d.remote or remote.orig_name != remoteName:
758 remoteName = remote.orig_name
759 e.setAttribute("remote", remoteName)
760 revision = remote.revision or d.revisionExpr
761 if not revision or revision != self._superproject.revision:
762 e.setAttribute("revision", self._superproject.revision)
763 root.appendChild(e)
764
765 if self._contactinfo.bugurl != Wrapper().BUG_URL:
766 root.appendChild(doc.createTextNode(""))
767 e = doc.createElement("contactinfo")
768 e.setAttribute("bugurl", self._contactinfo.bugurl)
769 root.appendChild(e)
770
771 return doc
772
773 def ToDict(self, **kwargs):
774 """Return the current manifest as a dictionary."""
775 # Elements that may only appear once.
776 SINGLE_ELEMENTS = {
777 "notice",
778 "default",
779 "manifest-server",
780 "repo-hooks",
781 "superproject",
782 "contactinfo",
783 }
784 # Elements that may be repeated.
785 MULTI_ELEMENTS = {
786 "remote",
787 "remove-project",
788 "project",
789 "extend-project",
790 "include",
791 "submanifest",
792 # These are children of 'project' nodes.
793 "annotation",
794 "project",
795 "copyfile",
796 "linkfile",
797 }
798
799 doc = self.ToXml(**kwargs)
800 ret = {}
801
802 def append_children(ret, node):
803 for child in node.childNodes:
804 if child.nodeType == xml.dom.Node.ELEMENT_NODE:
805 attrs = child.attributes
806 element = dict(
807 (attrs.item(i).localName, attrs.item(i).value)
808 for i in range(attrs.length)
809 )
810 if child.nodeName in SINGLE_ELEMENTS:
811 ret[child.nodeName] = element
812 elif child.nodeName in MULTI_ELEMENTS:
813 ret.setdefault(child.nodeName, []).append(element)
814 else:
815 raise ManifestParseError(
816 'Unhandled element "%s"' % (child.nodeName,)
817 )
818
819 append_children(element, child)
820
821 append_children(ret, doc.firstChild)
822
823 return ret
824
825 def Save(self, fd, **kwargs):
826 """Write the current manifest out to the given file descriptor."""
827 doc = self.ToXml(**kwargs)
828 doc.writexml(fd, "", " ", "\n", "UTF-8")
829
830 def _output_manifest_project_extras(self, p, e):
831 """Manifests can modify e if they support extra project attributes."""
832
833 @property
834 def is_multimanifest(self):
835 """Whether this is a multimanifest checkout.
836
837 This is safe to use as long as the outermost manifest XML has been
838 parsed.
839 """
840 return bool(self._outer_client._submanifests)
841
842 @property
843 def is_submanifest(self):
844 """Whether this manifest is a submanifest.
845
846 This is safe to use as long as the outermost manifest XML has been
847 parsed.
848 """
849 return self._outer_client and self._outer_client != self
850
851 @property
852 def outer_client(self):
853 """The instance of the outermost manifest client."""
854 self._Load()
855 return self._outer_client
856
857 @property
858 def all_manifests(self):
859 """Generator yielding all (sub)manifests, in depth-first order."""
860 self._Load()
861 outer = self._outer_client
862 yield outer
863 for tree in outer.all_children:
864 yield tree
865
866 @property
867 def all_children(self):
868 """Generator yielding all (present) child submanifests."""
869 self._Load()
870 for child in self._submanifests.values():
871 if child.repo_client:
872 yield child.repo_client
873 for tree in child.repo_client.all_children:
874 yield tree
875
876 @property
877 def path_prefix(self):
878 """The path of this submanifest, relative to the outermost manifest."""
879 if not self._outer_client or self == self._outer_client:
880 return ""
881 return os.path.relpath(self.topdir, self._outer_client.topdir)
882
883 @property
884 def all_paths(self):
885 """All project paths for all (sub)manifests.
886
887 See also `paths`.
888
889 Returns:
890 A dictionary of {path: Project()}. `path` is relative to the outer
891 manifest.
892 """
893 ret = {}
894 for tree in self.all_manifests:
895 prefix = tree.path_prefix
896 ret.update(
897 {os.path.join(prefix, k): v for k, v in tree.paths.items()}
898 )
899 return ret
900
901 @property
902 def all_projects(self):
903 """All projects for all (sub)manifests. See `projects`."""
904 return list(
905 itertools.chain.from_iterable(
906 x._paths.values() for x in self.all_manifests
907 )
908 )
909
910 @property
911 def paths(self):
912 """Return all paths for this manifest.
913
914 Returns:
915 A dictionary of {path: Project()}. `path` is relative to this
916 manifest.
917 """
918 self._Load()
919 return self._paths
920
921 @property
922 def projects(self):
923 """Return a list of all Projects in this manifest."""
924 self._Load()
925 return list(self._paths.values())
926
927 @property
928 def remotes(self):
929 """Return a list of remotes for this manifest."""
930 self._Load()
931 return self._remotes
932
933 @property
934 def default(self):
935 """Return default values for this manifest."""
936 self._Load()
937 return self._default
938
939 @property
940 def submanifests(self):
941 """All submanifests in this manifest."""
942 self._Load()
943 return self._submanifests
944
945 @property
946 def repo_hooks_project(self):
947 self._Load()
948 return self._repo_hooks_project
949
950 @property
951 def superproject(self):
952 self._Load()
953 return self._superproject
954
955 @property
956 def contactinfo(self):
957 self._Load()
958 return self._contactinfo
959
960 @property
961 def notice(self):
962 self._Load()
963 return self._notice
964
965 @property
966 def manifest_server(self):
967 self._Load()
968 return self._manifest_server
969
970 @property
971 def CloneBundle(self):
972 clone_bundle = self.manifestProject.clone_bundle
973 if clone_bundle is None:
974 return False if self.manifestProject.partial_clone else True
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800975 else:
Gavin Makea2e3302023-03-11 06:46:20 +0000976 return clone_bundle
Sean McAllisteraf908cb2020-04-20 08:41:58 -0600977
Gavin Makea2e3302023-03-11 06:46:20 +0000978 @property
979 def CloneFilter(self):
980 if self.manifestProject.partial_clone:
981 return self.manifestProject.clone_filter
982 return None
Sean McAllisteraf908cb2020-04-20 08:41:58 -0600983
Gavin Makea2e3302023-03-11 06:46:20 +0000984 @property
985 def PartialCloneExclude(self):
986 exclude = self.manifest.manifestProject.partial_clone_exclude or ""
987 return set(x.strip() for x in exclude.split(","))
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800988
Gavin Makea2e3302023-03-11 06:46:20 +0000989 def SetManifestOverride(self, path):
990 """Override manifestFile. The caller must call Unload()"""
991 self._outer_client.manifest.manifestFileOverrides[
992 self.path_prefix
993 ] = path
Simon Ruggier7e59de22015-07-24 12:50:06 +0200994
Gavin Makea2e3302023-03-11 06:46:20 +0000995 @property
996 def UseLocalManifests(self):
997 return self._load_local_manifests
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800998
Gavin Makea2e3302023-03-11 06:46:20 +0000999 def SetUseLocalManifests(self, value):
1000 self._load_local_manifests = value
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001001
Gavin Makea2e3302023-03-11 06:46:20 +00001002 @property
1003 def HasLocalManifests(self):
1004 return self._load_local_manifests and self.local_manifests
Colin Cross5acde752012-03-28 20:15:45 -07001005
Gavin Makea2e3302023-03-11 06:46:20 +00001006 def IsFromLocalManifest(self, project):
1007 """Is the project from a local manifest?"""
1008 return any(
1009 x.startswith(LOCAL_MANIFEST_GROUP_PREFIX) for x in project.groups
1010 )
James W. Mills24c13082012-04-12 15:04:13 -05001011
Gavin Makea2e3302023-03-11 06:46:20 +00001012 @property
1013 def IsMirror(self):
1014 return self.manifestProject.mirror
Anatol Pomazau79770d22012-04-20 14:41:59 -07001015
Gavin Makea2e3302023-03-11 06:46:20 +00001016 @property
1017 def UseGitWorktrees(self):
1018 return self.manifestProject.use_worktree
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001019
Gavin Makea2e3302023-03-11 06:46:20 +00001020 @property
1021 def IsArchive(self):
1022 return self.manifestProject.archive
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +09001023
Gavin Makea2e3302023-03-11 06:46:20 +00001024 @property
1025 def HasSubmodules(self):
1026 return self.manifestProject.submodules
Dan Willemsen88409222015-08-17 15:29:10 -07001027
Gavin Makea2e3302023-03-11 06:46:20 +00001028 @property
1029 def EnableGitLfs(self):
1030 return self.manifestProject.git_lfs
Simran Basib9a1b732015-08-20 12:19:28 -07001031
Gavin Makea2e3302023-03-11 06:46:20 +00001032 def FindManifestByPath(self, path):
1033 """Returns the manifest containing path."""
1034 path = os.path.abspath(path)
1035 manifest = self._outer_client or self
1036 old = None
1037 while manifest._submanifests and manifest != old:
1038 old = manifest
1039 for name in manifest._submanifests:
1040 tree = manifest._submanifests[name]
1041 if path.startswith(tree.repo_client.manifest.topdir):
1042 manifest = tree.repo_client
1043 break
1044 return manifest
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001045
Gavin Makea2e3302023-03-11 06:46:20 +00001046 @property
1047 def subdir(self):
1048 """Returns the path for per-submanifest objects for this manifest."""
1049 return self.SubmanifestInfoDir(self.path_prefix)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001050
Gavin Makea2e3302023-03-11 06:46:20 +00001051 def SubmanifestInfoDir(self, submanifest_path, object_path=""):
1052 """Return the path to submanifest-specific info for a submanifest.
Doug Anderson37282b42011-03-04 11:54:18 -08001053
Gavin Makea2e3302023-03-11 06:46:20 +00001054 Return the full path of the directory in which to put per-manifest
1055 objects.
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001056
Gavin Makea2e3302023-03-11 06:46:20 +00001057 Args:
1058 submanifest_path: a string, the path of the submanifest, relative to
1059 the outermost topdir. If empty, then repodir is returned.
1060 object_path: a string, relative path to append to the submanifest
1061 info directory path.
1062 """
1063 if submanifest_path:
1064 return os.path.join(
1065 self.repodir, SUBMANIFEST_DIR, submanifest_path, object_path
1066 )
1067 else:
1068 return os.path.join(self.repodir, object_path)
Raman Tenneti1c3f57e2021-05-04 12:32:13 -07001069
Gavin Makea2e3302023-03-11 06:46:20 +00001070 def SubmanifestProject(self, submanifest_path):
1071 """Return a manifestProject for a submanifest."""
1072 subdir = self.SubmanifestInfoDir(submanifest_path)
1073 mp = ManifestProject(
1074 self,
1075 "manifests",
1076 gitdir=os.path.join(subdir, "manifests.git"),
1077 worktree=os.path.join(subdir, "manifests"),
1078 )
1079 return mp
Mike Frysinger23411d32020-09-02 04:31:10 -04001080
Gavin Makea2e3302023-03-11 06:46:20 +00001081 def GetDefaultGroupsStr(self, with_platform=True):
1082 """Returns the default group string to use.
Mike Frysinger23411d32020-09-02 04:31:10 -04001083
Gavin Makea2e3302023-03-11 06:46:20 +00001084 Args:
1085 with_platform: a boolean, whether to include the group for the
1086 underlying platform.
1087 """
1088 groups = ",".join(self.default_groups or ["default"])
1089 if with_platform:
1090 groups += f",platform-{platform.system().lower()}"
1091 return groups
Mike Frysinger23411d32020-09-02 04:31:10 -04001092
Gavin Makea2e3302023-03-11 06:46:20 +00001093 def GetGroupsStr(self):
1094 """Returns the manifest group string that should be synced."""
1095 return (
1096 self.manifestProject.manifest_groups or self.GetDefaultGroupsStr()
1097 )
Mike Frysinger23411d32020-09-02 04:31:10 -04001098
Gavin Makea2e3302023-03-11 06:46:20 +00001099 def Unload(self):
1100 """Unload the manifest.
Mike Frysinger23411d32020-09-02 04:31:10 -04001101
Gavin Makea2e3302023-03-11 06:46:20 +00001102 If the manifest files have been changed since Load() was called, this
1103 will cause the new/updated manifest to be used.
Mike Frysinger23411d32020-09-02 04:31:10 -04001104
Gavin Makea2e3302023-03-11 06:46:20 +00001105 """
1106 self._loaded = False
1107 self._projects = {}
1108 self._paths = {}
1109 self._remotes = {}
1110 self._default = None
1111 self._submanifests = {}
1112 self._repo_hooks_project = None
1113 self._superproject = None
1114 self._contactinfo = ContactInfo(Wrapper().BUG_URL)
1115 self._notice = None
1116 self.branch = None
1117 self._manifest_server = None
Mike Frysinger23411d32020-09-02 04:31:10 -04001118
Gavin Makea2e3302023-03-11 06:46:20 +00001119 def Load(self):
1120 """Read the manifest into memory."""
1121 # Do not expose internal arguments.
1122 self._Load()
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -08001123
Gavin Makea2e3302023-03-11 06:46:20 +00001124 def _Load(self, initial_client=None, submanifest_depth=0):
1125 if submanifest_depth > MAX_SUBMANIFEST_DEPTH:
1126 raise ManifestParseError(
1127 "maximum submanifest depth %d exceeded." % MAX_SUBMANIFEST_DEPTH
1128 )
1129 if not self._loaded:
1130 if self._outer_client and self._outer_client != self:
1131 # This will load all clients.
1132 self._outer_client._Load(initial_client=self)
Simran Basib9a1b732015-08-20 12:19:28 -07001133
Gavin Makea2e3302023-03-11 06:46:20 +00001134 savedManifestFile = self.manifestFile
1135 override = self._outer_client.manifestFileOverrides.get(
1136 self.path_prefix
1137 )
1138 if override:
1139 self.manifestFile = override
Mike Frysinger1d00a7e2021-12-21 00:40:31 -05001140
Gavin Makea2e3302023-03-11 06:46:20 +00001141 try:
1142 m = self.manifestProject
1143 b = m.GetBranch(m.CurrentBranch).merge
1144 if b is not None and b.startswith(R_HEADS):
1145 b = b[len(R_HEADS) :]
1146 self.branch = b
LaMont Jonescc879a92021-11-18 22:40:18 +00001147
Gavin Makea2e3302023-03-11 06:46:20 +00001148 parent_groups = self.parent_groups
1149 if self.path_prefix:
1150 parent_groups = (
1151 f"{SUBMANIFEST_GROUP_PREFIX}:path:"
1152 f"{self.path_prefix},{parent_groups}"
1153 )
LaMont Jonesff6b1da2022-06-01 21:03:34 +00001154
Gavin Makea2e3302023-03-11 06:46:20 +00001155 # The manifestFile was specified by the user which is why we
1156 # allow include paths to point anywhere.
1157 nodes = []
1158 nodes.append(
1159 self._ParseManifestXml(
1160 self.manifestFile,
1161 self.manifestProject.worktree,
1162 parent_groups=parent_groups,
1163 restrict_includes=False,
1164 )
1165 )
LaMont Jonescc879a92021-11-18 22:40:18 +00001166
Gavin Makea2e3302023-03-11 06:46:20 +00001167 if self._load_local_manifests and self.local_manifests:
1168 try:
1169 for local_file in sorted(
1170 platform_utils.listdir(self.local_manifests)
1171 ):
1172 if local_file.endswith(".xml"):
1173 local = os.path.join(
1174 self.local_manifests, local_file
1175 )
1176 # Since local manifests are entirely managed by
1177 # the user, allow them to point anywhere the
1178 # user wants.
1179 local_group = (
1180 f"{LOCAL_MANIFEST_GROUP_PREFIX}:"
1181 f"{local_file[:-4]}"
1182 )
1183 nodes.append(
1184 self._ParseManifestXml(
1185 local,
1186 self.subdir,
1187 parent_groups=(
1188 f"{local_group},{parent_groups}"
1189 ),
1190 restrict_includes=False,
1191 )
1192 )
1193 except OSError:
1194 pass
Raman Tenneti080877e2021-03-09 15:19:06 -08001195
Gavin Makea2e3302023-03-11 06:46:20 +00001196 try:
1197 self._ParseManifest(nodes)
1198 except ManifestParseError as e:
1199 # There was a problem parsing, unload ourselves in case they
1200 # catch this error and try again later, we will show the
1201 # correct error
1202 self.Unload()
1203 raise e
Raman Tenneti080877e2021-03-09 15:19:06 -08001204
Gavin Makea2e3302023-03-11 06:46:20 +00001205 if self.IsMirror:
1206 self._AddMetaProjectMirror(self.repoProject)
1207 self._AddMetaProjectMirror(self.manifestProject)
LaMont Jonesa2ff20d2022-04-07 16:49:06 +00001208
Gavin Makea2e3302023-03-11 06:46:20 +00001209 self._loaded = True
1210 finally:
1211 if override:
1212 self.manifestFile = savedManifestFile
LaMont Jonesa2ff20d2022-04-07 16:49:06 +00001213
Gavin Makea2e3302023-03-11 06:46:20 +00001214 # Now that we have loaded this manifest, load any submanifests as
1215 # well. We need to do this after self._loaded is set to avoid
1216 # looping.
1217 for name in self._submanifests:
1218 tree = self._submanifests[name]
1219 tree.ToSubmanifestSpec()
1220 present = os.path.exists(
1221 os.path.join(self.subdir, MANIFEST_FILE_NAME)
1222 )
1223 if present and tree.present and not tree.repo_client:
1224 if initial_client and initial_client.topdir == self.topdir:
1225 tree.repo_client = self
1226 tree.present = present
1227 elif not os.path.exists(self.subdir):
1228 tree.present = False
1229 if present and tree.present:
1230 tree.repo_client._Load(
1231 initial_client=initial_client,
1232 submanifest_depth=submanifest_depth + 1,
1233 )
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001234
Gavin Makea2e3302023-03-11 06:46:20 +00001235 def _ParseManifestXml(
1236 self, path, include_root, parent_groups="", restrict_includes=True
1237 ):
1238 """Parse a manifest XML and return the computed nodes.
LaMont Jonesa2ff20d2022-04-07 16:49:06 +00001239
Gavin Makea2e3302023-03-11 06:46:20 +00001240 Args:
1241 path: The XML file to read & parse.
1242 include_root: The path to interpret include "name"s relative to.
1243 parent_groups: The groups to apply to this projects.
1244 restrict_includes: Whether to constrain the "name" attribute of
1245 includes.
LaMont Jonescc879a92021-11-18 22:40:18 +00001246
Gavin Makea2e3302023-03-11 06:46:20 +00001247 Returns:
1248 List of XML nodes.
1249 """
1250 try:
1251 root = xml.dom.minidom.parse(path)
1252 except (OSError, xml.parsers.expat.ExpatError) as e:
1253 raise ManifestParseError(
1254 "error parsing manifest %s: %s" % (path, e)
1255 )
David Pursehouse2d5a0df2012-11-13 02:50:36 +09001256
Gavin Makea2e3302023-03-11 06:46:20 +00001257 if not root or not root.childNodes:
1258 raise ManifestParseError("no root node in %s" % (path,))
Shawn O. Pearce5cc66792008-10-23 16:19:27 -07001259
Gavin Makea2e3302023-03-11 06:46:20 +00001260 for manifest in root.childNodes:
1261 if manifest.nodeName == "manifest":
1262 break
1263 else:
1264 raise ManifestParseError("no <manifest> in %s" % (path,))
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001265
LaMont Jonesb90a4222022-04-14 15:00:09 +00001266 nodes = []
Gavin Makea2e3302023-03-11 06:46:20 +00001267 for node in manifest.childNodes:
1268 if node.nodeName == "include":
1269 name = self._reqatt(node, "name")
1270 if restrict_includes:
1271 msg = self._CheckLocalPath(name)
1272 if msg:
1273 raise ManifestInvalidPathError(
1274 '<include> invalid "name": %s: %s' % (name, msg)
1275 )
1276 include_groups = ""
1277 if parent_groups:
1278 include_groups = parent_groups
1279 if node.hasAttribute("groups"):
1280 include_groups = (
1281 node.getAttribute("groups") + "," + include_groups
1282 )
1283 fp = os.path.join(include_root, name)
1284 if not os.path.isfile(fp):
1285 raise ManifestParseError(
1286 "include [%s/]%s doesn't exist or isn't a file"
1287 % (include_root, name)
1288 )
1289 try:
1290 nodes.extend(
1291 self._ParseManifestXml(fp, include_root, include_groups)
1292 )
1293 # should isolate this to the exact exception, but that's
1294 # tricky. actual parsing implementation may vary.
1295 except (
1296 KeyboardInterrupt,
1297 RuntimeError,
1298 SystemExit,
1299 ManifestParseError,
1300 ):
1301 raise
1302 except Exception as e:
1303 raise ManifestParseError(
1304 "failed parsing included manifest %s: %s" % (name, e)
1305 )
1306 else:
1307 if parent_groups and node.nodeName == "project":
1308 nodeGroups = parent_groups
1309 if node.hasAttribute("groups"):
1310 nodeGroups = (
1311 node.getAttribute("groups") + "," + nodeGroups
1312 )
1313 node.setAttribute("groups", nodeGroups)
1314 nodes.append(node)
1315 return nodes
LaMont Jonesb90a4222022-04-14 15:00:09 +00001316
Gavin Makea2e3302023-03-11 06:46:20 +00001317 def _ParseManifest(self, node_list):
1318 for node in itertools.chain(*node_list):
1319 if node.nodeName == "remote":
1320 remote = self._ParseRemote(node)
1321 if remote:
1322 if remote.name in self._remotes:
1323 if remote != self._remotes[remote.name]:
1324 raise ManifestParseError(
1325 "remote %s already exists with different "
1326 "attributes" % (remote.name)
1327 )
1328 else:
1329 self._remotes[remote.name] = remote
LaMont Jonesb90a4222022-04-14 15:00:09 +00001330
Gavin Makea2e3302023-03-11 06:46:20 +00001331 for node in itertools.chain(*node_list):
1332 if node.nodeName == "default":
1333 new_default = self._ParseDefault(node)
1334 emptyDefault = (
1335 not node.hasAttributes() and not node.hasChildNodes()
1336 )
1337 if self._default is None:
1338 self._default = new_default
1339 elif not emptyDefault and new_default != self._default:
1340 raise ManifestParseError(
1341 "duplicate default in %s" % (self.manifestFile)
1342 )
LaMont Jonesb90a4222022-04-14 15:00:09 +00001343
Julien Campergue74879922013-10-09 14:38:46 +02001344 if self._default is None:
Gavin Makea2e3302023-03-11 06:46:20 +00001345 self._default = _Default()
Julien Campergue74879922013-10-09 14:38:46 +02001346
Gavin Makea2e3302023-03-11 06:46:20 +00001347 submanifest_paths = set()
1348 for node in itertools.chain(*node_list):
1349 if node.nodeName == "submanifest":
1350 submanifest = self._ParseSubmanifest(node)
1351 if submanifest:
1352 if submanifest.name in self._submanifests:
1353 if submanifest != self._submanifests[submanifest.name]:
1354 raise ManifestParseError(
1355 "submanifest %s already exists with different "
1356 "attributes" % (submanifest.name)
1357 )
1358 else:
1359 self._submanifests[submanifest.name] = submanifest
1360 submanifest_paths.add(submanifest.relpath)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001361
Gavin Makea2e3302023-03-11 06:46:20 +00001362 for node in itertools.chain(*node_list):
1363 if node.nodeName == "notice":
1364 if self._notice is not None:
1365 raise ManifestParseError(
1366 "duplicate notice in %s" % (self.manifestFile)
1367 )
1368 self._notice = self._ParseNotice(node)
LaMont Jonescc879a92021-11-18 22:40:18 +00001369
Gavin Makea2e3302023-03-11 06:46:20 +00001370 for node in itertools.chain(*node_list):
1371 if node.nodeName == "manifest-server":
1372 url = self._reqatt(node, "url")
1373 if self._manifest_server is not None:
1374 raise ManifestParseError(
1375 "duplicate manifest-server in %s" % (self.manifestFile)
1376 )
1377 self._manifest_server = url
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001378
Gavin Makea2e3302023-03-11 06:46:20 +00001379 def recursively_add_projects(project):
1380 projects = self._projects.setdefault(project.name, [])
1381 if project.relpath is None:
1382 raise ManifestParseError(
1383 "missing path for %s in %s"
1384 % (project.name, self.manifestFile)
1385 )
1386 if project.relpath in self._paths:
1387 raise ManifestParseError(
1388 "duplicate path %s in %s"
1389 % (project.relpath, self.manifestFile)
1390 )
1391 for tree in submanifest_paths:
1392 if project.relpath.startswith(tree):
1393 raise ManifestParseError(
1394 "project %s conflicts with submanifest path %s"
1395 % (project.relpath, tree)
1396 )
1397 self._paths[project.relpath] = project
1398 projects.append(project)
1399 for subproject in project.subprojects:
1400 recursively_add_projects(subproject)
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001401
Gavin Makea2e3302023-03-11 06:46:20 +00001402 repo_hooks_project = None
1403 enabled_repo_hooks = None
1404 for node in itertools.chain(*node_list):
1405 if node.nodeName == "project":
1406 project = self._ParseProject(node)
1407 recursively_add_projects(project)
1408 if node.nodeName == "extend-project":
1409 name = self._reqatt(node, "name")
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001410
Gavin Makea2e3302023-03-11 06:46:20 +00001411 if name not in self._projects:
1412 raise ManifestParseError(
1413 "extend-project element specifies non-existent "
1414 "project: %s" % name
1415 )
1416
1417 path = node.getAttribute("path")
1418 dest_path = node.getAttribute("dest-path")
1419 groups = node.getAttribute("groups")
1420 if groups:
1421 groups = self._ParseList(groups)
1422 revision = node.getAttribute("revision")
1423 remote_name = node.getAttribute("remote")
1424 if not remote_name:
1425 remote = self._default.remote
1426 else:
1427 remote = self._get_remote(node)
1428 dest_branch = node.getAttribute("dest-branch")
1429 upstream = node.getAttribute("upstream")
1430
1431 named_projects = self._projects[name]
1432 if dest_path and not path and len(named_projects) > 1:
1433 raise ManifestParseError(
1434 "extend-project cannot use dest-path when "
1435 "matching multiple projects: %s" % name
1436 )
1437 for p in self._projects[name]:
1438 if path and p.relpath != path:
1439 continue
1440 if groups:
1441 p.groups.extend(groups)
1442 if revision:
1443 p.SetRevision(revision)
1444
1445 if remote_name:
1446 p.remote = remote.ToRemoteSpec(name)
1447 if dest_branch:
1448 p.dest_branch = dest_branch
1449 if upstream:
1450 p.upstream = upstream
1451
1452 if dest_path:
1453 del self._paths[p.relpath]
1454 (
1455 relpath,
1456 worktree,
1457 gitdir,
1458 objdir,
1459 _,
1460 ) = self.GetProjectPaths(name, dest_path, remote.name)
1461 p.UpdatePaths(relpath, worktree, gitdir, objdir)
1462 self._paths[p.relpath] = p
1463
1464 if node.nodeName == "repo-hooks":
1465 # Only one project can be the hooks project
1466 if repo_hooks_project is not None:
1467 raise ManifestParseError(
1468 "duplicate repo-hooks in %s" % (self.manifestFile)
1469 )
1470
1471 # Get the name of the project and the (space-separated) list of
1472 # enabled.
1473 repo_hooks_project = self._reqatt(node, "in-project")
1474 enabled_repo_hooks = self._ParseList(
1475 self._reqatt(node, "enabled-list")
1476 )
1477 if node.nodeName == "superproject":
1478 name = self._reqatt(node, "name")
1479 # There can only be one superproject.
1480 if self._superproject:
1481 raise ManifestParseError(
1482 "duplicate superproject in %s" % (self.manifestFile)
1483 )
1484 remote_name = node.getAttribute("remote")
1485 if not remote_name:
1486 remote = self._default.remote
1487 else:
1488 remote = self._get_remote(node)
1489 if remote is None:
1490 raise ManifestParseError(
1491 "no remote for superproject %s within %s"
1492 % (name, self.manifestFile)
1493 )
1494 revision = node.getAttribute("revision") or remote.revision
1495 if not revision:
1496 revision = self._default.revisionExpr
1497 if not revision:
1498 raise ManifestParseError(
1499 "no revision for superproject %s within %s"
1500 % (name, self.manifestFile)
1501 )
1502 self._superproject = Superproject(
1503 self,
1504 name=name,
1505 remote=remote.ToRemoteSpec(name),
1506 revision=revision,
1507 )
1508 if node.nodeName == "contactinfo":
1509 bugurl = self._reqatt(node, "bugurl")
1510 # This element can be repeated, later entries will clobber
1511 # earlier ones.
1512 self._contactinfo = ContactInfo(bugurl)
1513
1514 if node.nodeName == "remove-project":
1515 name = self._reqatt(node, "name")
1516
1517 if name in self._projects:
1518 for p in self._projects[name]:
1519 del self._paths[p.relpath]
1520 del self._projects[name]
1521
1522 # If the manifest removes the hooks project, treat it as if
1523 # it deleted
1524 # the repo-hooks element too.
1525 if repo_hooks_project == name:
1526 repo_hooks_project = None
1527 elif not XmlBool(node, "optional", False):
1528 raise ManifestParseError(
1529 "remove-project element specifies non-existent "
1530 "project: %s" % name
1531 )
1532
1533 # Store repo hooks project information.
1534 if repo_hooks_project:
1535 # Store a reference to the Project.
1536 try:
1537 repo_hooks_projects = self._projects[repo_hooks_project]
1538 except KeyError:
1539 raise ManifestParseError(
1540 "project %s not found for repo-hooks" % (repo_hooks_project)
1541 )
1542
1543 if len(repo_hooks_projects) != 1:
1544 raise ManifestParseError(
1545 "internal error parsing repo-hooks in %s"
1546 % (self.manifestFile)
1547 )
1548 self._repo_hooks_project = repo_hooks_projects[0]
1549 # Store the enabled hooks in the Project object.
1550 self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
1551
1552 def _AddMetaProjectMirror(self, m):
1553 name = None
1554 m_url = m.GetRemote().url
1555 if m_url.endswith("/.git"):
1556 raise ManifestParseError("refusing to mirror %s" % m_url)
1557
1558 if self._default and self._default.remote:
1559 url = self._default.remote.resolvedFetchUrl
1560 if not url.endswith("/"):
1561 url += "/"
1562 if m_url.startswith(url):
1563 remote = self._default.remote
1564 name = m_url[len(url) :]
1565
1566 if name is None:
1567 s = m_url.rindex("/") + 1
1568 manifestUrl = self.manifestProject.config.GetString(
1569 "remote.origin.url"
1570 )
1571 remote = _XmlRemote(
1572 "origin", fetch=m_url[:s], manifestUrl=manifestUrl
1573 )
1574 name = m_url[s:]
1575
1576 if name.endswith(".git"):
1577 name = name[:-4]
Josh Triplett884a3872014-06-12 14:57:29 -07001578
1579 if name not in self._projects:
Gavin Makea2e3302023-03-11 06:46:20 +00001580 m.PreSync()
1581 gitdir = os.path.join(self.topdir, "%s.git" % name)
1582 project = Project(
1583 manifest=self,
1584 name=name,
1585 remote=remote.ToRemoteSpec(name),
1586 gitdir=gitdir,
1587 objdir=gitdir,
1588 worktree=None,
1589 relpath=name or None,
1590 revisionExpr=m.revisionExpr,
1591 revisionId=None,
1592 )
1593 self._projects[project.name] = [project]
1594 self._paths[project.relpath] = project
Josh Triplett884a3872014-06-12 14:57:29 -07001595
Gavin Makea2e3302023-03-11 06:46:20 +00001596 def _ParseRemote(self, node):
1597 """
1598 reads a <remote> element from the manifest file
1599 """
1600 name = self._reqatt(node, "name")
1601 alias = node.getAttribute("alias")
1602 if alias == "":
1603 alias = None
1604 fetch = self._reqatt(node, "fetch")
1605 pushUrl = node.getAttribute("pushurl")
1606 if pushUrl == "":
1607 pushUrl = None
1608 review = node.getAttribute("review")
1609 if review == "":
1610 review = None
1611 revision = node.getAttribute("revision")
1612 if revision == "":
1613 revision = None
1614 manifestUrl = self.manifestProject.config.GetString("remote.origin.url")
1615
1616 remote = _XmlRemote(
1617 name, alias, fetch, pushUrl, manifestUrl, review, revision
1618 )
1619
1620 for n in node.childNodes:
1621 if n.nodeName == "annotation":
1622 self._ParseAnnotation(remote, n)
1623
1624 return remote
1625
1626 def _ParseDefault(self, node):
1627 """
1628 reads a <default> element from the manifest file
1629 """
1630 d = _Default()
1631 d.remote = self._get_remote(node)
1632 d.revisionExpr = node.getAttribute("revision")
1633 if d.revisionExpr == "":
1634 d.revisionExpr = None
1635
1636 d.destBranchExpr = node.getAttribute("dest-branch") or None
1637 d.upstreamExpr = node.getAttribute("upstream") or None
1638
1639 d.sync_j = XmlInt(node, "sync-j", None)
1640 if d.sync_j is not None and d.sync_j <= 0:
1641 raise ManifestParseError(
1642 '%s: sync-j must be greater than 0, not "%s"'
1643 % (self.manifestFile, d.sync_j)
1644 )
1645
1646 d.sync_c = XmlBool(node, "sync-c", False)
1647 d.sync_s = XmlBool(node, "sync-s", False)
1648 d.sync_tags = XmlBool(node, "sync-tags", True)
1649 return d
1650
1651 def _ParseNotice(self, node):
1652 """
1653 reads a <notice> element from the manifest file
1654
1655 The <notice> element is distinct from other tags in the XML in that the
1656 data is conveyed between the start and end tag (it's not an
1657 empty-element tag).
1658
1659 The white space (carriage returns, indentation) for the notice element
1660 is relevant and is parsed in a way that is based on how python
1661 docstrings work. In fact, the code is remarkably similar to here:
1662 http://www.python.org/dev/peps/pep-0257/
1663 """
1664 # Get the data out of the node...
1665 notice = node.childNodes[0].data
1666
1667 # Figure out minimum indentation, skipping the first line (the same line
1668 # as the <notice> tag)...
1669 minIndent = sys.maxsize
1670 lines = notice.splitlines()
1671 for line in lines[1:]:
1672 lstrippedLine = line.lstrip()
1673 if lstrippedLine:
1674 indent = len(line) - len(lstrippedLine)
1675 minIndent = min(indent, minIndent)
1676
1677 # Strip leading / trailing blank lines and also indentation.
1678 cleanLines = [lines[0].strip()]
1679 for line in lines[1:]:
1680 cleanLines.append(line[minIndent:].rstrip())
1681
1682 # Clear completely blank lines from front and back...
1683 while cleanLines and not cleanLines[0]:
1684 del cleanLines[0]
1685 while cleanLines and not cleanLines[-1]:
1686 del cleanLines[-1]
1687
1688 return "\n".join(cleanLines)
1689
1690 def _ParseSubmanifest(self, node):
1691 """Reads a <submanifest> element from the manifest file."""
1692 name = self._reqatt(node, "name")
1693 remote = node.getAttribute("remote")
1694 if remote == "":
1695 remote = None
1696 project = node.getAttribute("project")
1697 if project == "":
1698 project = None
1699 revision = node.getAttribute("revision")
1700 if revision == "":
1701 revision = None
1702 manifestName = node.getAttribute("manifest-name")
1703 if manifestName == "":
1704 manifestName = None
1705 groups = ""
1706 if node.hasAttribute("groups"):
1707 groups = node.getAttribute("groups")
1708 groups = self._ParseList(groups)
1709 default_groups = self._ParseList(node.getAttribute("default-groups"))
1710 path = node.getAttribute("path")
1711 if path == "":
1712 path = None
1713 if revision:
1714 msg = self._CheckLocalPath(revision.split("/")[-1])
1715 if msg:
1716 raise ManifestInvalidPathError(
1717 '<submanifest> invalid "revision": %s: %s'
1718 % (revision, msg)
1719 )
1720 else:
1721 msg = self._CheckLocalPath(name)
1722 if msg:
1723 raise ManifestInvalidPathError(
1724 '<submanifest> invalid "name": %s: %s' % (name, msg)
1725 )
LaMont Jonescc879a92021-11-18 22:40:18 +00001726 else:
Gavin Makea2e3302023-03-11 06:46:20 +00001727 msg = self._CheckLocalPath(path)
1728 if msg:
1729 raise ManifestInvalidPathError(
1730 '<submanifest> invalid "path": %s: %s' % (path, msg)
1731 )
Josh Triplett884a3872014-06-12 14:57:29 -07001732
Gavin Makea2e3302023-03-11 06:46:20 +00001733 submanifest = _XmlSubmanifest(
1734 name,
1735 remote,
1736 project,
1737 revision,
1738 manifestName,
1739 groups,
1740 default_groups,
1741 path,
1742 self,
1743 )
Michael Kelly2f3c3312020-07-21 19:40:38 -07001744
Gavin Makea2e3302023-03-11 06:46:20 +00001745 for n in node.childNodes:
1746 if n.nodeName == "annotation":
1747 self._ParseAnnotation(submanifest, n)
Michael Kelly2f3c3312020-07-21 19:40:38 -07001748
Gavin Makea2e3302023-03-11 06:46:20 +00001749 return submanifest
Michael Kelly37c21c22020-06-13 02:10:40 -07001750
Gavin Makea2e3302023-03-11 06:46:20 +00001751 def _JoinName(self, parent_name, name):
1752 return os.path.join(parent_name, name)
Doug Anderson37282b42011-03-04 11:54:18 -08001753
Gavin Makea2e3302023-03-11 06:46:20 +00001754 def _UnjoinName(self, parent_name, name):
1755 return os.path.relpath(name, parent_name)
1756
1757 def _ParseProject(self, node, parent=None, **extra_proj_attrs):
1758 """
1759 reads a <project> element from the manifest file
1760 """
1761 name = self._reqatt(node, "name")
1762 msg = self._CheckLocalPath(name, dir_ok=True)
1763 if msg:
1764 raise ManifestInvalidPathError(
1765 '<project> invalid "name": %s: %s' % (name, msg)
1766 )
1767 if parent:
1768 name = self._JoinName(parent.name, name)
1769
1770 remote = self._get_remote(node)
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001771 if remote is None:
Gavin Makea2e3302023-03-11 06:46:20 +00001772 remote = self._default.remote
1773 if remote is None:
1774 raise ManifestParseError(
1775 "no remote for project %s within %s" % (name, self.manifestFile)
1776 )
Raman Tenneti993af5e2021-05-12 12:00:31 -07001777
Gavin Makea2e3302023-03-11 06:46:20 +00001778 revisionExpr = node.getAttribute("revision") or remote.revision
1779 if not revisionExpr:
1780 revisionExpr = self._default.revisionExpr
1781 if not revisionExpr:
1782 raise ManifestParseError(
1783 "no revision for project %s within %s"
1784 % (name, self.manifestFile)
1785 )
David Jamesb8433df2014-01-30 10:11:17 -08001786
Gavin Makea2e3302023-03-11 06:46:20 +00001787 path = node.getAttribute("path")
1788 if not path:
1789 path = name
Julien Camperguedd654222014-01-09 16:21:37 +01001790 else:
Gavin Makea2e3302023-03-11 06:46:20 +00001791 # NB: The "." project is handled specially in
1792 # Project.Sync_LocalHalf.
1793 msg = self._CheckLocalPath(path, dir_ok=True, cwd_dot_ok=True)
1794 if msg:
1795 raise ManifestInvalidPathError(
1796 '<project> invalid "path": %s: %s' % (path, msg)
1797 )
Julien Camperguedd654222014-01-09 16:21:37 +01001798
Gavin Makea2e3302023-03-11 06:46:20 +00001799 rebase = XmlBool(node, "rebase", True)
1800 sync_c = XmlBool(node, "sync-c", False)
1801 sync_s = XmlBool(node, "sync-s", self._default.sync_s)
1802 sync_tags = XmlBool(node, "sync-tags", self._default.sync_tags)
Julien Camperguedd654222014-01-09 16:21:37 +01001803
Gavin Makea2e3302023-03-11 06:46:20 +00001804 clone_depth = XmlInt(node, "clone-depth")
1805 if clone_depth is not None and clone_depth <= 0:
1806 raise ManifestParseError(
1807 '%s: clone-depth must be greater than 0, not "%s"'
1808 % (self.manifestFile, clone_depth)
1809 )
1810
1811 dest_branch = (
1812 node.getAttribute("dest-branch") or self._default.destBranchExpr
1813 )
1814
1815 upstream = node.getAttribute("upstream") or self._default.upstreamExpr
1816
1817 groups = ""
1818 if node.hasAttribute("groups"):
1819 groups = node.getAttribute("groups")
1820 groups = self._ParseList(groups)
1821
1822 if parent is None:
1823 (
1824 relpath,
1825 worktree,
1826 gitdir,
1827 objdir,
1828 use_git_worktrees,
1829 ) = self.GetProjectPaths(name, path, remote.name)
1830 else:
1831 use_git_worktrees = False
1832 relpath, worktree, gitdir, objdir = self.GetSubprojectPaths(
1833 parent, name, path
1834 )
1835
1836 default_groups = ["all", "name:%s" % name, "path:%s" % relpath]
1837 groups.extend(set(default_groups).difference(groups))
1838
1839 if self.IsMirror and node.hasAttribute("force-path"):
1840 if XmlBool(node, "force-path", False):
1841 gitdir = os.path.join(self.topdir, "%s.git" % path)
1842
1843 project = Project(
1844 manifest=self,
1845 name=name,
1846 remote=remote.ToRemoteSpec(name),
1847 gitdir=gitdir,
1848 objdir=objdir,
1849 worktree=worktree,
1850 relpath=relpath,
1851 revisionExpr=revisionExpr,
1852 revisionId=None,
1853 rebase=rebase,
1854 groups=groups,
1855 sync_c=sync_c,
1856 sync_s=sync_s,
1857 sync_tags=sync_tags,
1858 clone_depth=clone_depth,
1859 upstream=upstream,
1860 parent=parent,
1861 dest_branch=dest_branch,
1862 use_git_worktrees=use_git_worktrees,
1863 **extra_proj_attrs,
1864 )
1865
1866 for n in node.childNodes:
1867 if n.nodeName == "copyfile":
1868 self._ParseCopyFile(project, n)
1869 if n.nodeName == "linkfile":
1870 self._ParseLinkFile(project, n)
1871 if n.nodeName == "annotation":
1872 self._ParseAnnotation(project, n)
1873 if n.nodeName == "project":
1874 project.subprojects.append(
1875 self._ParseProject(n, parent=project)
1876 )
1877
1878 return project
1879
1880 def GetProjectPaths(self, name, path, remote):
1881 """Return the paths for a project.
1882
1883 Args:
1884 name: a string, the name of the project.
1885 path: a string, the path of the project.
1886 remote: a string, the remote.name of the project.
1887
1888 Returns:
1889 A tuple of (relpath, worktree, gitdir, objdir, use_git_worktrees)
1890 for the project with |name| and |path|.
1891 """
1892 # The manifest entries might have trailing slashes. Normalize them to
1893 # avoid unexpected filesystem behavior since we do string concatenation
1894 # below.
1895 path = path.rstrip("/")
1896 name = name.rstrip("/")
1897 remote = remote.rstrip("/")
1898 use_git_worktrees = False
1899 use_remote_name = self.is_multimanifest
1900 relpath = path
1901 if self.IsMirror:
1902 worktree = None
1903 gitdir = os.path.join(self.topdir, "%s.git" % name)
1904 objdir = gitdir
1905 else:
1906 if use_remote_name:
1907 namepath = os.path.join(remote, f"{name}.git")
1908 else:
1909 namepath = f"{name}.git"
1910 worktree = os.path.join(self.topdir, path).replace("\\", "/")
1911 gitdir = os.path.join(self.subdir, "projects", "%s.git" % path)
1912 # We allow people to mix git worktrees & non-git worktrees for now.
1913 # This allows for in situ migration of repo clients.
1914 if os.path.exists(gitdir) or not self.UseGitWorktrees:
1915 objdir = os.path.join(self.repodir, "project-objects", namepath)
1916 else:
1917 use_git_worktrees = True
1918 gitdir = os.path.join(self.repodir, "worktrees", namepath)
1919 objdir = gitdir
1920 return relpath, worktree, gitdir, objdir, use_git_worktrees
1921
1922 def GetProjectsWithName(self, name, all_manifests=False):
1923 """All projects with |name|.
1924
1925 Args:
1926 name: a string, the name of the project.
1927 all_manifests: a boolean, if True, then all manifests are searched.
1928 If False, then only this manifest is searched.
1929
1930 Returns:
1931 A list of Project instances with name |name|.
1932 """
1933 if all_manifests:
1934 return list(
1935 itertools.chain.from_iterable(
1936 x._projects.get(name, []) for x in self.all_manifests
1937 )
1938 )
1939 return self._projects.get(name, [])
1940
1941 def GetSubprojectName(self, parent, submodule_path):
1942 return os.path.join(parent.name, submodule_path)
1943
1944 def _JoinRelpath(self, parent_relpath, relpath):
1945 return os.path.join(parent_relpath, relpath)
1946
1947 def _UnjoinRelpath(self, parent_relpath, relpath):
1948 return os.path.relpath(relpath, parent_relpath)
1949
1950 def GetSubprojectPaths(self, parent, name, path):
1951 # The manifest entries might have trailing slashes. Normalize them to
1952 # avoid unexpected filesystem behavior since we do string concatenation
1953 # below.
1954 path = path.rstrip("/")
1955 name = name.rstrip("/")
1956 relpath = self._JoinRelpath(parent.relpath, path)
1957 gitdir = os.path.join(parent.gitdir, "subprojects", "%s.git" % path)
1958 objdir = os.path.join(
1959 parent.gitdir, "subproject-objects", "%s.git" % name
1960 )
1961 if self.IsMirror:
1962 worktree = None
1963 else:
1964 worktree = os.path.join(parent.worktree, path).replace("\\", "/")
1965 return relpath, worktree, gitdir, objdir
1966
1967 @staticmethod
1968 def _CheckLocalPath(path, dir_ok=False, cwd_dot_ok=False):
1969 """Verify |path| is reasonable for use in filesystem paths.
1970
1971 Used with <copyfile> & <linkfile> & <project> elements.
1972
1973 This only validates the |path| in isolation: it does not check against
1974 the current filesystem state. Thus it is suitable as a first-past in a
1975 parser.
1976
1977 It enforces a number of constraints:
1978 * No empty paths.
1979 * No "~" in paths.
1980 * No Unicode codepoints that filesystems might elide when normalizing.
1981 * No relative path components like "." or "..".
1982 * No absolute paths.
1983 * No ".git" or ".repo*" path components.
1984
1985 Args:
1986 path: The path name to validate.
1987 dir_ok: Whether |path| may force a directory (e.g. end in a /).
1988 cwd_dot_ok: Whether |path| may be just ".".
1989
1990 Returns:
1991 None if |path| is OK, a failure message otherwise.
1992 """
1993 if not path:
1994 return "empty paths not allowed"
1995
1996 if "~" in path:
1997 return "~ not allowed (due to 8.3 filenames on Windows filesystems)"
1998
1999 path_codepoints = set(path)
2000
2001 # Some filesystems (like Apple's HFS+) try to normalize Unicode
2002 # codepoints which means there are alternative names for ".git". Reject
2003 # paths with these in it as there shouldn't be any reasonable need for
2004 # them here. The set of codepoints here was cribbed from jgit's
2005 # implementation:
2006 # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
2007 BAD_CODEPOINTS = {
2008 "\u200C", # ZERO WIDTH NON-JOINER
2009 "\u200D", # ZERO WIDTH JOINER
2010 "\u200E", # LEFT-TO-RIGHT MARK
2011 "\u200F", # RIGHT-TO-LEFT MARK
2012 "\u202A", # LEFT-TO-RIGHT EMBEDDING
2013 "\u202B", # RIGHT-TO-LEFT EMBEDDING
2014 "\u202C", # POP DIRECTIONAL FORMATTING
2015 "\u202D", # LEFT-TO-RIGHT OVERRIDE
2016 "\u202E", # RIGHT-TO-LEFT OVERRIDE
2017 "\u206A", # INHIBIT SYMMETRIC SWAPPING
2018 "\u206B", # ACTIVATE SYMMETRIC SWAPPING
2019 "\u206C", # INHIBIT ARABIC FORM SHAPING
2020 "\u206D", # ACTIVATE ARABIC FORM SHAPING
2021 "\u206E", # NATIONAL DIGIT SHAPES
2022 "\u206F", # NOMINAL DIGIT SHAPES
2023 "\uFEFF", # ZERO WIDTH NO-BREAK SPACE
2024 }
2025 if BAD_CODEPOINTS & path_codepoints:
2026 # This message is more expansive than reality, but should be fine.
2027 return "Unicode combining characters not allowed"
2028
2029 # Reject newlines as there shouldn't be any legitmate use for them,
2030 # they'll be confusing to users, and they can easily break tools that
2031 # expect to be able to iterate over newline delimited lists. This even
2032 # applies to our own code like .repo/project.list.
2033 if {"\r", "\n"} & path_codepoints:
2034 return "Newlines not allowed"
2035
2036 # Assume paths might be used on case-insensitive filesystems.
2037 path = path.lower()
2038
2039 # Split up the path by its components. We can't use os.path.sep
2040 # exclusively as some platforms (like Windows) will convert / to \ and
2041 # that bypasses all our constructed logic here. Especially since
2042 # manifest authors only use / in their paths.
2043 resep = re.compile(r"[/%s]" % re.escape(os.path.sep))
2044 # Strip off trailing slashes as those only produce '' elements, and we
2045 # use parts to look for individual bad components.
2046 parts = resep.split(path.rstrip("/"))
2047
2048 # Some people use src="." to create stable links to projects. Lets
2049 # allow that but reject all other uses of "." to keep things simple.
2050 if not cwd_dot_ok or parts != ["."]:
2051 for part in set(parts):
2052 if part in {".", "..", ".git"} or part.startswith(".repo"):
2053 return "bad component: %s" % (part,)
2054
2055 if not dir_ok and resep.match(path[-1]):
2056 return "dirs not allowed"
2057
2058 # NB: The two abspath checks here are to handle platforms with multiple
2059 # filesystem path styles (e.g. Windows).
2060 norm = os.path.normpath(path)
2061 if (
2062 norm == ".."
2063 or (
2064 len(norm) >= 3
2065 and norm.startswith("..")
2066 and resep.match(norm[0])
2067 )
2068 or os.path.isabs(norm)
2069 or norm.startswith("/")
2070 ):
2071 return "path cannot be outside"
2072
2073 @classmethod
2074 def _ValidateFilePaths(cls, element, src, dest):
2075 """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
2076
2077 We verify the path independent of any filesystem state as we won't have
2078 a checkout available to compare to. i.e. This is for parsing validation
2079 purposes only.
2080
2081 We'll do full/live sanity checking before we do the actual filesystem
2082 modifications in _CopyFile/_LinkFile/etc...
2083 """
2084 # |dest| is the file we write to or symlink we create.
2085 # It is relative to the top of the repo client checkout.
2086 msg = cls._CheckLocalPath(dest)
2087 if msg:
2088 raise ManifestInvalidPathError(
2089 '<%s> invalid "dest": %s: %s' % (element, dest, msg)
2090 )
2091
2092 # |src| is the file we read from or path we point to for symlinks.
2093 # It is relative to the top of the git project checkout.
2094 is_linkfile = element == "linkfile"
2095 msg = cls._CheckLocalPath(
2096 src, dir_ok=is_linkfile, cwd_dot_ok=is_linkfile
2097 )
2098 if msg:
2099 raise ManifestInvalidPathError(
2100 '<%s> invalid "src": %s: %s' % (element, src, msg)
2101 )
2102
2103 def _ParseCopyFile(self, project, node):
2104 src = self._reqatt(node, "src")
2105 dest = self._reqatt(node, "dest")
2106 if not self.IsMirror:
2107 # src is project relative;
2108 # dest is relative to the top of the tree.
2109 # We only validate paths if we actually plan to process them.
2110 self._ValidateFilePaths("copyfile", src, dest)
2111 project.AddCopyFile(src, dest, self.topdir)
2112
2113 def _ParseLinkFile(self, project, node):
2114 src = self._reqatt(node, "src")
2115 dest = self._reqatt(node, "dest")
2116 if not self.IsMirror:
2117 # src is project relative;
2118 # dest is relative to the top of the tree.
2119 # We only validate paths if we actually plan to process them.
2120 self._ValidateFilePaths("linkfile", src, dest)
2121 project.AddLinkFile(src, dest, self.topdir)
2122
2123 def _ParseAnnotation(self, element, node):
2124 name = self._reqatt(node, "name")
2125 value = self._reqatt(node, "value")
2126 try:
2127 keep = self._reqatt(node, "keep").lower()
2128 except ManifestParseError:
2129 keep = "true"
2130 if keep != "true" and keep != "false":
2131 raise ManifestParseError(
2132 'optional "keep" attribute must be ' '"true" or "false"'
2133 )
2134 element.AddAnnotation(name, value, keep)
2135
2136 def _get_remote(self, node):
2137 name = node.getAttribute("remote")
2138 if not name:
2139 return None
2140
2141 v = self._remotes.get(name)
2142 if not v:
2143 raise ManifestParseError(
2144 "remote %s not defined in %s" % (name, self.manifestFile)
2145 )
2146 return v
2147
2148 def _reqatt(self, node, attname):
2149 """
2150 reads a required attribute from the node.
2151 """
2152 v = node.getAttribute(attname)
2153 if not v:
2154 raise ManifestParseError(
2155 "no %s in <%s> within %s"
2156 % (attname, node.nodeName, self.manifestFile)
2157 )
2158 return v
2159
2160 def projectsDiff(self, manifest):
2161 """return the projects differences between two manifests.
2162
2163 The diff will be from self to given manifest.
2164
2165 """
2166 fromProjects = self.paths
2167 toProjects = manifest.paths
2168
2169 fromKeys = sorted(fromProjects.keys())
2170 toKeys = sorted(toProjects.keys())
2171
2172 diff = {
2173 "added": [],
2174 "removed": [],
2175 "missing": [],
2176 "changed": [],
2177 "unreachable": [],
2178 }
2179
2180 for proj in fromKeys:
2181 if proj not in toKeys:
2182 diff["removed"].append(fromProjects[proj])
2183 elif not fromProjects[proj].Exists:
2184 diff["missing"].append(toProjects[proj])
2185 toKeys.remove(proj)
2186 else:
2187 fromProj = fromProjects[proj]
2188 toProj = toProjects[proj]
2189 try:
2190 fromRevId = fromProj.GetCommitRevisionId()
2191 toRevId = toProj.GetCommitRevisionId()
2192 except ManifestInvalidRevisionError:
2193 diff["unreachable"].append((fromProj, toProj))
2194 else:
2195 if fromRevId != toRevId:
2196 diff["changed"].append((fromProj, toProj))
2197 toKeys.remove(proj)
2198
2199 for proj in toKeys:
2200 diff["added"].append(toProjects[proj])
2201
2202 return diff
Simran Basib9a1b732015-08-20 12:19:28 -07002203
2204
2205class GitcManifest(XmlManifest):
Gavin Makea2e3302023-03-11 06:46:20 +00002206 """Parser for GitC (git-in-the-cloud) manifests."""
Simran Basib9a1b732015-08-20 12:19:28 -07002207
Gavin Makea2e3302023-03-11 06:46:20 +00002208 def _ParseProject(self, node, parent=None):
2209 """Override _ParseProject and add support for GITC specific attributes.""" # noqa: E501
2210 return super()._ParseProject(
2211 node, parent=parent, old_revision=node.getAttribute("old-revision")
2212 )
Simran Basib9a1b732015-08-20 12:19:28 -07002213
Gavin Makea2e3302023-03-11 06:46:20 +00002214 def _output_manifest_project_extras(self, p, e):
2215 """Output GITC Specific Project attributes"""
2216 if p.old_revision:
2217 e.setAttribute("old-revision", str(p.old_revision))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04002218
2219
2220class RepoClient(XmlManifest):
Gavin Makea2e3302023-03-11 06:46:20 +00002221 """Manages a repo client checkout."""
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04002222
Gavin Makea2e3302023-03-11 06:46:20 +00002223 def __init__(
2224 self, repodir, manifest_file=None, submanifest_path="", **kwargs
2225 ):
2226 """Initialize.
LaMont Jonesff6b1da2022-06-01 21:03:34 +00002227
Gavin Makea2e3302023-03-11 06:46:20 +00002228 Args:
2229 repodir: Path to the .repo/ dir for holding all internal checkout
2230 state. It must be in the top directory of the repo client
2231 checkout.
2232 manifest_file: Full path to the manifest file to parse. This will
2233 usually be |repodir|/|MANIFEST_FILE_NAME|.
2234 submanifest_path: The submanifest root relative to the repo root.
2235 **kwargs: Additional keyword arguments, passed to XmlManifest.
2236 """
2237 self.isGitcClient = False
2238 submanifest_path = submanifest_path or ""
2239 if submanifest_path:
2240 self._CheckLocalPath(submanifest_path)
2241 prefix = os.path.join(repodir, SUBMANIFEST_DIR, submanifest_path)
2242 else:
2243 prefix = repodir
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04002244
Gavin Makea2e3302023-03-11 06:46:20 +00002245 if os.path.exists(os.path.join(prefix, LOCAL_MANIFEST_NAME)):
2246 print(
2247 "error: %s is not supported; put local manifests in `%s` "
2248 "instead"
2249 % (
2250 LOCAL_MANIFEST_NAME,
2251 os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME),
2252 ),
2253 file=sys.stderr,
2254 )
2255 sys.exit(1)
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04002256
Gavin Makea2e3302023-03-11 06:46:20 +00002257 if manifest_file is None:
2258 manifest_file = os.path.join(prefix, MANIFEST_FILE_NAME)
2259 local_manifests = os.path.abspath(
2260 os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME)
2261 )
2262 super().__init__(
2263 repodir,
2264 manifest_file,
2265 local_manifests,
2266 submanifest_path=submanifest_path,
2267 **kwargs,
2268 )
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04002269
Gavin Makea2e3302023-03-11 06:46:20 +00002270 # TODO: Completely separate manifest logic out of the client.
2271 self.manifest = self
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04002272
2273
2274class GitcClient(RepoClient, GitcManifest):
Gavin Makea2e3302023-03-11 06:46:20 +00002275 """Manages a GitC client checkout."""
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04002276
Gavin Makea2e3302023-03-11 06:46:20 +00002277 def __init__(self, repodir, gitc_client_name):
2278 """Initialize the GitcManifest object."""
2279 self.gitc_client_name = gitc_client_name
2280 self.gitc_client_dir = os.path.join(
2281 gitc_utils.get_gitc_manifest_dir(), gitc_client_name
2282 )
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04002283
Gavin Makea2e3302023-03-11 06:46:20 +00002284 super().__init__(
2285 repodir, os.path.join(self.gitc_client_dir, ".manifest")
2286 )
2287 self.isGitcClient = True