blob: dbab974b986d97d550216a8ce72886fec225facb [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
Miguel Gaio1f207762020-07-17 14:09:13 +020025from git_config import GitConfig, IsId
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
LaMont Jones9b72cf22022-03-29 21:54:22 +000029from project import (Annotation, RemoteSpec, Project, RepoProject,
30 ManifestProject)
Mike Frysinger04122b72019-07-31 23:32:58 -040031from error import (ManifestParseError, ManifestInvalidPathError,
32 ManifestInvalidRevisionError)
Raman Tenneti993af5e2021-05-12 12:00:31 -070033from wrapper import Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070034
35MANIFEST_FILE_NAME = 'manifest.xml'
Shawn O. Pearce5cc66792008-10-23 16:19:27 -070036LOCAL_MANIFEST_NAME = 'local_manifest.xml'
David Pursehouse2d5a0df2012-11-13 02:50:36 +090037LOCAL_MANIFESTS_DIR_NAME = 'local_manifests'
LaMont Jonescc879a92021-11-18 22:40:18 +000038SUBMANIFEST_DIR = 'submanifests'
39# Limit submanifests to an arbitrary depth for loop detection.
40MAX_SUBMANIFEST_DEPTH = 8
LaMont Jonesb308db12022-02-25 17:05:21 +000041# Add all projects from sub manifest into a group.
42SUBMANIFEST_GROUP_PREFIX = 'submanifest:'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070043
Raman Tenneti78f4dd32021-06-07 13:27:37 -070044# Add all projects from local manifest into a group.
45LOCAL_MANIFEST_GROUP_PREFIX = 'local:'
46
Raman Tenneti993af5e2021-05-12 12:00:31 -070047# ContactInfo has the self-registered bug url, supplied by the manifest authors.
48ContactInfo = collections.namedtuple('ContactInfo', 'bugurl')
49
Anthony Kingcb07ba72015-03-28 23:26:04 +000050# urljoin gets confused if the scheme is not known.
Joe Kilner6e310792016-10-27 15:53:53 -070051urllib.parse.uses_relative.extend([
52 'ssh',
53 'git',
54 'persistent-https',
55 'sso',
56 'rpc'])
57urllib.parse.uses_netloc.extend([
58 'ssh',
59 'git',
60 'persistent-https',
61 'sso',
62 'rpc'])
Conley Owensdb728cd2011-09-26 16:34:01 -070063
David Pursehouse819827a2020-02-12 15:20:19 +090064
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050065def XmlBool(node, attr, default=None):
66 """Determine boolean value of |node|'s |attr|.
67
68 Invalid values will issue a non-fatal warning.
69
70 Args:
71 node: XML node whose attributes we access.
72 attr: The attribute to access.
73 default: If the attribute is not set (value is empty), then use this.
74
75 Returns:
76 True if the attribute is a valid string representing true.
77 False if the attribute is a valid string representing false.
78 |default| otherwise.
79 """
80 value = node.getAttribute(attr)
81 s = value.lower()
82 if s == '':
83 return default
84 elif s in {'yes', 'true', '1'}:
85 return True
86 elif s in {'no', 'false', '0'}:
87 return False
88 else:
89 print('warning: manifest: %s="%s": ignoring invalid XML boolean' %
90 (attr, value), file=sys.stderr)
91 return default
92
93
94def XmlInt(node, attr, default=None):
95 """Determine integer value of |node|'s |attr|.
96
97 Args:
98 node: XML node whose attributes we access.
99 attr: The attribute to access.
100 default: If the attribute is not set (value is empty), then use this.
101
102 Returns:
103 The number if the attribute is a valid number.
104
105 Raises:
106 ManifestParseError: The number is invalid.
107 """
108 value = node.getAttribute(attr)
109 if not value:
110 return default
111
112 try:
113 return int(value)
114 except ValueError:
115 raise ManifestParseError('manifest: invalid %s="%s" integer' %
116 (attr, value))
117
118
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700119class _Default(object):
120 """Project defaults within the manifest."""
121
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700122 revisionExpr = None
Conley Owensb6a16e62013-09-25 15:06:09 -0700123 destBranchExpr = None
Nasser Grainawida403412018-05-04 12:53:29 -0600124 upstreamExpr = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700125 remote = None
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700126 sync_j = 1
Anatol Pomazau79770d22012-04-20 14:41:59 -0700127 sync_c = False
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800128 sync_s = False
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900129 sync_tags = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700130
Julien Campergue74879922013-10-09 14:38:46 +0200131 def __eq__(self, other):
Jack Neus5ba21202021-06-09 15:21:25 +0000132 if not isinstance(other, _Default):
133 return False
Julien Campergue74879922013-10-09 14:38:46 +0200134 return self.__dict__ == other.__dict__
135
136 def __ne__(self, other):
Jack Neus5ba21202021-06-09 15:21:25 +0000137 if not isinstance(other, _Default):
138 return True
Julien Campergue74879922013-10-09 14:38:46 +0200139 return self.__dict__ != other.__dict__
140
David Pursehouse819827a2020-02-12 15:20:19 +0900141
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700142class _XmlRemote(object):
143 def __init__(self,
144 name,
Yestin Sunb292b982012-07-02 07:32:50 -0700145 alias=None,
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700146 fetch=None,
Steve Raed6480452016-08-10 15:00:00 -0700147 pushUrl=None,
Conley Owensdb728cd2011-09-26 16:34:01 -0700148 manifestUrl=None,
Anthony King36ea2fb2014-05-06 11:54:01 +0100149 review=None,
Jonathan Nieder93719792015-03-17 11:29:58 -0700150 revision=None):
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700151 self.name = name
152 self.fetchUrl = fetch
Steve Raed6480452016-08-10 15:00:00 -0700153 self.pushUrl = pushUrl
Conley Owensdb728cd2011-09-26 16:34:01 -0700154 self.manifestUrl = manifestUrl
Yestin Sunb292b982012-07-02 07:32:50 -0700155 self.remoteAlias = alias
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700156 self.reviewUrl = review
Anthony King36ea2fb2014-05-06 11:54:01 +0100157 self.revision = revision
Conley Owensceea3682011-10-20 10:45:47 -0700158 self.resolvedFetchUrl = self._resolveFetchUrl()
Jack Neus6ea0cae2021-07-20 20:52:33 +0000159 self.annotations = []
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700160
David Pursehouse717ece92012-11-13 08:49:16 +0900161 def __eq__(self, other):
Jack Neus5ba21202021-06-09 15:21:25 +0000162 if not isinstance(other, _XmlRemote):
163 return False
Jack Neus6ea0cae2021-07-20 20:52:33 +0000164 return (sorted(self.annotations) == sorted(other.annotations) and
165 self.name == other.name and self.fetchUrl == other.fetchUrl and
166 self.pushUrl == other.pushUrl and self.remoteAlias == other.remoteAlias
167 and self.reviewUrl == other.reviewUrl and self.revision == other.revision)
David Pursehouse717ece92012-11-13 08:49:16 +0900168
169 def __ne__(self, other):
Jack Neus6ea0cae2021-07-20 20:52:33 +0000170 return not self.__eq__(other)
David Pursehouse717ece92012-11-13 08:49:16 +0900171
Conley Owensceea3682011-10-20 10:45:47 -0700172 def _resolveFetchUrl(self):
Jack Neus5ba21202021-06-09 15:21:25 +0000173 if self.fetchUrl is None:
174 return ''
Conley Owensceea3682011-10-20 10:45:47 -0700175 url = self.fetchUrl.rstrip('/')
Conley Owensdb728cd2011-09-26 16:34:01 -0700176 manifestUrl = self.manifestUrl.rstrip('/')
Conley Owens2d0f5082014-01-31 15:03:51 -0800177 # urljoin will gets confused over quite a few things. The ones we care
178 # about here are:
179 # * no scheme in the base url, like <hostname:port>
Anthony Kingcb07ba72015-03-28 23:26:04 +0000180 # We handle no scheme by replacing it with an obscure protocol, gopher
181 # and then replacing it with the original when we are done.
182
Conley Owensdb728cd2011-09-26 16:34:01 -0700183 if manifestUrl.find(':') != manifestUrl.find('/') - 1:
Conley Owens4ccad752015-04-29 10:45:37 -0700184 url = urllib.parse.urljoin('gopher://' + manifestUrl, url)
185 url = re.sub(r'^gopher://', '', url)
Anthony Kingcb07ba72015-03-28 23:26:04 +0000186 else:
187 url = urllib.parse.urljoin(manifestUrl, url)
Shawn Pearcea9f11b32013-01-02 15:40:48 -0800188 return url
Conley Owensceea3682011-10-20 10:45:47 -0700189
190 def ToRemoteSpec(self, projectName):
David Rileye0684ad2017-04-05 00:02:59 -0700191 fetchUrl = self.resolvedFetchUrl.rstrip('/')
192 url = fetchUrl + '/' + projectName
Yestin Sunb292b982012-07-02 07:32:50 -0700193 remoteName = self.name
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700194 if self.remoteAlias:
David Pursehouse37128b62013-10-15 10:48:40 +0900195 remoteName = self.remoteAlias
Dan Willemsen96c2d652016-04-06 16:03:54 -0700196 return RemoteSpec(remoteName,
197 url=url,
Steve Raed6480452016-08-10 15:00:00 -0700198 pushUrl=self.pushUrl,
Dan Willemsen96c2d652016-04-06 16:03:54 -0700199 review=self.reviewUrl,
David Rileye0684ad2017-04-05 00:02:59 -0700200 orig_name=self.name,
201 fetchUrl=self.fetchUrl)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700202
Jack Neus6ea0cae2021-07-20 20:52:33 +0000203 def AddAnnotation(self, name, value, keep):
204 self.annotations.append(Annotation(name, value, keep))
205
David Pursehouse819827a2020-02-12 15:20:19 +0900206
LaMont Jonescc879a92021-11-18 22:40:18 +0000207class _XmlSubmanifest:
208 """Manage the <submanifest> element specified in the manifest.
209
210 Attributes:
211 name: a string, the name for this submanifest.
212 remote: a string, the remote.name for this submanifest.
213 project: a string, the name of the manifest project.
214 revision: a string, the commitish.
215 manifestName: a string, the submanifest file name.
216 groups: a list of strings, the groups to add to all projects in the submanifest.
217 path: a string, the relative path for the submanifest checkout.
LaMont Jonesb90a4222022-04-14 15:00:09 +0000218 parent: an XmlManifest, the parent manifest.
LaMont Jonescc879a92021-11-18 22:40:18 +0000219 annotations: (derived) a list of annotations.
LaMont Jonesb90a4222022-04-14 15:00:09 +0000220 present: (derived) a boolean, whether the sub manifest file is present.
LaMont Jonescc879a92021-11-18 22:40:18 +0000221 """
222 def __init__(self,
223 name,
224 remote=None,
225 project=None,
226 revision=None,
227 manifestName=None,
228 groups=None,
229 path=None,
230 parent=None):
231 self.name = name
232 self.remote = remote
233 self.project = project
234 self.revision = revision
235 self.manifestName = manifestName
236 self.groups = groups
237 self.path = path
LaMont Jonesb90a4222022-04-14 15:00:09 +0000238 self.parent = parent
LaMont Jonescc879a92021-11-18 22:40:18 +0000239 self.annotations = []
240 outer_client = parent._outer_client or parent
241 if self.remote and not self.project:
242 raise ManifestParseError(
243 f'Submanifest {name}: must specify project when remote is given.')
LaMont Jones5d3291d2022-03-23 19:03:02 +0000244 # Construct the absolute path to the manifest file using the parent's
245 # method, so that we can correctly create our repo_client.
246 manifestFile = parent.SubmanifestInfoDir(
247 os.path.join(parent.path_prefix, self.relpath),
248 os.path.join('manifests', manifestName or 'default.xml'))
LaMont Jones55ee3042022-04-06 17:10:21 +0000249 linkFile = parent.SubmanifestInfoDir(
250 os.path.join(parent.path_prefix, self.relpath), MANIFEST_FILE_NAME)
LaMont Jonescc879a92021-11-18 22:40:18 +0000251 rc = self.repo_client = RepoClient(
LaMont Jones55ee3042022-04-06 17:10:21 +0000252 parent.repodir, linkFile, parent_groups=','.join(groups) or '',
LaMont Jonescc879a92021-11-18 22:40:18 +0000253 submanifest_path=self.relpath, outer_client=outer_client)
254
LaMont Jones55ee3042022-04-06 17:10:21 +0000255 self.present = os.path.exists(manifestFile)
LaMont Jonescc879a92021-11-18 22:40:18 +0000256
257 def __eq__(self, other):
258 if not isinstance(other, _XmlSubmanifest):
259 return False
260 return (
261 self.name == other.name and
262 self.remote == other.remote and
263 self.project == other.project and
264 self.revision == other.revision and
265 self.manifestName == other.manifestName and
266 self.groups == other.groups and
267 self.path == other.path and
268 sorted(self.annotations) == sorted(other.annotations))
269
270 def __ne__(self, other):
271 return not self.__eq__(other)
272
LaMont Jonesb90a4222022-04-14 15:00:09 +0000273 def ToSubmanifestSpec(self):
LaMont Jonescc879a92021-11-18 22:40:18 +0000274 """Return a SubmanifestSpec object, populating attributes"""
LaMont Jonesb90a4222022-04-14 15:00:09 +0000275 mp = self.parent.manifestProject
276 remote = self.parent.remotes[self.remote or self.parent.default.remote.name]
LaMont Jonescc879a92021-11-18 22:40:18 +0000277 # If a project was given, generate the url from the remote and project.
278 # If not, use this manifestProject's url.
279 if self.project:
280 manifestUrl = remote.ToRemoteSpec(self.project).url
281 else:
282 manifestUrl = mp.GetRemote(mp.remote.name).url
283 manifestName = self.manifestName or 'default.xml'
284 revision = self.revision or self.name
285 path = self.path or revision.split('/')[-1]
286 groups = self.groups or []
287
288 return SubmanifestSpec(self.name, manifestUrl, manifestName, revision, path,
289 groups)
290
291 @property
292 def relpath(self):
293 """The path of this submanifest relative to the parent manifest."""
294 revision = self.revision or self.name
295 return self.path or revision.split('/')[-1]
296
297 def GetGroupsStr(self):
298 """Returns the `groups` given for this submanifest."""
299 if self.groups:
300 return ','.join(self.groups)
301 return ''
302
303 def AddAnnotation(self, name, value, keep):
304 """Add annotations to the submanifest."""
305 self.annotations.append(Annotation(name, value, keep))
306
307
308class SubmanifestSpec:
309 """The submanifest element, with all fields expanded."""
310
311 def __init__(self,
312 name,
313 manifestUrl,
314 manifestName,
315 revision,
316 path,
317 groups):
318 self.name = name
319 self.manifestUrl = manifestUrl
320 self.manifestName = manifestName
321 self.revision = revision
322 self.path = path
323 self.groups = groups or []
324
325
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700326class XmlManifest(object):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700327 """manages the repo configuration file"""
328
LaMont Jonescc879a92021-11-18 22:40:18 +0000329 def __init__(self, repodir, manifest_file, local_manifests=None,
330 outer_client=None, parent_groups='', submanifest_path=''):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400331 """Initialize.
332
333 Args:
334 repodir: Path to the .repo/ dir for holding all internal checkout state.
335 It must be in the top directory of the repo client checkout.
336 manifest_file: Full path to the manifest file to parse. This will usually
337 be |repodir|/|MANIFEST_FILE_NAME|.
338 local_manifests: Full path to the directory of local override manifests.
339 This will usually be |repodir|/|LOCAL_MANIFESTS_DIR_NAME|.
LaMont Jonescc879a92021-11-18 22:40:18 +0000340 outer_client: RepoClient of the outertree.
341 parent_groups: a string, the groups to apply to this projects.
342 submanifest_path: The submanifest root relative to the repo root.
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400343 """
344 # TODO(vapier): Move this out of this class.
345 self.globalConfig = GitConfig.ForUser()
346
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700347 self.repodir = os.path.abspath(repodir)
LaMont Jonescc879a92021-11-18 22:40:18 +0000348 self._CheckLocalPath(submanifest_path)
349 self.topdir = os.path.join(os.path.dirname(self.repodir), submanifest_path)
LaMont Jones5d3291d2022-03-23 19:03:02 +0000350 if manifest_file != os.path.abspath(manifest_file):
351 raise ManifestParseError('manifest_file must be abspath')
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400352 self.manifestFile = manifest_file
LaMont Jonesb90a4222022-04-14 15:00:09 +0000353 if not outer_client or outer_client == self:
354 # manifestFileOverrides only exists in the outer_client's manifest, since
355 # that is the only instance left when Unload() is called on the outer
356 # manifest.
357 self.manifestFileOverrides = {}
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400358 self.local_manifests = local_manifests
Basil Gelloc7453502018-05-25 20:23:52 +0300359 self._load_local_manifests = True
LaMont Jonescc879a92021-11-18 22:40:18 +0000360 self.parent_groups = parent_groups
361
362 if outer_client and self.isGitcClient:
363 raise ManifestParseError('Multi-manifest is incompatible with `gitc-init`')
364
365 if submanifest_path and not outer_client:
366 # If passing a submanifest_path, there must be an outer_client.
367 raise ManifestParseError(f'Bad call to {self.__class__.__name__}')
368
369 # If self._outer_client is None, this is not a checkout that supports
370 # multi-tree.
371 self._outer_client = outer_client or self
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700372
LaMont Jones9b72cf22022-03-29 21:54:22 +0000373 self.repoProject = RepoProject(self, 'repo',
David Pursehouseabdf7502020-02-12 14:58:39 +0900374 gitdir=os.path.join(repodir, 'repo/.git'),
375 worktree=os.path.join(repodir, 'repo'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700376
LaMont Jonescc879a92021-11-18 22:40:18 +0000377 mp = self.SubmanifestProject(self.path_prefix)
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500378 self.manifestProject = mp
379
380 # This is a bit hacky, but we're in a chicken & egg situation: all the
381 # normal repo settings live in the manifestProject which we just setup
382 # above, so we couldn't easily query before that. We assume Project()
383 # init doesn't care if this changes afterwards.
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000384 if os.path.exists(mp.gitdir) and mp.use_worktree:
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500385 mp.use_git_worktrees = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700386
LaMont Jonesa2ff20d2022-04-07 16:49:06 +0000387 self.Unload()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700388
Basil Gelloc7453502018-05-25 20:23:52 +0300389 def Override(self, name, load_local_manifests=True):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700390 """Use a different manifest, just for the current instantiation.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700391 """
Basil Gelloc7453502018-05-25 20:23:52 +0300392 path = None
393
394 # Look for a manifest by path in the filesystem (including the cwd).
395 if not load_local_manifests:
396 local_path = os.path.abspath(name)
397 if os.path.isfile(local_path):
398 path = local_path
399
400 # Look for manifests by name from the manifests repo.
401 if path is None:
402 path = os.path.join(self.manifestProject.worktree, name)
403 if not os.path.isfile(path):
404 raise ManifestParseError('manifest %s not found' % name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700405
LaMont Jonesb90a4222022-04-14 15:00:09 +0000406 self._load_local_manifests = load_local_manifests
407 self._outer_client.manifestFileOverrides[self.path_prefix] = path
408 self.Unload()
409 self._Load()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700410
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700411 def Link(self, name):
412 """Update the repo metadata to use a different manifest.
413 """
414 self.Override(name)
415
Mike Frysingera269b1c2020-02-21 00:49:41 -0500416 # Old versions of repo would generate symlinks we need to clean up.
Mike Frysinger9d96f582021-09-28 11:27:24 -0400417 platform_utils.remove(self.manifestFile, missing_ok=True)
Mike Frysingera269b1c2020-02-21 00:49:41 -0500418 # This file is interpreted as if it existed inside the manifest repo.
419 # That allows us to use <include> with the relative file name.
420 with open(self.manifestFile, 'w') as fp:
421 fp.write("""<?xml version="1.0" encoding="UTF-8"?>
422<!--
423DO NOT EDIT THIS FILE! It is generated by repo and changes will be discarded.
424If you want to use a different manifest, use `repo init -m <file>` instead.
425
426If you want to customize your checkout by overriding manifest settings, use
427the local_manifests/ directory instead.
428
429For more information on repo manifests, check out:
430https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
431-->
432<manifest>
433 <include name="%s" />
434</manifest>
435""" % (name,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700436
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800437 def _RemoteToXml(self, r, doc, root):
438 e = doc.createElement('remote')
439 root.appendChild(e)
440 e.setAttribute('name', r.name)
441 e.setAttribute('fetch', r.fetchUrl)
Steve Raed6480452016-08-10 15:00:00 -0700442 if r.pushUrl is not None:
443 e.setAttribute('pushurl', r.pushUrl)
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700444 if r.remoteAlias is not None:
445 e.setAttribute('alias', r.remoteAlias)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800446 if r.reviewUrl is not None:
447 e.setAttribute('review', r.reviewUrl)
Anthony King36ea2fb2014-05-06 11:54:01 +0100448 if r.revision is not None:
449 e.setAttribute('revision', r.revision)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800450
Jack Neus6ea0cae2021-07-20 20:52:33 +0000451 for a in r.annotations:
452 if a.keep == 'true':
453 ae = doc.createElement('annotation')
454 ae.setAttribute('name', a.name)
455 ae.setAttribute('value', a.value)
456 e.appendChild(ae)
457
LaMont Jonescc879a92021-11-18 22:40:18 +0000458 def _SubmanifestToXml(self, r, doc, root):
459 """Generate XML <submanifest/> node."""
460 e = doc.createElement('submanifest')
461 root.appendChild(e)
462 e.setAttribute('name', r.name)
463 if r.remote is not None:
464 e.setAttribute('remote', r.remote)
465 if r.project is not None:
466 e.setAttribute('project', r.project)
467 if r.manifestName is not None:
468 e.setAttribute('manifest-name', r.manifestName)
469 if r.revision is not None:
470 e.setAttribute('revision', r.revision)
471 if r.path is not None:
472 e.setAttribute('path', r.path)
473 if r.groups:
474 e.setAttribute('groups', r.GetGroupsStr())
475
476 for a in r.annotations:
477 if a.keep == 'true':
478 ae = doc.createElement('annotation')
479 ae.setAttribute('name', a.name)
480 ae.setAttribute('value', a.value)
481 e.appendChild(ae)
482
Mike Frysinger51e39d52020-12-04 05:32:06 -0500483 def _ParseList(self, field):
484 """Parse fields that contain flattened lists.
485
486 These are whitespace & comma separated. Empty elements will be discarded.
487 """
488 return [x for x in re.split(r'[,\s]+', field) if x]
Josh Triplett884a3872014-06-12 14:57:29 -0700489
Mike Frysinger23411d32020-09-02 04:31:10 -0400490 def ToXml(self, peg_rev=False, peg_rev_upstream=True, peg_rev_dest_branch=True, groups=None):
491 """Return the current manifest XML."""
Colin Cross5acde752012-03-28 20:15:45 -0700492 mp = self.manifestProject
493
Dan Willemsen5ea32d12015-09-08 13:27:20 -0700494 if groups is None:
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000495 groups = mp.manifest_groups
Matt Gumbel0c635bb2012-12-21 10:14:53 -0800496 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -0500497 groups = self._ParseList(groups)
Colin Cross5acde752012-03-28 20:15:45 -0700498
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800499 doc = xml.dom.minidom.Document()
500 root = doc.createElement('manifest')
LaMont Jonescc879a92021-11-18 22:40:18 +0000501 if self.is_submanifest:
502 root.setAttribute('path', self.path_prefix)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800503 doc.appendChild(root)
504
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700505 # Save out the notice. There's a little bit of work here to give it the
506 # right whitespace, which assumes that the notice is automatically indented
507 # by 4 by minidom.
508 if self.notice:
509 notice_element = root.appendChild(doc.createElement('notice'))
510 notice_lines = self.notice.splitlines()
David Pursehouse54a4e602020-02-12 14:31:05 +0900511 indented_notice = ('\n'.join(" " * 4 + line for line in notice_lines))[4:]
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700512 notice_element.appendChild(doc.createTextNode(indented_notice))
513
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800514 d = self.default
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800515
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530516 for r in sorted(self.remotes):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800517 self._RemoteToXml(self.remotes[r], doc, root)
518 if self.remotes:
519 root.appendChild(doc.createTextNode(''))
520
521 have_default = False
522 e = doc.createElement('default')
523 if d.remote:
524 have_default = True
525 e.setAttribute('remote', d.remote.name)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700526 if d.revisionExpr:
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800527 have_default = True
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700528 e.setAttribute('revision', d.revisionExpr)
Simon Ruggier7e59de22015-07-24 12:50:06 +0200529 if d.destBranchExpr:
530 have_default = True
531 e.setAttribute('dest-branch', d.destBranchExpr)
Nasser Grainawida403412018-05-04 12:53:29 -0600532 if d.upstreamExpr:
533 have_default = True
534 e.setAttribute('upstream', d.upstreamExpr)
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700535 if d.sync_j > 1:
536 have_default = True
537 e.setAttribute('sync-j', '%d' % d.sync_j)
Anatol Pomazau79770d22012-04-20 14:41:59 -0700538 if d.sync_c:
539 have_default = True
540 e.setAttribute('sync-c', 'true')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800541 if d.sync_s:
542 have_default = True
543 e.setAttribute('sync-s', 'true')
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900544 if not d.sync_tags:
545 have_default = True
546 e.setAttribute('sync-tags', 'false')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800547 if have_default:
548 root.appendChild(e)
549 root.appendChild(doc.createTextNode(''))
550
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700551 if self._manifest_server:
552 e = doc.createElement('manifest-server')
553 e.setAttribute('url', self._manifest_server)
554 root.appendChild(e)
555 root.appendChild(doc.createTextNode(''))
556
LaMont Jonescc879a92021-11-18 22:40:18 +0000557 for r in sorted(self.submanifests):
558 self._SubmanifestToXml(self.submanifests[r], doc, root)
559 if self.submanifests:
560 root.appendChild(doc.createTextNode(''))
561
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800562 def output_projects(parent, parent_node, projects):
David James8d201162013-10-11 17:03:19 -0700563 for project_name in projects:
564 for project in self._projects[project_name]:
565 output_project(parent, parent_node, project)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800566
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800567 def output_project(parent, parent_node, p):
Colin Cross5acde752012-03-28 20:15:45 -0700568 if not p.MatchesGroups(groups):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800569 return
570
571 name = p.name
572 relpath = p.relpath
573 if parent:
574 name = self._UnjoinName(parent.name, name)
575 relpath = self._UnjoinRelpath(parent.relpath, relpath)
Colin Cross5acde752012-03-28 20:15:45 -0700576
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800577 e = doc.createElement('project')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800578 parent_node.appendChild(e)
579 e.setAttribute('name', name)
580 if relpath != name:
581 e.setAttribute('path', relpath)
Conley Owensa17d7af2013-10-16 14:38:09 -0700582 remoteName = None
583 if d.remote:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700584 remoteName = d.remote.name
585 if not d.remote or p.remote.orig_name != remoteName:
586 remoteName = p.remote.orig_name
Anthony King36ea2fb2014-05-06 11:54:01 +0100587 e.setAttribute('remote', remoteName)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800588 if peg_rev:
589 if self.IsMirror:
Brian Harring14a66742012-09-28 20:21:57 -0700590 value = p.bare_git.rev_parse(p.revisionExpr + '^0')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800591 else:
Brian Harring14a66742012-09-28 20:21:57 -0700592 value = p.work_git.rev_parse(HEAD + '^0')
593 e.setAttribute('revision', value)
Conley Owens551dfec2015-07-10 14:54:54 -0700594 if peg_rev_upstream:
595 if p.upstream:
596 e.setAttribute('upstream', p.upstream)
597 elif value != p.revisionExpr:
598 # Only save the origin if the origin is not a sha1, and the default
599 # isn't our value
600 e.setAttribute('upstream', p.revisionExpr)
Sean McAllisteraf908cb2020-04-20 08:41:58 -0600601
602 if peg_rev_dest_branch:
603 if p.dest_branch:
604 e.setAttribute('dest-branch', p.dest_branch)
605 elif value != p.revisionExpr:
606 e.setAttribute('dest-branch', p.revisionExpr)
607
Anthony King36ea2fb2014-05-06 11:54:01 +0100608 else:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700609 revision = self.remotes[p.remote.orig_name].revision or d.revisionExpr
Anthony King36ea2fb2014-05-06 11:54:01 +0100610 if not revision or revision != p.revisionExpr:
611 e.setAttribute('revision', p.revisionExpr)
Raman Tennetib5c5a5e2021-02-06 09:44:15 -0800612 elif p.revisionId:
613 e.setAttribute('revision', p.revisionId)
Nasser Grainawida403412018-05-04 12:53:29 -0600614 if (p.upstream and (p.upstream != p.revisionExpr or
615 p.upstream != d.upstreamExpr)):
Mani Chandel7a91d512014-07-24 16:27:08 +0530616 e.setAttribute('upstream', p.upstream)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800617
Simon Ruggier7e59de22015-07-24 12:50:06 +0200618 if p.dest_branch and p.dest_branch != d.destBranchExpr:
619 e.setAttribute('dest-branch', p.dest_branch)
620
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800621 for c in p.copyfiles:
622 ce = doc.createElement('copyfile')
623 ce.setAttribute('src', c.src)
624 ce.setAttribute('dest', c.dest)
625 e.appendChild(ce)
626
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500627 for l in p.linkfiles:
628 le = doc.createElement('linkfile')
629 le.setAttribute('src', l.src)
630 le.setAttribute('dest', l.dest)
631 e.appendChild(le)
632
Conley Owensbb1b5f52012-08-13 13:11:18 -0700633 default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
Dmitry Fink17f85ea2012-08-06 14:52:29 -0700634 egroups = [g for g in p.groups if g not in default_groups]
Conley Owens971de8e2012-04-16 10:36:08 -0700635 if egroups:
636 e.setAttribute('groups', ','.join(egroups))
Colin Cross5acde752012-03-28 20:15:45 -0700637
James W. Mills24c13082012-04-12 15:04:13 -0500638 for a in p.annotations:
639 if a.keep == "true":
640 ae = doc.createElement('annotation')
641 ae.setAttribute('name', a.name)
642 ae.setAttribute('value', a.value)
643 e.appendChild(ae)
644
Anatol Pomazau79770d22012-04-20 14:41:59 -0700645 if p.sync_c:
646 e.setAttribute('sync-c', 'true')
647
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800648 if p.sync_s:
649 e.setAttribute('sync-s', 'true')
650
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900651 if not p.sync_tags:
652 e.setAttribute('sync-tags', 'false')
653
Dan Willemsen88409222015-08-17 15:29:10 -0700654 if p.clone_depth:
655 e.setAttribute('clone-depth', str(p.clone_depth))
656
Simran Basib9a1b732015-08-20 12:19:28 -0700657 self._output_manifest_project_extras(p, e)
658
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800659 if p.subprojects:
David James8d201162013-10-11 17:03:19 -0700660 subprojects = set(subp.name for subp in p.subprojects)
661 output_projects(p, e, list(sorted(subprojects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800662
David James8d201162013-10-11 17:03:19 -0700663 projects = set(p.name for p in self._paths.values() if not p.parent)
664 output_projects(None, root, list(sorted(projects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800665
Doug Anderson37282b42011-03-04 11:54:18 -0800666 if self._repo_hooks_project:
667 root.appendChild(doc.createTextNode(''))
668 e = doc.createElement('repo-hooks')
669 e.setAttribute('in-project', self._repo_hooks_project.name)
670 e.setAttribute('enabled-list',
671 ' '.join(self._repo_hooks_project.enabled_repo_hooks))
672 root.appendChild(e)
673
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800674 if self._superproject:
675 root.appendChild(doc.createTextNode(''))
676 e = doc.createElement('superproject')
LaMont Jonesd56e2eb2022-04-07 18:14:46 +0000677 e.setAttribute('name', self._superproject.name)
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800678 remoteName = None
679 if d.remote:
680 remoteName = d.remote.name
LaMont Jonesd56e2eb2022-04-07 18:14:46 +0000681 remote = self._superproject.remote
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800682 if not d.remote or remote.orig_name != remoteName:
683 remoteName = remote.orig_name
684 e.setAttribute('remote', remoteName)
Xin Lie0b16a22021-09-26 23:20:32 -0700685 revision = remote.revision or d.revisionExpr
LaMont Jonesd56e2eb2022-04-07 18:14:46 +0000686 if not revision or revision != self._superproject.revision:
687 e.setAttribute('revision', self._superproject.revision)
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800688 root.appendChild(e)
689
Raman Tenneti993af5e2021-05-12 12:00:31 -0700690 if self._contactinfo.bugurl != Wrapper().BUG_URL:
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700691 root.appendChild(doc.createTextNode(''))
692 e = doc.createElement('contactinfo')
Raman Tenneti993af5e2021-05-12 12:00:31 -0700693 e.setAttribute('bugurl', self._contactinfo.bugurl)
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700694 root.appendChild(e)
695
Mike Frysinger23411d32020-09-02 04:31:10 -0400696 return doc
697
698 def ToDict(self, **kwargs):
699 """Return the current manifest as a dictionary."""
700 # Elements that may only appear once.
701 SINGLE_ELEMENTS = {
702 'notice',
703 'default',
704 'manifest-server',
705 'repo-hooks',
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800706 'superproject',
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700707 'contactinfo',
Mike Frysinger23411d32020-09-02 04:31:10 -0400708 }
709 # Elements that may be repeated.
710 MULTI_ELEMENTS = {
711 'remote',
712 'remove-project',
713 'project',
714 'extend-project',
715 'include',
LaMont Jonescc879a92021-11-18 22:40:18 +0000716 'submanifest',
Mike Frysinger23411d32020-09-02 04:31:10 -0400717 # These are children of 'project' nodes.
718 'annotation',
719 'project',
720 'copyfile',
721 'linkfile',
722 }
723
724 doc = self.ToXml(**kwargs)
725 ret = {}
726
727 def append_children(ret, node):
728 for child in node.childNodes:
729 if child.nodeType == xml.dom.Node.ELEMENT_NODE:
730 attrs = child.attributes
731 element = dict((attrs.item(i).localName, attrs.item(i).value)
732 for i in range(attrs.length))
733 if child.nodeName in SINGLE_ELEMENTS:
734 ret[child.nodeName] = element
735 elif child.nodeName in MULTI_ELEMENTS:
736 ret.setdefault(child.nodeName, []).append(element)
737 else:
738 raise ManifestParseError('Unhandled element "%s"' % (child.nodeName,))
739
740 append_children(element, child)
741
742 append_children(ret, doc.firstChild)
743
744 return ret
745
746 def Save(self, fd, **kwargs):
747 """Write the current manifest out to the given file descriptor."""
748 doc = self.ToXml(**kwargs)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800749 doc.writexml(fd, '', ' ', '\n', 'UTF-8')
750
Simran Basib9a1b732015-08-20 12:19:28 -0700751 def _output_manifest_project_extras(self, p, e):
752 """Manifests can modify e if they support extra project attributes."""
Simran Basib9a1b732015-08-20 12:19:28 -0700753
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700754 @property
LaMont Jonescc879a92021-11-18 22:40:18 +0000755 def is_multimanifest(self):
756 """Whether this is a multimanifest checkout"""
757 return bool(self.outer_client.submanifests)
758
759 @property
760 def is_submanifest(self):
761 """Whether this manifest is a submanifest"""
762 return self._outer_client and self._outer_client != self
763
764 @property
765 def outer_client(self):
766 """The instance of the outermost manifest client"""
767 self._Load()
768 return self._outer_client
769
770 @property
771 def all_manifests(self):
772 """Generator yielding all (sub)manifests."""
773 self._Load()
774 outer = self._outer_client
775 yield outer
776 for tree in outer.all_children:
777 yield tree
778
779 @property
780 def all_children(self):
781 """Generator yielding all child submanifests."""
782 self._Load()
783 for child in self._submanifests.values():
784 if child.repo_client:
785 yield child.repo_client
786 for tree in child.repo_client.all_children:
787 yield tree
788
789 @property
790 def path_prefix(self):
791 """The path of this submanifest, relative to the outermost manifest."""
792 if not self._outer_client or self == self._outer_client:
793 return ''
794 return os.path.relpath(self.topdir, self._outer_client.topdir)
795
796 @property
797 def all_paths(self):
798 """All project paths for all (sub)manifests. See `paths`."""
799 ret = {}
800 for tree in self.all_manifests:
801 prefix = tree.path_prefix
802 ret.update({os.path.join(prefix, k): v for k, v in tree.paths.items()})
803 return ret
804
805 @property
806 def all_projects(self):
807 """All projects for all (sub)manifests. See `projects`."""
808 return list(itertools.chain.from_iterable(x._paths.values() for x in self.all_manifests))
809
810 @property
David James8d201162013-10-11 17:03:19 -0700811 def paths(self):
LaMont Jonescc879a92021-11-18 22:40:18 +0000812 """Return all paths for this manifest.
813
814 Return:
815 A dictionary of {path: Project()}. `path` is relative to this manifest.
816 """
David James8d201162013-10-11 17:03:19 -0700817 self._Load()
818 return self._paths
819
820 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700821 def projects(self):
LaMont Jonescc879a92021-11-18 22:40:18 +0000822 """Return a list of all Projects in this manifest."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700823 self._Load()
Anthony Kingd58bfe52014-05-05 23:30:49 +0100824 return list(self._paths.values())
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700825
826 @property
827 def remotes(self):
828 self._Load()
829 return self._remotes
830
831 @property
832 def default(self):
833 self._Load()
834 return self._default
835
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800836 @property
LaMont Jonescc879a92021-11-18 22:40:18 +0000837 def submanifests(self):
838 """All submanifests in this manifest."""
839 self._Load()
840 return self._submanifests
841
842 @property
Doug Anderson37282b42011-03-04 11:54:18 -0800843 def repo_hooks_project(self):
844 self._Load()
845 return self._repo_hooks_project
846
847 @property
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800848 def superproject(self):
849 self._Load()
850 return self._superproject
851
852 @property
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700853 def contactinfo(self):
854 self._Load()
855 return self._contactinfo
856
857 @property
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700858 def notice(self):
859 self._Load()
860 return self._notice
861
862 @property
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700863 def manifest_server(self):
864 self._Load()
Shawn O. Pearce34fb20f2011-11-30 13:41:02 -0800865 return self._manifest_server
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700866
867 @property
Xin Lid79a4bc2020-05-20 16:03:45 -0700868 def CloneBundle(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000869 clone_bundle = self.manifestProject.clone_bundle
Xin Lid79a4bc2020-05-20 16:03:45 -0700870 if clone_bundle is None:
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000871 return False if self.manifestProject.partial_clone else True
Xin Lid79a4bc2020-05-20 16:03:45 -0700872 else:
873 return clone_bundle
874
875 @property
Xin Li745be2e2019-06-03 11:24:30 -0700876 def CloneFilter(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000877 if self.manifestProject.partial_clone:
878 return self.manifestProject.clone_filter
Xin Li745be2e2019-06-03 11:24:30 -0700879 return None
880
881 @property
Raman Tennetif32f2432021-04-12 20:57:25 -0700882 def PartialCloneExclude(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000883 exclude = self.manifest.manifestProject.partial_clone_exclude or ''
Raman Tennetif32f2432021-04-12 20:57:25 -0700884 return set(x.strip() for x in exclude.split(','))
885
LaMont Jonesb90a4222022-04-14 15:00:09 +0000886 def SetManifestOverride(self, path):
887 """Override manifestFile. The caller must call Unload()"""
888 self._outer_client.manifest.manifestFileOverrides[self.path_prefix] = path
889
Raman Tennetif32f2432021-04-12 20:57:25 -0700890 @property
Michael Kellyc34b91c2021-07-02 09:25:48 -0700891 def UseLocalManifests(self):
892 return self._load_local_manifests
893
894 def SetUseLocalManifests(self, value):
895 self._load_local_manifests = value
896
897 @property
Raman Tennetifeb28912021-05-02 19:47:29 -0700898 def HasLocalManifests(self):
899 return self._load_local_manifests and self.local_manifests
900
LaMont Jones87cce682022-02-14 17:48:31 +0000901 def IsFromLocalManifest(self, project):
LaMont Jonescc879a92021-11-18 22:40:18 +0000902 """Is the project from a local manifest?"""
LaMont Jones87cce682022-02-14 17:48:31 +0000903 return any(x.startswith(LOCAL_MANIFEST_GROUP_PREFIX)
904 for x in project.groups)
905
Raman Tennetifeb28912021-05-02 19:47:29 -0700906 @property
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800907 def IsMirror(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000908 return self.manifestProject.mirror
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800909
Julien Campergue335f5ef2013-10-16 11:02:35 +0200910 @property
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500911 def UseGitWorktrees(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000912 return self.manifestProject.use_worktree
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500913
914 @property
Julien Campergue335f5ef2013-10-16 11:02:35 +0200915 def IsArchive(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000916 return self.manifestProject.archive
Julien Campergue335f5ef2013-10-16 11:02:35 +0200917
Martin Kellye4e94d22017-03-21 16:05:12 -0700918 @property
919 def HasSubmodules(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000920 return self.manifestProject.submodules
Martin Kellye4e94d22017-03-21 16:05:12 -0700921
XD Trol630876f2022-01-17 23:29:04 +0800922 @property
923 def EnableGitLfs(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000924 return self.manifestProject.git_lfs
XD Trol630876f2022-01-17 23:29:04 +0800925
LaMont Jonescc879a92021-11-18 22:40:18 +0000926 def FindManifestByPath(self, path):
927 """Returns the manifest containing path."""
928 path = os.path.abspath(path)
929 manifest = self._outer_client or self
930 old = None
931 while manifest._submanifests and manifest != old:
932 old = manifest
933 for name in manifest._submanifests:
934 tree = manifest._submanifests[name]
935 if path.startswith(tree.repo_client.manifest.topdir):
936 manifest = tree.repo_client
937 break
938 return manifest
939
940 @property
941 def subdir(self):
942 """Returns the path for per-submanifest objects for this manifest."""
943 return self.SubmanifestInfoDir(self.path_prefix)
944
945 def SubmanifestInfoDir(self, submanifest_path, object_path=''):
946 """Return the path to submanifest-specific info for a submanifest.
947
948 Return the full path of the directory in which to put per-manifest objects.
949
950 Args:
951 submanifest_path: a string, the path of the submanifest, relative to the
952 outermost topdir. If empty, then repodir is returned.
953 object_path: a string, relative path to append to the submanifest info
954 directory path.
955 """
956 if submanifest_path:
957 return os.path.join(self.repodir, SUBMANIFEST_DIR, submanifest_path,
958 object_path)
959 else:
960 return os.path.join(self.repodir, object_path)
961
962 def SubmanifestProject(self, submanifest_path):
963 """Return a manifestProject for a submanifest."""
964 subdir = self.SubmanifestInfoDir(submanifest_path)
LaMont Jones9b72cf22022-03-29 21:54:22 +0000965 mp = ManifestProject(self, 'manifests',
966 gitdir=os.path.join(subdir, 'manifests.git'),
967 worktree=os.path.join(subdir, 'manifests'))
LaMont Jonescc879a92021-11-18 22:40:18 +0000968 return mp
969
Raman Tenneti080877e2021-03-09 15:19:06 -0800970 def GetDefaultGroupsStr(self):
971 """Returns the default group string for the platform."""
972 return 'default,platform-' + platform.system().lower()
973
974 def GetGroupsStr(self):
975 """Returns the manifest group string that should be synced."""
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000976 groups = self.manifestProject.manifest_groups
Raman Tenneti080877e2021-03-09 15:19:06 -0800977 if not groups:
978 groups = self.GetDefaultGroupsStr()
979 return groups
980
LaMont Jonesa2ff20d2022-04-07 16:49:06 +0000981 def Unload(self):
982 """Unload the manifest.
983
984 If the manifest files have been changed since Load() was called, this will
985 cause the new/updated manifest to be used.
986
987 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700988 self._loaded = False
989 self._projects = {}
David James8d201162013-10-11 17:03:19 -0700990 self._paths = {}
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700991 self._remotes = {}
992 self._default = None
LaMont Jonescc879a92021-11-18 22:40:18 +0000993 self._submanifests = {}
Doug Anderson37282b42011-03-04 11:54:18 -0800994 self._repo_hooks_project = None
LaMont Jonesd56e2eb2022-04-07 18:14:46 +0000995 self._superproject = None
Raman Tenneti993af5e2021-05-12 12:00:31 -0700996 self._contactinfo = ContactInfo(Wrapper().BUG_URL)
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700997 self._notice = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700998 self.branch = None
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700999 self._manifest_server = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001000
LaMont Jonesa2ff20d2022-04-07 16:49:06 +00001001 def Load(self):
1002 """Read the manifest into memory."""
1003 # Do not expose internal arguments.
1004 self._Load()
1005
LaMont Jonescc879a92021-11-18 22:40:18 +00001006 def _Load(self, initial_client=None, submanifest_depth=0):
1007 if submanifest_depth > MAX_SUBMANIFEST_DEPTH:
1008 raise ManifestParseError('maximum submanifest depth %d exceeded.' %
1009 MAX_SUBMANIFEST_DEPTH)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001010 if not self._loaded:
LaMont Jonescc879a92021-11-18 22:40:18 +00001011 if self._outer_client and self._outer_client != self:
1012 # This will load all clients.
1013 self._outer_client._Load(initial_client=self)
1014
LaMont Jonesb90a4222022-04-14 15:00:09 +00001015 savedManifestFile = self.manifestFile
1016 override = self._outer_client.manifestFileOverrides.get(self.path_prefix)
1017 if override:
1018 self.manifestFile = override
David Pursehouse2d5a0df2012-11-13 02:50:36 +09001019
Joe Onorato26e24752013-01-11 12:35:53 -08001020 try:
LaMont Jonesb90a4222022-04-14 15:00:09 +00001021 m = self.manifestProject
1022 b = m.GetBranch(m.CurrentBranch).merge
1023 if b is not None and b.startswith(R_HEADS):
1024 b = b[len(R_HEADS):]
1025 self.branch = b
Shawn O. Pearce5cc66792008-10-23 16:19:27 -07001026
LaMont Jonesb90a4222022-04-14 15:00:09 +00001027 parent_groups = self.parent_groups
1028 if self.path_prefix:
1029 parent_groups = f'{SUBMANIFEST_GROUP_PREFIX}:path:{self.path_prefix},{parent_groups}'
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001030
LaMont Jonesb90a4222022-04-14 15:00:09 +00001031 # The manifestFile was specified by the user which is why we allow include
1032 # paths to point anywhere.
1033 nodes = []
1034 nodes.append(self._ParseManifestXml(
1035 self.manifestFile, self.manifestProject.worktree,
1036 parent_groups=parent_groups, restrict_includes=False))
1037
1038 if self._load_local_manifests and self.local_manifests:
1039 try:
1040 for local_file in sorted(platform_utils.listdir(self.local_manifests)):
1041 if local_file.endswith('.xml'):
1042 local = os.path.join(self.local_manifests, local_file)
1043 # Since local manifests are entirely managed by the user, allow
1044 # them to point anywhere the user wants.
1045 local_group = f'{LOCAL_MANIFEST_GROUP_PREFIX}:{local_file[:-4]}'
1046 nodes.append(self._ParseManifestXml(
1047 local, self.subdir,
1048 parent_groups=f'{local_group},{parent_groups}',
1049 restrict_includes=False))
1050 except OSError:
1051 pass
1052
1053 try:
1054 self._ParseManifest(nodes)
1055 except ManifestParseError as e:
1056 # There was a problem parsing, unload ourselves in case they catch
1057 # this error and try again later, we will show the correct error
1058 self.Unload()
1059 raise e
1060
1061 if self.IsMirror:
1062 self._AddMetaProjectMirror(self.repoProject)
1063 self._AddMetaProjectMirror(self.manifestProject)
1064
1065 self._loaded = True
1066 finally:
1067 if override:
1068 self.manifestFile = savedManifestFile
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001069
LaMont Jonescc879a92021-11-18 22:40:18 +00001070 # Now that we have loaded this manifest, load any submanifest manifests
1071 # as well. We need to do this after self._loaded is set to avoid looping.
LaMont Jonesd56e2eb2022-04-07 18:14:46 +00001072 for name in self._submanifests:
1073 tree = self._submanifests[name]
LaMont Jonesb90a4222022-04-14 15:00:09 +00001074 spec = tree.ToSubmanifestSpec()
LaMont Jonesd56e2eb2022-04-07 18:14:46 +00001075 present = os.path.exists(os.path.join(self.subdir, MANIFEST_FILE_NAME))
1076 if present and tree.present and not tree.repo_client:
1077 if initial_client and initial_client.topdir == self.topdir:
1078 tree.repo_client = self
1079 tree.present = present
1080 elif not os.path.exists(self.subdir):
1081 tree.present = False
1082 if present and tree.present:
1083 tree.repo_client._Load(initial_client=initial_client,
1084 submanifest_depth=submanifest_depth + 1)
LaMont Jonescc879a92021-11-18 22:40:18 +00001085
Mike Frysinger54133972021-03-01 21:38:08 -05001086 def _ParseManifestXml(self, path, include_root, parent_groups='',
1087 restrict_includes=True):
1088 """Parse a manifest XML and return the computed nodes.
1089
1090 Args:
1091 path: The XML file to read & parse.
1092 include_root: The path to interpret include "name"s relative to.
1093 parent_groups: The groups to apply to this projects.
1094 restrict_includes: Whether to constrain the "name" attribute of includes.
1095
1096 Returns:
1097 List of XML nodes.
1098 """
David Pursehousef7fc8a92012-11-13 04:00:28 +09001099 try:
1100 root = xml.dom.minidom.parse(path)
David Pursehouse2d5a0df2012-11-13 02:50:36 +09001101 except (OSError, xml.parsers.expat.ExpatError) as e:
David Pursehousef7fc8a92012-11-13 04:00:28 +09001102 raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
1103
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001104 if not root or not root.childNodes:
Brian Harring26448742011-04-28 05:04:41 -07001105 raise ManifestParseError("no root node in %s" % (path,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001106
Jooncheol Park34acdd22012-08-27 02:25:59 +09001107 for manifest in root.childNodes:
1108 if manifest.nodeName == 'manifest':
1109 break
1110 else:
Brian Harring26448742011-04-28 05:04:41 -07001111 raise ManifestParseError("no <manifest> in %s" % (path,))
1112
Colin Cross23acdd32012-04-21 00:33:54 -07001113 nodes = []
David Pursehouse65b0ba52018-06-24 16:21:51 +09001114 for node in manifest.childNodes:
David Pursehousec1b86a22012-11-14 11:36:51 +09001115 if node.nodeName == 'include':
1116 name = self._reqatt(node, 'name')
Mike Frysinger54133972021-03-01 21:38:08 -05001117 if restrict_includes:
1118 msg = self._CheckLocalPath(name)
1119 if msg:
1120 raise ManifestInvalidPathError(
1121 '<include> invalid "name": %s: %s' % (name, msg))
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001122 include_groups = ''
1123 if parent_groups:
1124 include_groups = parent_groups
1125 if node.hasAttribute('groups'):
1126 include_groups = node.getAttribute('groups') + ',' + include_groups
David Pursehousec1b86a22012-11-14 11:36:51 +09001127 fp = os.path.join(include_root, name)
1128 if not os.path.isfile(fp):
Mike Frysinger54133972021-03-01 21:38:08 -05001129 raise ManifestParseError("include [%s/]%s doesn't exist or isn't a file"
1130 % (include_root, name))
David Pursehousec1b86a22012-11-14 11:36:51 +09001131 try:
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001132 nodes.extend(self._ParseManifestXml(fp, include_root, include_groups))
David Pursehousec1b86a22012-11-14 11:36:51 +09001133 # should isolate this to the exact exception, but that's
1134 # tricky. actual parsing implementation may vary.
Mike Frysinger54133972021-03-01 21:38:08 -05001135 except (KeyboardInterrupt, RuntimeError, SystemExit, ManifestParseError):
David Pursehousec1b86a22012-11-14 11:36:51 +09001136 raise
1137 except Exception as e:
1138 raise ManifestParseError(
Mike Frysingerec558df2019-07-05 01:38:05 -04001139 "failed parsing included manifest %s: %s" % (name, e))
David Pursehousec1b86a22012-11-14 11:36:51 +09001140 else:
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001141 if parent_groups and node.nodeName == 'project':
1142 nodeGroups = parent_groups
1143 if node.hasAttribute('groups'):
1144 nodeGroups = node.getAttribute('groups') + ',' + nodeGroups
1145 node.setAttribute('groups', nodeGroups)
David Pursehousec1b86a22012-11-14 11:36:51 +09001146 nodes.append(node)
Colin Cross23acdd32012-04-21 00:33:54 -07001147 return nodes
Brian Harring26448742011-04-28 05:04:41 -07001148
Colin Cross23acdd32012-04-21 00:33:54 -07001149 def _ParseManifest(self, node_list):
1150 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001151 if node.nodeName == 'remote':
1152 remote = self._ParseRemote(node)
David Pursehouse717ece92012-11-13 08:49:16 +09001153 if remote:
1154 if remote.name in self._remotes:
1155 if remote != self._remotes[remote.name]:
1156 raise ManifestParseError(
1157 'remote %s already exists with different attributes' %
1158 (remote.name))
1159 else:
1160 self._remotes[remote.name] = remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001161
Colin Cross23acdd32012-04-21 00:33:54 -07001162 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001163 if node.nodeName == 'default':
Julien Campergue74879922013-10-09 14:38:46 +02001164 new_default = self._ParseDefault(node)
Jack Neusb8c84482021-06-15 14:28:30 +00001165 emptyDefault = not node.hasAttributes() and not node.hasChildNodes()
Julien Campergue74879922013-10-09 14:38:46 +02001166 if self._default is None:
1167 self._default = new_default
Jack Neusb8c84482021-06-15 14:28:30 +00001168 elif not emptyDefault and new_default != self._default:
David Pursehouse37128b62013-10-15 10:48:40 +09001169 raise ManifestParseError('duplicate default in %s' %
1170 (self.manifestFile))
Julien Campergue74879922013-10-09 14:38:46 +02001171
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001172 if self._default is None:
1173 self._default = _Default()
1174
LaMont Jonescc879a92021-11-18 22:40:18 +00001175 submanifest_paths = set()
1176 for node in itertools.chain(*node_list):
1177 if node.nodeName == 'submanifest':
1178 submanifest = self._ParseSubmanifest(node)
1179 if submanifest:
1180 if submanifest.name in self._submanifests:
1181 if submanifest != self._submanifests[submanifest.name]:
1182 raise ManifestParseError(
1183 'submanifest %s already exists with different attributes' %
1184 (submanifest.name))
1185 else:
1186 self._submanifests[submanifest.name] = submanifest
1187 submanifest_paths.add(submanifest.relpath)
1188
Colin Cross23acdd32012-04-21 00:33:54 -07001189 for node in itertools.chain(*node_list):
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001190 if node.nodeName == 'notice':
1191 if self._notice is not None:
Doug Anderson37282b42011-03-04 11:54:18 -08001192 raise ManifestParseError(
1193 'duplicate notice in %s' %
1194 (self.manifestFile))
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001195 self._notice = self._ParseNotice(node)
1196
Colin Cross23acdd32012-04-21 00:33:54 -07001197 for node in itertools.chain(*node_list):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001198 if node.nodeName == 'manifest-server':
1199 url = self._reqatt(node, 'url')
1200 if self._manifest_server is not None:
David Pursehousec1b86a22012-11-14 11:36:51 +09001201 raise ManifestParseError(
1202 'duplicate manifest-server in %s' %
1203 (self.manifestFile))
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001204 self._manifest_server = url
1205
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001206 def recursively_add_projects(project):
David James8d201162013-10-11 17:03:19 -07001207 projects = self._projects.setdefault(project.name, [])
1208 if project.relpath is None:
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001209 raise ManifestParseError(
David James8d201162013-10-11 17:03:19 -07001210 'missing path for %s in %s' %
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001211 (project.name, self.manifestFile))
David James8d201162013-10-11 17:03:19 -07001212 if project.relpath in self._paths:
1213 raise ManifestParseError(
1214 'duplicate path %s in %s' %
1215 (project.relpath, self.manifestFile))
LaMont Jonescc879a92021-11-18 22:40:18 +00001216 for tree in submanifest_paths:
1217 if project.relpath.startswith(tree):
1218 raise ManifestParseError(
1219 'project %s conflicts with submanifest path %s' %
1220 (project.relpath, tree))
David James8d201162013-10-11 17:03:19 -07001221 self._paths[project.relpath] = project
1222 projects.append(project)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001223 for subproject in project.subprojects:
1224 recursively_add_projects(subproject)
1225
Jack Neusa84f43a2021-09-21 22:23:55 +00001226 repo_hooks_project = None
1227 enabled_repo_hooks = None
Colin Cross23acdd32012-04-21 00:33:54 -07001228 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001229 if node.nodeName == 'project':
1230 project = self._ParseProject(node)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001231 recursively_add_projects(project)
Josh Triplett884a3872014-06-12 14:57:29 -07001232 if node.nodeName == 'extend-project':
1233 name = self._reqatt(node, 'name')
1234
1235 if name not in self._projects:
1236 raise ManifestParseError('extend-project element specifies non-existent '
1237 'project: %s' % name)
1238
1239 path = node.getAttribute('path')
Michael Kelly37c21c22020-06-13 02:10:40 -07001240 dest_path = node.getAttribute('dest-path')
Josh Triplett884a3872014-06-12 14:57:29 -07001241 groups = node.getAttribute('groups')
1242 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -05001243 groups = self._ParseList(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -07001244 revision = node.getAttribute('revision')
LaMont Jonescc879a92021-11-18 22:40:18 +00001245 remote_name = node.getAttribute('remote')
1246 if not remote_name:
1247 remote = self._default.remote
1248 else:
Kyunam Jobd0aae92020-02-04 11:38:53 +09001249 remote = self._get_remote(node)
Josh Triplett884a3872014-06-12 14:57:29 -07001250
Michael Kelly37c21c22020-06-13 02:10:40 -07001251 named_projects = self._projects[name]
1252 if dest_path and not path and len(named_projects) > 1:
1253 raise ManifestParseError('extend-project cannot use dest-path when '
1254 'matching multiple projects: %s' % name)
Josh Triplett884a3872014-06-12 14:57:29 -07001255 for p in self._projects[name]:
1256 if path and p.relpath != path:
1257 continue
1258 if groups:
1259 p.groups.extend(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -07001260 if revision:
Michael Kelly2f3c3312020-07-21 19:40:38 -07001261 p.SetRevision(revision)
1262
LaMont Jonescc879a92021-11-18 22:40:18 +00001263 if remote_name:
Kyunam Jobd0aae92020-02-04 11:38:53 +09001264 p.remote = remote.ToRemoteSpec(name)
Michael Kelly2f3c3312020-07-21 19:40:38 -07001265
Michael Kelly37c21c22020-06-13 02:10:40 -07001266 if dest_path:
1267 del self._paths[p.relpath]
LaMont Jonescc879a92021-11-18 22:40:18 +00001268 relpath, worktree, gitdir, objdir, _ = self.GetProjectPaths(
1269 name, dest_path, remote.name)
Michael Kelly37c21c22020-06-13 02:10:40 -07001270 p.UpdatePaths(relpath, worktree, gitdir, objdir)
1271 self._paths[p.relpath] = p
1272
Doug Anderson37282b42011-03-04 11:54:18 -08001273 if node.nodeName == 'repo-hooks':
Doug Anderson37282b42011-03-04 11:54:18 -08001274 # Only one project can be the hooks project
Jack Neusa84f43a2021-09-21 22:23:55 +00001275 if repo_hooks_project is not None:
Doug Anderson37282b42011-03-04 11:54:18 -08001276 raise ManifestParseError(
1277 'duplicate repo-hooks in %s' %
1278 (self.manifestFile))
1279
Jack Neusa84f43a2021-09-21 22:23:55 +00001280 # Get the name of the project and the (space-separated) list of enabled.
1281 repo_hooks_project = self._reqatt(node, 'in-project')
1282 enabled_repo_hooks = self._ParseList(self._reqatt(node, 'enabled-list'))
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001283 if node.nodeName == 'superproject':
1284 name = self._reqatt(node, 'name')
1285 # There can only be one superproject.
LaMont Jonesd56e2eb2022-04-07 18:14:46 +00001286 if self._superproject:
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001287 raise ManifestParseError(
1288 'duplicate superproject in %s' %
1289 (self.manifestFile))
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001290 remote_name = node.getAttribute('remote')
1291 if not remote_name:
1292 remote = self._default.remote
1293 else:
1294 remote = self._get_remote(node)
1295 if remote is None:
1296 raise ManifestParseError("no remote for superproject %s within %s" %
1297 (name, self.manifestFile))
Xin Lie0b16a22021-09-26 23:20:32 -07001298 revision = node.getAttribute('revision') or remote.revision
1299 if not revision:
1300 revision = self._default.revisionExpr
1301 if not revision:
1302 raise ManifestParseError('no revision for superproject %s within %s' %
1303 (name, self.manifestFile))
LaMont Jonesd56e2eb2022-04-07 18:14:46 +00001304 self._superproject = Superproject(self,
1305 name=name,
1306 remote=remote.ToRemoteSpec(name),
1307 revision=revision)
Raman Tenneti1c3f57e2021-05-04 12:32:13 -07001308 if node.nodeName == 'contactinfo':
1309 bugurl = self._reqatt(node, 'bugurl')
1310 # This element can be repeated, later entries will clobber earlier ones.
Raman Tenneti993af5e2021-05-12 12:00:31 -07001311 self._contactinfo = ContactInfo(bugurl)
1312
Colin Cross23acdd32012-04-21 00:33:54 -07001313 if node.nodeName == 'remove-project':
1314 name = self._reqatt(node, 'name')
David Jamesb8433df2014-01-30 10:11:17 -08001315
Michael Kelly06da9982021-06-30 01:58:28 -07001316 if name in self._projects:
1317 for p in self._projects[name]:
1318 del self._paths[p.relpath]
1319 del self._projects[name]
1320
1321 # If the manifest removes the hooks project, treat it as if it deleted
1322 # the repo-hooks element too.
Jack Neusa84f43a2021-09-21 22:23:55 +00001323 if repo_hooks_project == name:
1324 repo_hooks_project = None
Michael Kelly06da9982021-06-30 01:58:28 -07001325 elif not XmlBool(node, 'optional', False):
David Pursehousef9107482012-11-16 19:12:32 +09001326 raise ManifestParseError('remove-project element specifies non-existent '
1327 'project: %s' % name)
Colin Cross23acdd32012-04-21 00:33:54 -07001328
Jack Neusa84f43a2021-09-21 22:23:55 +00001329 # Store repo hooks project information.
1330 if repo_hooks_project:
1331 # Store a reference to the Project.
1332 try:
1333 repo_hooks_projects = self._projects[repo_hooks_project]
1334 except KeyError:
1335 raise ManifestParseError(
1336 'project %s not found for repo-hooks' %
1337 (repo_hooks_project))
1338
1339 if len(repo_hooks_projects) != 1:
1340 raise ManifestParseError(
1341 'internal error parsing repo-hooks in %s' %
1342 (self.manifestFile))
1343 self._repo_hooks_project = repo_hooks_projects[0]
1344 # Store the enabled hooks in the Project object.
1345 self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
1346
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001347 def _AddMetaProjectMirror(self, m):
1348 name = None
1349 m_url = m.GetRemote(m.remote.name).url
1350 if m_url.endswith('/.git'):
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301351 raise ManifestParseError('refusing to mirror %s' % m_url)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001352
1353 if self._default and self._default.remote:
Conley Owensceea3682011-10-20 10:45:47 -07001354 url = self._default.remote.resolvedFetchUrl
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001355 if not url.endswith('/'):
1356 url += '/'
1357 if m_url.startswith(url):
1358 remote = self._default.remote
1359 name = m_url[len(url):]
1360
1361 if name is None:
1362 s = m_url.rindex('/') + 1
Conley Owensdb728cd2011-09-26 16:34:01 -07001363 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Shawn O. Pearcef35b2d92012-08-02 11:46:22 -07001364 remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001365 name = m_url[s:]
1366
1367 if name.endswith('.git'):
1368 name = name[:-4]
1369
1370 if name not in self._projects:
1371 m.PreSync()
1372 gitdir = os.path.join(self.topdir, '%s.git' % name)
David Pursehousee5913ae2020-02-12 13:56:59 +09001373 project = Project(manifest=self,
1374 name=name,
1375 remote=remote.ToRemoteSpec(name),
1376 gitdir=gitdir,
1377 objdir=gitdir,
1378 worktree=None,
1379 relpath=name or None,
1380 revisionExpr=m.revisionExpr,
1381 revisionId=None)
David James8d201162013-10-11 17:03:19 -07001382 self._projects[project.name] = [project]
Kwanhong Leeccd218c2014-02-17 13:07:32 +09001383 self._paths[project.relpath] = project
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001384
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001385 def _ParseRemote(self, node):
1386 """
1387 reads a <remote> element from the manifest file
1388 """
1389 name = self._reqatt(node, 'name')
Yestin Sunb292b982012-07-02 07:32:50 -07001390 alias = node.getAttribute('alias')
1391 if alias == '':
1392 alias = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001393 fetch = self._reqatt(node, 'fetch')
Steve Raed6480452016-08-10 15:00:00 -07001394 pushUrl = node.getAttribute('pushurl')
1395 if pushUrl == '':
1396 pushUrl = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001397 review = node.getAttribute('review')
Shawn O. Pearceae6e0942008-11-06 10:25:35 -08001398 if review == '':
1399 review = None
Anthony King36ea2fb2014-05-06 11:54:01 +01001400 revision = node.getAttribute('revision')
1401 if revision == '':
1402 revision = None
Conley Owensdb728cd2011-09-26 16:34:01 -07001403 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Jack Neus6ea0cae2021-07-20 20:52:33 +00001404
1405 remote = _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
1406
1407 for n in node.childNodes:
1408 if n.nodeName == 'annotation':
1409 self._ParseAnnotation(remote, n)
1410
1411 return remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001412
1413 def _ParseDefault(self, node):
1414 """
1415 reads a <default> element from the manifest file
1416 """
1417 d = _Default()
1418 d.remote = self._get_remote(node)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001419 d.revisionExpr = node.getAttribute('revision')
1420 if d.revisionExpr == '':
1421 d.revisionExpr = None
Anatol Pomazau79770d22012-04-20 14:41:59 -07001422
Bryan Jacobsf609f912013-05-06 13:36:24 -04001423 d.destBranchExpr = node.getAttribute('dest-branch') or None
Nasser Grainawida403412018-05-04 12:53:29 -06001424 d.upstreamExpr = node.getAttribute('upstream') or None
Bryan Jacobsf609f912013-05-06 13:36:24 -04001425
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001426 d.sync_j = XmlInt(node, 'sync-j', 1)
1427 if d.sync_j <= 0:
1428 raise ManifestParseError('%s: sync-j must be greater than 0, not "%s"' %
1429 (self.manifestFile, d.sync_j))
Anatol Pomazau79770d22012-04-20 14:41:59 -07001430
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001431 d.sync_c = XmlBool(node, 'sync-c', False)
1432 d.sync_s = XmlBool(node, 'sync-s', False)
1433 d.sync_tags = XmlBool(node, 'sync-tags', True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001434 return d
1435
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001436 def _ParseNotice(self, node):
1437 """
1438 reads a <notice> element from the manifest file
1439
1440 The <notice> element is distinct from other tags in the XML in that the
1441 data is conveyed between the start and end tag (it's not an empty-element
1442 tag).
1443
1444 The white space (carriage returns, indentation) for the notice element is
1445 relevant and is parsed in a way that is based on how python docstrings work.
1446 In fact, the code is remarkably similar to here:
1447 http://www.python.org/dev/peps/pep-0257/
1448 """
1449 # Get the data out of the node...
1450 notice = node.childNodes[0].data
1451
1452 # Figure out minimum indentation, skipping the first line (the same line
1453 # as the <notice> tag)...
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301454 minIndent = sys.maxsize
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001455 lines = notice.splitlines()
1456 for line in lines[1:]:
1457 lstrippedLine = line.lstrip()
1458 if lstrippedLine:
1459 indent = len(line) - len(lstrippedLine)
1460 minIndent = min(indent, minIndent)
1461
1462 # Strip leading / trailing blank lines and also indentation.
1463 cleanLines = [lines[0].strip()]
1464 for line in lines[1:]:
1465 cleanLines.append(line[minIndent:].rstrip())
1466
1467 # Clear completely blank lines from front and back...
1468 while cleanLines and not cleanLines[0]:
1469 del cleanLines[0]
1470 while cleanLines and not cleanLines[-1]:
1471 del cleanLines[-1]
1472
1473 return '\n'.join(cleanLines)
1474
LaMont Jonescc879a92021-11-18 22:40:18 +00001475 def _ParseSubmanifest(self, node):
1476 """Reads a <submanifest> element from the manifest file."""
1477 name = self._reqatt(node, 'name')
1478 remote = node.getAttribute('remote')
1479 if remote == '':
1480 remote = None
1481 project = node.getAttribute('project')
1482 if project == '':
1483 project = None
1484 revision = node.getAttribute('revision')
1485 if revision == '':
1486 revision = None
1487 manifestName = node.getAttribute('manifest-name')
1488 if manifestName == '':
1489 manifestName = None
1490 groups = ''
1491 if node.hasAttribute('groups'):
1492 groups = node.getAttribute('groups')
1493 groups = self._ParseList(groups)
1494 path = node.getAttribute('path')
1495 if path == '':
1496 path = None
1497 if revision:
1498 msg = self._CheckLocalPath(revision.split('/')[-1])
1499 if msg:
1500 raise ManifestInvalidPathError(
1501 '<submanifest> invalid "revision": %s: %s' % (revision, msg))
1502 else:
1503 msg = self._CheckLocalPath(name)
1504 if msg:
1505 raise ManifestInvalidPathError(
1506 '<submanifest> invalid "name": %s: %s' % (name, msg))
1507 else:
1508 msg = self._CheckLocalPath(path)
1509 if msg:
1510 raise ManifestInvalidPathError(
1511 '<submanifest> invalid "path": %s: %s' % (path, msg))
1512
1513 submanifest = _XmlSubmanifest(name, remote, project, revision, manifestName,
1514 groups, path, self)
1515
1516 for n in node.childNodes:
1517 if n.nodeName == 'annotation':
1518 self._ParseAnnotation(submanifest, n)
1519
1520 return submanifest
1521
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001522 def _JoinName(self, parent_name, name):
1523 return os.path.join(parent_name, name)
1524
1525 def _UnjoinName(self, parent_name, name):
1526 return os.path.relpath(name, parent_name)
1527
David Pursehousee5913ae2020-02-12 13:56:59 +09001528 def _ParseProject(self, node, parent=None, **extra_proj_attrs):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001529 """
1530 reads a <project> element from the manifest file
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001531 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001532 name = self._reqatt(node, 'name')
Mike Frysingera29424e2021-02-25 21:53:49 -05001533 msg = self._CheckLocalPath(name, dir_ok=True)
1534 if msg:
1535 raise ManifestInvalidPathError(
1536 '<project> invalid "name": %s: %s' % (name, msg))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001537 if parent:
1538 name = self._JoinName(parent.name, name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001539
1540 remote = self._get_remote(node)
1541 if remote is None:
1542 remote = self._default.remote
1543 if remote is None:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301544 raise ManifestParseError("no remote for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001545 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001546
Anthony King36ea2fb2014-05-06 11:54:01 +01001547 revisionExpr = node.getAttribute('revision') or remote.revision
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001548 if not revisionExpr:
1549 revisionExpr = self._default.revisionExpr
1550 if not revisionExpr:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301551 raise ManifestParseError("no revision for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001552 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001553
1554 path = node.getAttribute('path')
1555 if not path:
1556 path = name
Mike Frysingera29424e2021-02-25 21:53:49 -05001557 else:
Mike Frysinger0458faa2021-03-10 23:35:44 -05001558 # NB: The "." project is handled specially in Project.Sync_LocalHalf.
1559 msg = self._CheckLocalPath(path, dir_ok=True, cwd_dot_ok=True)
Mike Frysingera29424e2021-02-25 21:53:49 -05001560 if msg:
1561 raise ManifestInvalidPathError(
1562 '<project> invalid "path": %s: %s' % (path, msg))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001563
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001564 rebase = XmlBool(node, 'rebase', True)
1565 sync_c = XmlBool(node, 'sync-c', False)
1566 sync_s = XmlBool(node, 'sync-s', self._default.sync_s)
1567 sync_tags = XmlBool(node, 'sync-tags', self._default.sync_tags)
Mike Pontillod3153822012-02-28 11:53:24 -08001568
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001569 clone_depth = XmlInt(node, 'clone-depth')
1570 if clone_depth is not None and clone_depth <= 0:
1571 raise ManifestParseError('%s: clone-depth must be greater than 0, not "%s"' %
1572 (self.manifestFile, clone_depth))
David Pursehouseede7f122012-11-27 22:25:30 +09001573
Bryan Jacobsf609f912013-05-06 13:36:24 -04001574 dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
1575
Nasser Grainawida403412018-05-04 12:53:29 -06001576 upstream = node.getAttribute('upstream') or self._default.upstreamExpr
Brian Harring14a66742012-09-28 20:21:57 -07001577
Conley Owens971de8e2012-04-16 10:36:08 -07001578 groups = ''
1579 if node.hasAttribute('groups'):
1580 groups = node.getAttribute('groups')
Mike Frysinger51e39d52020-12-04 05:32:06 -05001581 groups = self._ParseList(groups)
Brian Harring7da13142012-06-15 02:24:20 -07001582
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001583 if parent is None:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001584 relpath, worktree, gitdir, objdir, use_git_worktrees = \
LaMont Jonescc879a92021-11-18 22:40:18 +00001585 self.GetProjectPaths(name, path, remote.name)
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001586 else:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001587 use_git_worktrees = False
David James8d201162013-10-11 17:03:19 -07001588 relpath, worktree, gitdir, objdir = \
1589 self.GetSubprojectPaths(parent, name, path)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001590
1591 default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
1592 groups.extend(set(default_groups).difference(groups))
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001593
Scott Fandb83b1b2013-02-28 09:34:14 +08001594 if self.IsMirror and node.hasAttribute('force-path'):
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001595 if XmlBool(node, 'force-path', False):
Scott Fandb83b1b2013-02-28 09:34:14 +08001596 gitdir = os.path.join(self.topdir, '%s.git' % path)
1597
David Pursehousee5913ae2020-02-12 13:56:59 +09001598 project = Project(manifest=self,
1599 name=name,
1600 remote=remote.ToRemoteSpec(name),
1601 gitdir=gitdir,
1602 objdir=objdir,
1603 worktree=worktree,
1604 relpath=relpath,
1605 revisionExpr=revisionExpr,
1606 revisionId=None,
1607 rebase=rebase,
1608 groups=groups,
1609 sync_c=sync_c,
1610 sync_s=sync_s,
1611 sync_tags=sync_tags,
1612 clone_depth=clone_depth,
1613 upstream=upstream,
1614 parent=parent,
1615 dest_branch=dest_branch,
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001616 use_git_worktrees=use_git_worktrees,
Simran Basib9a1b732015-08-20 12:19:28 -07001617 **extra_proj_attrs)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001618
1619 for n in node.childNodes:
Shawn O. Pearce242b5262009-05-19 13:00:29 -07001620 if n.nodeName == 'copyfile':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001621 self._ParseCopyFile(project, n)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001622 if n.nodeName == 'linkfile':
1623 self._ParseLinkFile(project, n)
James W. Mills24c13082012-04-12 15:04:13 -05001624 if n.nodeName == 'annotation':
1625 self._ParseAnnotation(project, n)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001626 if n.nodeName == 'project':
David Pursehousee5913ae2020-02-12 13:56:59 +09001627 project.subprojects.append(self._ParseProject(n, parent=project))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001628
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001629 return project
1630
LaMont Jonescc879a92021-11-18 22:40:18 +00001631 def GetProjectPaths(self, name, path, remote):
1632 """Return the paths for a project.
1633
1634 Args:
1635 name: a string, the name of the project.
1636 path: a string, the path of the project.
1637 remote: a string, the remote.name of the project.
1638 """
Mike Frysingercebf2272020-05-26 01:02:29 -04001639 # The manifest entries might have trailing slashes. Normalize them to avoid
1640 # unexpected filesystem behavior since we do string concatenation below.
1641 path = path.rstrip('/')
1642 name = name.rstrip('/')
LaMont Jonescc879a92021-11-18 22:40:18 +00001643 remote = remote.rstrip('/')
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001644 use_git_worktrees = False
LaMont Jonescc879a92021-11-18 22:40:18 +00001645 use_remote_name = bool(self._outer_client._submanifests)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001646 relpath = path
1647 if self.IsMirror:
1648 worktree = None
1649 gitdir = os.path.join(self.topdir, '%s.git' % name)
David James8d201162013-10-11 17:03:19 -07001650 objdir = gitdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001651 else:
LaMont Jonescc879a92021-11-18 22:40:18 +00001652 if use_remote_name:
1653 namepath = os.path.join(remote, f'{name}.git')
1654 else:
1655 namepath = f'{name}.git'
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001656 worktree = os.path.join(self.topdir, path).replace('\\', '/')
LaMont Jonescc879a92021-11-18 22:40:18 +00001657 gitdir = os.path.join(self.subdir, 'projects', '%s.git' % path)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001658 # We allow people to mix git worktrees & non-git worktrees for now.
1659 # This allows for in situ migration of repo clients.
1660 if os.path.exists(gitdir) or not self.UseGitWorktrees:
LaMont Jonescc879a92021-11-18 22:40:18 +00001661 objdir = os.path.join(self.subdir, 'project-objects', namepath)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001662 else:
1663 use_git_worktrees = True
LaMont Jonescc879a92021-11-18 22:40:18 +00001664 gitdir = os.path.join(self.repodir, 'worktrees', namepath)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001665 objdir = gitdir
1666 return relpath, worktree, gitdir, objdir, use_git_worktrees
David James8d201162013-10-11 17:03:19 -07001667
LaMont Jonescc879a92021-11-18 22:40:18 +00001668 def GetProjectsWithName(self, name, all_manifests=False):
1669 """All projects with |name|.
1670
1671 Args:
1672 name: a string, the name of the project.
1673 all_manifests: a boolean, if True, then all manifests are searched. If
1674 False, then only this manifest is searched.
1675 """
1676 if all_manifests:
1677 return list(itertools.chain.from_iterable(
1678 x._projects.get(name, []) for x in self.all_manifests))
David James8d201162013-10-11 17:03:19 -07001679 return self._projects.get(name, [])
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001680
1681 def GetSubprojectName(self, parent, submodule_path):
1682 return os.path.join(parent.name, submodule_path)
1683
1684 def _JoinRelpath(self, parent_relpath, relpath):
1685 return os.path.join(parent_relpath, relpath)
1686
1687 def _UnjoinRelpath(self, parent_relpath, relpath):
1688 return os.path.relpath(relpath, parent_relpath)
1689
David James8d201162013-10-11 17:03:19 -07001690 def GetSubprojectPaths(self, parent, name, path):
Mike Frysingercebf2272020-05-26 01:02:29 -04001691 # The manifest entries might have trailing slashes. Normalize them to avoid
1692 # unexpected filesystem behavior since we do string concatenation below.
1693 path = path.rstrip('/')
1694 name = name.rstrip('/')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001695 relpath = self._JoinRelpath(parent.relpath, path)
1696 gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
David James8d201162013-10-11 17:03:19 -07001697 objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001698 if self.IsMirror:
1699 worktree = None
1700 else:
1701 worktree = os.path.join(parent.worktree, path).replace('\\', '/')
David James8d201162013-10-11 17:03:19 -07001702 return relpath, worktree, gitdir, objdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001703
Mike Frysinger04122b72019-07-31 23:32:58 -04001704 @staticmethod
Mike Frysingera00c5f42021-02-25 18:26:31 -05001705 def _CheckLocalPath(path, dir_ok=False, cwd_dot_ok=False):
1706 """Verify |path| is reasonable for use in filesystem paths.
1707
Mike Frysingera29424e2021-02-25 21:53:49 -05001708 Used with <copyfile> & <linkfile> & <project> elements.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001709
1710 This only validates the |path| in isolation: it does not check against the
1711 current filesystem state. Thus it is suitable as a first-past in a parser.
1712
1713 It enforces a number of constraints:
1714 * No empty paths.
1715 * No "~" in paths.
1716 * No Unicode codepoints that filesystems might elide when normalizing.
1717 * No relative path components like "." or "..".
1718 * No absolute paths.
1719 * No ".git" or ".repo*" path components.
1720
1721 Args:
1722 path: The path name to validate.
1723 dir_ok: Whether |path| may force a directory (e.g. end in a /).
1724 cwd_dot_ok: Whether |path| may be just ".".
1725
1726 Returns:
1727 None if |path| is OK, a failure message otherwise.
1728 """
1729 if not path:
1730 return 'empty paths not allowed'
1731
Mike Frysinger04122b72019-07-31 23:32:58 -04001732 if '~' in path:
1733 return '~ not allowed (due to 8.3 filenames on Windows filesystems)'
1734
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001735 path_codepoints = set(path)
1736
Mike Frysinger04122b72019-07-31 23:32:58 -04001737 # Some filesystems (like Apple's HFS+) try to normalize Unicode codepoints
1738 # which means there are alternative names for ".git". Reject paths with
1739 # these in it as there shouldn't be any reasonable need for them here.
1740 # The set of codepoints here was cribbed from jgit's implementation:
1741 # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
1742 BAD_CODEPOINTS = {
1743 u'\u200C', # ZERO WIDTH NON-JOINER
1744 u'\u200D', # ZERO WIDTH JOINER
1745 u'\u200E', # LEFT-TO-RIGHT MARK
1746 u'\u200F', # RIGHT-TO-LEFT MARK
1747 u'\u202A', # LEFT-TO-RIGHT EMBEDDING
1748 u'\u202B', # RIGHT-TO-LEFT EMBEDDING
1749 u'\u202C', # POP DIRECTIONAL FORMATTING
1750 u'\u202D', # LEFT-TO-RIGHT OVERRIDE
1751 u'\u202E', # RIGHT-TO-LEFT OVERRIDE
1752 u'\u206A', # INHIBIT SYMMETRIC SWAPPING
1753 u'\u206B', # ACTIVATE SYMMETRIC SWAPPING
1754 u'\u206C', # INHIBIT ARABIC FORM SHAPING
1755 u'\u206D', # ACTIVATE ARABIC FORM SHAPING
1756 u'\u206E', # NATIONAL DIGIT SHAPES
1757 u'\u206F', # NOMINAL DIGIT SHAPES
1758 u'\uFEFF', # ZERO WIDTH NO-BREAK SPACE
1759 }
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001760 if BAD_CODEPOINTS & path_codepoints:
Mike Frysinger04122b72019-07-31 23:32:58 -04001761 # This message is more expansive than reality, but should be fine.
1762 return 'Unicode combining characters not allowed'
1763
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001764 # Reject newlines as there shouldn't be any legitmate use for them, they'll
1765 # be confusing to users, and they can easily break tools that expect to be
1766 # able to iterate over newline delimited lists. This even applies to our
1767 # own code like .repo/project.list.
1768 if {'\r', '\n'} & path_codepoints:
1769 return 'Newlines not allowed'
1770
Mike Frysinger04122b72019-07-31 23:32:58 -04001771 # Assume paths might be used on case-insensitive filesystems.
1772 path = path.lower()
1773
Mike Frysingerd9254592020-02-19 22:36:26 -05001774 # Split up the path by its components. We can't use os.path.sep exclusively
1775 # as some platforms (like Windows) will convert / to \ and that bypasses all
1776 # our constructed logic here. Especially since manifest authors only use
1777 # / in their paths.
1778 resep = re.compile(r'[/%s]' % re.escape(os.path.sep))
Mike Frysinger0458faa2021-03-10 23:35:44 -05001779 # Strip off trailing slashes as those only produce '' elements, and we use
1780 # parts to look for individual bad components.
1781 parts = resep.split(path.rstrip('/'))
Mike Frysingerd9254592020-02-19 22:36:26 -05001782
Mike Frysingerae625412020-02-10 17:10:03 -05001783 # Some people use src="." to create stable links to projects. Lets allow
1784 # that but reject all other uses of "." to keep things simple.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001785 if not cwd_dot_ok or parts != ['.']:
Mike Frysingerae625412020-02-10 17:10:03 -05001786 for part in set(parts):
1787 if part in {'.', '..', '.git'} or part.startswith('.repo'):
1788 return 'bad component: %s' % (part,)
Mike Frysinger04122b72019-07-31 23:32:58 -04001789
Mike Frysingera00c5f42021-02-25 18:26:31 -05001790 if not dir_ok and resep.match(path[-1]):
Mike Frysinger04122b72019-07-31 23:32:58 -04001791 return 'dirs not allowed'
1792
Mike Frysingerd9254592020-02-19 22:36:26 -05001793 # NB: The two abspath checks here are to handle platforms with multiple
1794 # filesystem path styles (e.g. Windows).
Mike Frysinger04122b72019-07-31 23:32:58 -04001795 norm = os.path.normpath(path)
Mike Frysingerd9254592020-02-19 22:36:26 -05001796 if (norm == '..' or
1797 (len(norm) >= 3 and norm.startswith('..') and resep.match(norm[0])) or
1798 os.path.isabs(norm) or
1799 norm.startswith('/')):
Mike Frysinger04122b72019-07-31 23:32:58 -04001800 return 'path cannot be outside'
1801
1802 @classmethod
1803 def _ValidateFilePaths(cls, element, src, dest):
1804 """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
1805
1806 We verify the path independent of any filesystem state as we won't have a
1807 checkout available to compare to. i.e. This is for parsing validation
1808 purposes only.
1809
1810 We'll do full/live sanity checking before we do the actual filesystem
1811 modifications in _CopyFile/_LinkFile/etc...
1812 """
1813 # |dest| is the file we write to or symlink we create.
1814 # It is relative to the top of the repo client checkout.
1815 msg = cls._CheckLocalPath(dest)
1816 if msg:
1817 raise ManifestInvalidPathError(
1818 '<%s> invalid "dest": %s: %s' % (element, dest, msg))
1819
1820 # |src| is the file we read from or path we point to for symlinks.
1821 # It is relative to the top of the git project checkout.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001822 is_linkfile = element == 'linkfile'
1823 msg = cls._CheckLocalPath(src, dir_ok=is_linkfile, cwd_dot_ok=is_linkfile)
Mike Frysinger04122b72019-07-31 23:32:58 -04001824 if msg:
1825 raise ManifestInvalidPathError(
1826 '<%s> invalid "src": %s: %s' % (element, src, msg))
1827
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001828 def _ParseCopyFile(self, project, node):
1829 src = self._reqatt(node, 'src')
1830 dest = self._reqatt(node, 'dest')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001831 if not self.IsMirror:
1832 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001833 # dest is relative to the top of the tree.
1834 # We only validate paths if we actually plan to process them.
1835 self._ValidateFilePaths('copyfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001836 project.AddCopyFile(src, dest, self.topdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001837
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001838 def _ParseLinkFile(self, project, node):
1839 src = self._reqatt(node, 'src')
1840 dest = self._reqatt(node, 'dest')
1841 if not self.IsMirror:
1842 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001843 # dest is relative to the top of the tree.
1844 # We only validate paths if we actually plan to process them.
1845 self._ValidateFilePaths('linkfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001846 project.AddLinkFile(src, dest, self.topdir)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001847
Jack Neus6ea0cae2021-07-20 20:52:33 +00001848 def _ParseAnnotation(self, element, node):
James W. Mills24c13082012-04-12 15:04:13 -05001849 name = self._reqatt(node, 'name')
1850 value = self._reqatt(node, 'value')
1851 try:
1852 keep = self._reqatt(node, 'keep').lower()
1853 except ManifestParseError:
1854 keep = "true"
1855 if keep != "true" and keep != "false":
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301856 raise ManifestParseError('optional "keep" attribute must be '
David Pursehouseabdf7502020-02-12 14:58:39 +09001857 '"true" or "false"')
Jack Neus6ea0cae2021-07-20 20:52:33 +00001858 element.AddAnnotation(name, value, keep)
James W. Mills24c13082012-04-12 15:04:13 -05001859
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001860 def _get_remote(self, node):
1861 name = node.getAttribute('remote')
1862 if not name:
1863 return None
1864
1865 v = self._remotes.get(name)
1866 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301867 raise ManifestParseError("remote %s not defined in %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001868 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001869 return v
1870
1871 def _reqatt(self, node, attname):
1872 """
1873 reads a required attribute from the node.
1874 """
1875 v = node.getAttribute(attname)
1876 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301877 raise ManifestParseError("no %s in <%s> within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001878 (attname, node.nodeName, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001879 return v
Julien Camperguedd654222014-01-09 16:21:37 +01001880
1881 def projectsDiff(self, manifest):
1882 """return the projects differences between two manifests.
1883
1884 The diff will be from self to given manifest.
1885
1886 """
1887 fromProjects = self.paths
1888 toProjects = manifest.paths
1889
Anthony King7446c592014-05-06 09:19:39 +01001890 fromKeys = sorted(fromProjects.keys())
1891 toKeys = sorted(toProjects.keys())
Julien Camperguedd654222014-01-09 16:21:37 +01001892
1893 diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
1894
1895 for proj in fromKeys:
David Pursehouseeeff3532020-02-12 11:24:10 +09001896 if proj not in toKeys:
Julien Camperguedd654222014-01-09 16:21:37 +01001897 diff['removed'].append(fromProjects[proj])
1898 else:
1899 fromProj = fromProjects[proj]
1900 toProj = toProjects[proj]
1901 try:
1902 fromRevId = fromProj.GetCommitRevisionId()
1903 toRevId = toProj.GetCommitRevisionId()
1904 except ManifestInvalidRevisionError:
1905 diff['unreachable'].append((fromProj, toProj))
1906 else:
1907 if fromRevId != toRevId:
1908 diff['changed'].append((fromProj, toProj))
1909 toKeys.remove(proj)
1910
1911 for proj in toKeys:
1912 diff['added'].append(toProjects[proj])
1913
1914 return diff
Simran Basib9a1b732015-08-20 12:19:28 -07001915
1916
1917class GitcManifest(XmlManifest):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001918 """Parser for GitC (git-in-the-cloud) manifests."""
Simran Basib9a1b732015-08-20 12:19:28 -07001919
David Pursehousee5913ae2020-02-12 13:56:59 +09001920 def _ParseProject(self, node, parent=None):
Simran Basib9a1b732015-08-20 12:19:28 -07001921 """Override _ParseProject and add support for GITC specific attributes."""
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001922 return super()._ParseProject(
Simran Basib9a1b732015-08-20 12:19:28 -07001923 node, parent=parent, old_revision=node.getAttribute('old-revision'))
1924
1925 def _output_manifest_project_extras(self, p, e):
1926 """Output GITC Specific Project attributes"""
1927 if p.old_revision:
Stefan Beller66851062016-06-17 16:40:08 -07001928 e.setAttribute('old-revision', str(p.old_revision))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001929
1930
1931class RepoClient(XmlManifest):
1932 """Manages a repo client checkout."""
1933
LaMont Jonescc879a92021-11-18 22:40:18 +00001934 def __init__(self, repodir, manifest_file=None, submanifest_path='', **kwargs):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001935 self.isGitcClient = False
LaMont Jonescc879a92021-11-18 22:40:18 +00001936 submanifest_path = submanifest_path or ''
1937 if submanifest_path:
1938 self._CheckLocalPath(submanifest_path)
1939 prefix = os.path.join(repodir, SUBMANIFEST_DIR, submanifest_path)
1940 else:
1941 prefix = repodir
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001942
LaMont Jonescc879a92021-11-18 22:40:18 +00001943 if os.path.exists(os.path.join(prefix, LOCAL_MANIFEST_NAME)):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001944 print('error: %s is not supported; put local manifests in `%s` instead' %
LaMont Jonescc879a92021-11-18 22:40:18 +00001945 (LOCAL_MANIFEST_NAME, os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME)),
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001946 file=sys.stderr)
1947 sys.exit(1)
1948
1949 if manifest_file is None:
LaMont Jonescc879a92021-11-18 22:40:18 +00001950 manifest_file = os.path.join(prefix, MANIFEST_FILE_NAME)
1951 local_manifests = os.path.abspath(os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME))
1952 super().__init__(repodir, manifest_file, local_manifests,
1953 submanifest_path=submanifest_path, **kwargs)
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001954
1955 # TODO: Completely separate manifest logic out of the client.
1956 self.manifest = self
1957
1958
1959class GitcClient(RepoClient, GitcManifest):
1960 """Manages a GitC client checkout."""
1961
1962 def __init__(self, repodir, gitc_client_name):
1963 """Initialize the GitcManifest object."""
1964 self.gitc_client_name = gitc_client_name
1965 self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
1966 gitc_client_name)
1967
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001968 super().__init__(repodir, os.path.join(self.gitc_client_dir, '.manifest'))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001969 self.isGitcClient = True