blob: 7d19d63e8d8164e5caf46cf6daf433cc4a90aa87 [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.
218 annotations: (derived) a list of annotations.
219 present: (derived) a boolean, whether the submanifest's manifest file is present.
220 """
221 def __init__(self,
222 name,
223 remote=None,
224 project=None,
225 revision=None,
226 manifestName=None,
227 groups=None,
228 path=None,
229 parent=None):
230 self.name = name
231 self.remote = remote
232 self.project = project
233 self.revision = revision
234 self.manifestName = manifestName
235 self.groups = groups
236 self.path = path
237 self.annotations = []
238 outer_client = parent._outer_client or parent
239 if self.remote and not self.project:
240 raise ManifestParseError(
241 f'Submanifest {name}: must specify project when remote is given.')
LaMont Jones5d3291d2022-03-23 19:03:02 +0000242 # Construct the absolute path to the manifest file using the parent's
243 # method, so that we can correctly create our repo_client.
244 manifestFile = parent.SubmanifestInfoDir(
245 os.path.join(parent.path_prefix, self.relpath),
246 os.path.join('manifests', manifestName or 'default.xml'))
LaMont Jones55ee3042022-04-06 17:10:21 +0000247 linkFile = parent.SubmanifestInfoDir(
248 os.path.join(parent.path_prefix, self.relpath), MANIFEST_FILE_NAME)
LaMont Jonescc879a92021-11-18 22:40:18 +0000249 rc = self.repo_client = RepoClient(
LaMont Jones55ee3042022-04-06 17:10:21 +0000250 parent.repodir, linkFile, parent_groups=','.join(groups) or '',
LaMont Jonescc879a92021-11-18 22:40:18 +0000251 submanifest_path=self.relpath, outer_client=outer_client)
252
LaMont Jones55ee3042022-04-06 17:10:21 +0000253 self.present = os.path.exists(manifestFile)
LaMont Jonescc879a92021-11-18 22:40:18 +0000254
255 def __eq__(self, other):
256 if not isinstance(other, _XmlSubmanifest):
257 return False
258 return (
259 self.name == other.name and
260 self.remote == other.remote and
261 self.project == other.project and
262 self.revision == other.revision and
263 self.manifestName == other.manifestName and
264 self.groups == other.groups and
265 self.path == other.path and
266 sorted(self.annotations) == sorted(other.annotations))
267
268 def __ne__(self, other):
269 return not self.__eq__(other)
270
271 def ToSubmanifestSpec(self, root):
272 """Return a SubmanifestSpec object, populating attributes"""
273 mp = root.manifestProject
274 remote = root.remotes[self.remote or root.default.remote.name]
275 # If a project was given, generate the url from the remote and project.
276 # If not, use this manifestProject's url.
277 if self.project:
278 manifestUrl = remote.ToRemoteSpec(self.project).url
279 else:
280 manifestUrl = mp.GetRemote(mp.remote.name).url
281 manifestName = self.manifestName or 'default.xml'
282 revision = self.revision or self.name
283 path = self.path or revision.split('/')[-1]
284 groups = self.groups or []
285
286 return SubmanifestSpec(self.name, manifestUrl, manifestName, revision, path,
287 groups)
288
289 @property
290 def relpath(self):
291 """The path of this submanifest relative to the parent manifest."""
292 revision = self.revision or self.name
293 return self.path or revision.split('/')[-1]
294
295 def GetGroupsStr(self):
296 """Returns the `groups` given for this submanifest."""
297 if self.groups:
298 return ','.join(self.groups)
299 return ''
300
301 def AddAnnotation(self, name, value, keep):
302 """Add annotations to the submanifest."""
303 self.annotations.append(Annotation(name, value, keep))
304
305
306class SubmanifestSpec:
307 """The submanifest element, with all fields expanded."""
308
309 def __init__(self,
310 name,
311 manifestUrl,
312 manifestName,
313 revision,
314 path,
315 groups):
316 self.name = name
317 self.manifestUrl = manifestUrl
318 self.manifestName = manifestName
319 self.revision = revision
320 self.path = path
321 self.groups = groups or []
322
323
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700324class XmlManifest(object):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700325 """manages the repo configuration file"""
326
LaMont Jonescc879a92021-11-18 22:40:18 +0000327 def __init__(self, repodir, manifest_file, local_manifests=None,
328 outer_client=None, parent_groups='', submanifest_path=''):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400329 """Initialize.
330
331 Args:
332 repodir: Path to the .repo/ dir for holding all internal checkout state.
333 It must be in the top directory of the repo client checkout.
334 manifest_file: Full path to the manifest file to parse. This will usually
335 be |repodir|/|MANIFEST_FILE_NAME|.
336 local_manifests: Full path to the directory of local override manifests.
337 This will usually be |repodir|/|LOCAL_MANIFESTS_DIR_NAME|.
LaMont Jonescc879a92021-11-18 22:40:18 +0000338 outer_client: RepoClient of the outertree.
339 parent_groups: a string, the groups to apply to this projects.
340 submanifest_path: The submanifest root relative to the repo root.
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400341 """
342 # TODO(vapier): Move this out of this class.
343 self.globalConfig = GitConfig.ForUser()
344
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700345 self.repodir = os.path.abspath(repodir)
LaMont Jonescc879a92021-11-18 22:40:18 +0000346 self._CheckLocalPath(submanifest_path)
347 self.topdir = os.path.join(os.path.dirname(self.repodir), submanifest_path)
LaMont Jones5d3291d2022-03-23 19:03:02 +0000348 if manifest_file != os.path.abspath(manifest_file):
349 raise ManifestParseError('manifest_file must be abspath')
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400350 self.manifestFile = manifest_file
351 self.local_manifests = local_manifests
Basil Gelloc7453502018-05-25 20:23:52 +0300352 self._load_local_manifests = True
LaMont Jonescc879a92021-11-18 22:40:18 +0000353 self.parent_groups = parent_groups
354
355 if outer_client and self.isGitcClient:
356 raise ManifestParseError('Multi-manifest is incompatible with `gitc-init`')
357
358 if submanifest_path and not outer_client:
359 # If passing a submanifest_path, there must be an outer_client.
360 raise ManifestParseError(f'Bad call to {self.__class__.__name__}')
361
362 # If self._outer_client is None, this is not a checkout that supports
363 # multi-tree.
364 self._outer_client = outer_client or self
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700365
LaMont Jones9b72cf22022-03-29 21:54:22 +0000366 self.repoProject = RepoProject(self, 'repo',
David Pursehouseabdf7502020-02-12 14:58:39 +0900367 gitdir=os.path.join(repodir, 'repo/.git'),
368 worktree=os.path.join(repodir, 'repo'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700369
LaMont Jonescc879a92021-11-18 22:40:18 +0000370 mp = self.SubmanifestProject(self.path_prefix)
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500371 self.manifestProject = mp
372
373 # This is a bit hacky, but we're in a chicken & egg situation: all the
374 # normal repo settings live in the manifestProject which we just setup
375 # above, so we couldn't easily query before that. We assume Project()
376 # init doesn't care if this changes afterwards.
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000377 if os.path.exists(mp.gitdir) and mp.use_worktree:
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500378 mp.use_git_worktrees = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700379
LaMont Jonesa2ff20d2022-04-07 16:49:06 +0000380 self.Unload()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700381
Basil Gelloc7453502018-05-25 20:23:52 +0300382 def Override(self, name, load_local_manifests=True):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700383 """Use a different manifest, just for the current instantiation.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700384 """
Basil Gelloc7453502018-05-25 20:23:52 +0300385 path = None
386
387 # Look for a manifest by path in the filesystem (including the cwd).
388 if not load_local_manifests:
389 local_path = os.path.abspath(name)
390 if os.path.isfile(local_path):
391 path = local_path
392
393 # Look for manifests by name from the manifests repo.
394 if path is None:
395 path = os.path.join(self.manifestProject.worktree, name)
396 if not os.path.isfile(path):
397 raise ManifestParseError('manifest %s not found' % name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700398
399 old = self.manifestFile
400 try:
Basil Gelloc7453502018-05-25 20:23:52 +0300401 self._load_local_manifests = load_local_manifests
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700402 self.manifestFile = path
LaMont Jonesa2ff20d2022-04-07 16:49:06 +0000403 self.Unload()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700404 self._Load()
405 finally:
406 self.manifestFile = old
407
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700408 def Link(self, name):
409 """Update the repo metadata to use a different manifest.
410 """
411 self.Override(name)
412
Mike Frysingera269b1c2020-02-21 00:49:41 -0500413 # Old versions of repo would generate symlinks we need to clean up.
Mike Frysinger9d96f582021-09-28 11:27:24 -0400414 platform_utils.remove(self.manifestFile, missing_ok=True)
Mike Frysingera269b1c2020-02-21 00:49:41 -0500415 # This file is interpreted as if it existed inside the manifest repo.
416 # That allows us to use <include> with the relative file name.
417 with open(self.manifestFile, 'w') as fp:
418 fp.write("""<?xml version="1.0" encoding="UTF-8"?>
419<!--
420DO NOT EDIT THIS FILE! It is generated by repo and changes will be discarded.
421If you want to use a different manifest, use `repo init -m <file>` instead.
422
423If you want to customize your checkout by overriding manifest settings, use
424the local_manifests/ directory instead.
425
426For more information on repo manifests, check out:
427https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
428-->
429<manifest>
430 <include name="%s" />
431</manifest>
432""" % (name,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700433
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800434 def _RemoteToXml(self, r, doc, root):
435 e = doc.createElement('remote')
436 root.appendChild(e)
437 e.setAttribute('name', r.name)
438 e.setAttribute('fetch', r.fetchUrl)
Steve Raed6480452016-08-10 15:00:00 -0700439 if r.pushUrl is not None:
440 e.setAttribute('pushurl', r.pushUrl)
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700441 if r.remoteAlias is not None:
442 e.setAttribute('alias', r.remoteAlias)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800443 if r.reviewUrl is not None:
444 e.setAttribute('review', r.reviewUrl)
Anthony King36ea2fb2014-05-06 11:54:01 +0100445 if r.revision is not None:
446 e.setAttribute('revision', r.revision)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800447
Jack Neus6ea0cae2021-07-20 20:52:33 +0000448 for a in r.annotations:
449 if a.keep == 'true':
450 ae = doc.createElement('annotation')
451 ae.setAttribute('name', a.name)
452 ae.setAttribute('value', a.value)
453 e.appendChild(ae)
454
LaMont Jonescc879a92021-11-18 22:40:18 +0000455 def _SubmanifestToXml(self, r, doc, root):
456 """Generate XML <submanifest/> node."""
457 e = doc.createElement('submanifest')
458 root.appendChild(e)
459 e.setAttribute('name', r.name)
460 if r.remote is not None:
461 e.setAttribute('remote', r.remote)
462 if r.project is not None:
463 e.setAttribute('project', r.project)
464 if r.manifestName is not None:
465 e.setAttribute('manifest-name', r.manifestName)
466 if r.revision is not None:
467 e.setAttribute('revision', r.revision)
468 if r.path is not None:
469 e.setAttribute('path', r.path)
470 if r.groups:
471 e.setAttribute('groups', r.GetGroupsStr())
472
473 for a in r.annotations:
474 if a.keep == 'true':
475 ae = doc.createElement('annotation')
476 ae.setAttribute('name', a.name)
477 ae.setAttribute('value', a.value)
478 e.appendChild(ae)
479
Mike Frysinger51e39d52020-12-04 05:32:06 -0500480 def _ParseList(self, field):
481 """Parse fields that contain flattened lists.
482
483 These are whitespace & comma separated. Empty elements will be discarded.
484 """
485 return [x for x in re.split(r'[,\s]+', field) if x]
Josh Triplett884a3872014-06-12 14:57:29 -0700486
Mike Frysinger23411d32020-09-02 04:31:10 -0400487 def ToXml(self, peg_rev=False, peg_rev_upstream=True, peg_rev_dest_branch=True, groups=None):
488 """Return the current manifest XML."""
Colin Cross5acde752012-03-28 20:15:45 -0700489 mp = self.manifestProject
490
Dan Willemsen5ea32d12015-09-08 13:27:20 -0700491 if groups is None:
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000492 groups = mp.manifest_groups
Matt Gumbel0c635bb2012-12-21 10:14:53 -0800493 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -0500494 groups = self._ParseList(groups)
Colin Cross5acde752012-03-28 20:15:45 -0700495
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800496 doc = xml.dom.minidom.Document()
497 root = doc.createElement('manifest')
LaMont Jonescc879a92021-11-18 22:40:18 +0000498 if self.is_submanifest:
499 root.setAttribute('path', self.path_prefix)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800500 doc.appendChild(root)
501
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700502 # Save out the notice. There's a little bit of work here to give it the
503 # right whitespace, which assumes that the notice is automatically indented
504 # by 4 by minidom.
505 if self.notice:
506 notice_element = root.appendChild(doc.createElement('notice'))
507 notice_lines = self.notice.splitlines()
David Pursehouse54a4e602020-02-12 14:31:05 +0900508 indented_notice = ('\n'.join(" " * 4 + line for line in notice_lines))[4:]
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700509 notice_element.appendChild(doc.createTextNode(indented_notice))
510
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800511 d = self.default
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800512
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530513 for r in sorted(self.remotes):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800514 self._RemoteToXml(self.remotes[r], doc, root)
515 if self.remotes:
516 root.appendChild(doc.createTextNode(''))
517
518 have_default = False
519 e = doc.createElement('default')
520 if d.remote:
521 have_default = True
522 e.setAttribute('remote', d.remote.name)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700523 if d.revisionExpr:
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800524 have_default = True
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700525 e.setAttribute('revision', d.revisionExpr)
Simon Ruggier7e59de22015-07-24 12:50:06 +0200526 if d.destBranchExpr:
527 have_default = True
528 e.setAttribute('dest-branch', d.destBranchExpr)
Nasser Grainawida403412018-05-04 12:53:29 -0600529 if d.upstreamExpr:
530 have_default = True
531 e.setAttribute('upstream', d.upstreamExpr)
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700532 if d.sync_j > 1:
533 have_default = True
534 e.setAttribute('sync-j', '%d' % d.sync_j)
Anatol Pomazau79770d22012-04-20 14:41:59 -0700535 if d.sync_c:
536 have_default = True
537 e.setAttribute('sync-c', 'true')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800538 if d.sync_s:
539 have_default = True
540 e.setAttribute('sync-s', 'true')
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900541 if not d.sync_tags:
542 have_default = True
543 e.setAttribute('sync-tags', 'false')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800544 if have_default:
545 root.appendChild(e)
546 root.appendChild(doc.createTextNode(''))
547
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700548 if self._manifest_server:
549 e = doc.createElement('manifest-server')
550 e.setAttribute('url', self._manifest_server)
551 root.appendChild(e)
552 root.appendChild(doc.createTextNode(''))
553
LaMont Jonescc879a92021-11-18 22:40:18 +0000554 for r in sorted(self.submanifests):
555 self._SubmanifestToXml(self.submanifests[r], doc, root)
556 if self.submanifests:
557 root.appendChild(doc.createTextNode(''))
558
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800559 def output_projects(parent, parent_node, projects):
David James8d201162013-10-11 17:03:19 -0700560 for project_name in projects:
561 for project in self._projects[project_name]:
562 output_project(parent, parent_node, project)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800563
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800564 def output_project(parent, parent_node, p):
Colin Cross5acde752012-03-28 20:15:45 -0700565 if not p.MatchesGroups(groups):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800566 return
567
568 name = p.name
569 relpath = p.relpath
570 if parent:
571 name = self._UnjoinName(parent.name, name)
572 relpath = self._UnjoinRelpath(parent.relpath, relpath)
Colin Cross5acde752012-03-28 20:15:45 -0700573
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800574 e = doc.createElement('project')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800575 parent_node.appendChild(e)
576 e.setAttribute('name', name)
577 if relpath != name:
578 e.setAttribute('path', relpath)
Conley Owensa17d7af2013-10-16 14:38:09 -0700579 remoteName = None
580 if d.remote:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700581 remoteName = d.remote.name
582 if not d.remote or p.remote.orig_name != remoteName:
583 remoteName = p.remote.orig_name
Anthony King36ea2fb2014-05-06 11:54:01 +0100584 e.setAttribute('remote', remoteName)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800585 if peg_rev:
586 if self.IsMirror:
Brian Harring14a66742012-09-28 20:21:57 -0700587 value = p.bare_git.rev_parse(p.revisionExpr + '^0')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800588 else:
Brian Harring14a66742012-09-28 20:21:57 -0700589 value = p.work_git.rev_parse(HEAD + '^0')
590 e.setAttribute('revision', value)
Conley Owens551dfec2015-07-10 14:54:54 -0700591 if peg_rev_upstream:
592 if p.upstream:
593 e.setAttribute('upstream', p.upstream)
594 elif value != p.revisionExpr:
595 # Only save the origin if the origin is not a sha1, and the default
596 # isn't our value
597 e.setAttribute('upstream', p.revisionExpr)
Sean McAllisteraf908cb2020-04-20 08:41:58 -0600598
599 if peg_rev_dest_branch:
600 if p.dest_branch:
601 e.setAttribute('dest-branch', p.dest_branch)
602 elif value != p.revisionExpr:
603 e.setAttribute('dest-branch', p.revisionExpr)
604
Anthony King36ea2fb2014-05-06 11:54:01 +0100605 else:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700606 revision = self.remotes[p.remote.orig_name].revision or d.revisionExpr
Anthony King36ea2fb2014-05-06 11:54:01 +0100607 if not revision or revision != p.revisionExpr:
608 e.setAttribute('revision', p.revisionExpr)
Raman Tennetib5c5a5e2021-02-06 09:44:15 -0800609 elif p.revisionId:
610 e.setAttribute('revision', p.revisionId)
Nasser Grainawida403412018-05-04 12:53:29 -0600611 if (p.upstream and (p.upstream != p.revisionExpr or
612 p.upstream != d.upstreamExpr)):
Mani Chandel7a91d512014-07-24 16:27:08 +0530613 e.setAttribute('upstream', p.upstream)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800614
Simon Ruggier7e59de22015-07-24 12:50:06 +0200615 if p.dest_branch and p.dest_branch != d.destBranchExpr:
616 e.setAttribute('dest-branch', p.dest_branch)
617
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800618 for c in p.copyfiles:
619 ce = doc.createElement('copyfile')
620 ce.setAttribute('src', c.src)
621 ce.setAttribute('dest', c.dest)
622 e.appendChild(ce)
623
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500624 for l in p.linkfiles:
625 le = doc.createElement('linkfile')
626 le.setAttribute('src', l.src)
627 le.setAttribute('dest', l.dest)
628 e.appendChild(le)
629
Conley Owensbb1b5f52012-08-13 13:11:18 -0700630 default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
Dmitry Fink17f85ea2012-08-06 14:52:29 -0700631 egroups = [g for g in p.groups if g not in default_groups]
Conley Owens971de8e2012-04-16 10:36:08 -0700632 if egroups:
633 e.setAttribute('groups', ','.join(egroups))
Colin Cross5acde752012-03-28 20:15:45 -0700634
James W. Mills24c13082012-04-12 15:04:13 -0500635 for a in p.annotations:
636 if a.keep == "true":
637 ae = doc.createElement('annotation')
638 ae.setAttribute('name', a.name)
639 ae.setAttribute('value', a.value)
640 e.appendChild(ae)
641
Anatol Pomazau79770d22012-04-20 14:41:59 -0700642 if p.sync_c:
643 e.setAttribute('sync-c', 'true')
644
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800645 if p.sync_s:
646 e.setAttribute('sync-s', 'true')
647
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900648 if not p.sync_tags:
649 e.setAttribute('sync-tags', 'false')
650
Dan Willemsen88409222015-08-17 15:29:10 -0700651 if p.clone_depth:
652 e.setAttribute('clone-depth', str(p.clone_depth))
653
Simran Basib9a1b732015-08-20 12:19:28 -0700654 self._output_manifest_project_extras(p, e)
655
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800656 if p.subprojects:
David James8d201162013-10-11 17:03:19 -0700657 subprojects = set(subp.name for subp in p.subprojects)
658 output_projects(p, e, list(sorted(subprojects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800659
David James8d201162013-10-11 17:03:19 -0700660 projects = set(p.name for p in self._paths.values() if not p.parent)
661 output_projects(None, root, list(sorted(projects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800662
Doug Anderson37282b42011-03-04 11:54:18 -0800663 if self._repo_hooks_project:
664 root.appendChild(doc.createTextNode(''))
665 e = doc.createElement('repo-hooks')
666 e.setAttribute('in-project', self._repo_hooks_project.name)
667 e.setAttribute('enabled-list',
668 ' '.join(self._repo_hooks_project.enabled_repo_hooks))
669 root.appendChild(e)
670
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800671 if self._superproject:
672 root.appendChild(doc.createTextNode(''))
673 e = doc.createElement('superproject')
LaMont Jonesd56e2eb2022-04-07 18:14:46 +0000674 e.setAttribute('name', self._superproject.name)
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800675 remoteName = None
676 if d.remote:
677 remoteName = d.remote.name
LaMont Jonesd56e2eb2022-04-07 18:14:46 +0000678 remote = self._superproject.remote
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800679 if not d.remote or remote.orig_name != remoteName:
680 remoteName = remote.orig_name
681 e.setAttribute('remote', remoteName)
Xin Lie0b16a22021-09-26 23:20:32 -0700682 revision = remote.revision or d.revisionExpr
LaMont Jonesd56e2eb2022-04-07 18:14:46 +0000683 if not revision or revision != self._superproject.revision:
684 e.setAttribute('revision', self._superproject.revision)
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800685 root.appendChild(e)
686
Raman Tenneti993af5e2021-05-12 12:00:31 -0700687 if self._contactinfo.bugurl != Wrapper().BUG_URL:
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700688 root.appendChild(doc.createTextNode(''))
689 e = doc.createElement('contactinfo')
Raman Tenneti993af5e2021-05-12 12:00:31 -0700690 e.setAttribute('bugurl', self._contactinfo.bugurl)
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700691 root.appendChild(e)
692
Mike Frysinger23411d32020-09-02 04:31:10 -0400693 return doc
694
695 def ToDict(self, **kwargs):
696 """Return the current manifest as a dictionary."""
697 # Elements that may only appear once.
698 SINGLE_ELEMENTS = {
699 'notice',
700 'default',
701 'manifest-server',
702 'repo-hooks',
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800703 'superproject',
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700704 'contactinfo',
Mike Frysinger23411d32020-09-02 04:31:10 -0400705 }
706 # Elements that may be repeated.
707 MULTI_ELEMENTS = {
708 'remote',
709 'remove-project',
710 'project',
711 'extend-project',
712 'include',
LaMont Jonescc879a92021-11-18 22:40:18 +0000713 'submanifest',
Mike Frysinger23411d32020-09-02 04:31:10 -0400714 # These are children of 'project' nodes.
715 'annotation',
716 'project',
717 'copyfile',
718 'linkfile',
719 }
720
721 doc = self.ToXml(**kwargs)
722 ret = {}
723
724 def append_children(ret, node):
725 for child in node.childNodes:
726 if child.nodeType == xml.dom.Node.ELEMENT_NODE:
727 attrs = child.attributes
728 element = dict((attrs.item(i).localName, attrs.item(i).value)
729 for i in range(attrs.length))
730 if child.nodeName in SINGLE_ELEMENTS:
731 ret[child.nodeName] = element
732 elif child.nodeName in MULTI_ELEMENTS:
733 ret.setdefault(child.nodeName, []).append(element)
734 else:
735 raise ManifestParseError('Unhandled element "%s"' % (child.nodeName,))
736
737 append_children(element, child)
738
739 append_children(ret, doc.firstChild)
740
741 return ret
742
743 def Save(self, fd, **kwargs):
744 """Write the current manifest out to the given file descriptor."""
745 doc = self.ToXml(**kwargs)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800746 doc.writexml(fd, '', ' ', '\n', 'UTF-8')
747
Simran Basib9a1b732015-08-20 12:19:28 -0700748 def _output_manifest_project_extras(self, p, e):
749 """Manifests can modify e if they support extra project attributes."""
Simran Basib9a1b732015-08-20 12:19:28 -0700750
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700751 @property
LaMont Jonescc879a92021-11-18 22:40:18 +0000752 def is_multimanifest(self):
753 """Whether this is a multimanifest checkout"""
754 return bool(self.outer_client.submanifests)
755
756 @property
757 def is_submanifest(self):
758 """Whether this manifest is a submanifest"""
759 return self._outer_client and self._outer_client != self
760
761 @property
762 def outer_client(self):
763 """The instance of the outermost manifest client"""
764 self._Load()
765 return self._outer_client
766
767 @property
768 def all_manifests(self):
769 """Generator yielding all (sub)manifests."""
770 self._Load()
771 outer = self._outer_client
772 yield outer
773 for tree in outer.all_children:
774 yield tree
775
776 @property
777 def all_children(self):
778 """Generator yielding all child submanifests."""
779 self._Load()
780 for child in self._submanifests.values():
781 if child.repo_client:
782 yield child.repo_client
783 for tree in child.repo_client.all_children:
784 yield tree
785
786 @property
787 def path_prefix(self):
788 """The path of this submanifest, relative to the outermost manifest."""
789 if not self._outer_client or self == self._outer_client:
790 return ''
791 return os.path.relpath(self.topdir, self._outer_client.topdir)
792
793 @property
794 def all_paths(self):
795 """All project paths for all (sub)manifests. See `paths`."""
796 ret = {}
797 for tree in self.all_manifests:
798 prefix = tree.path_prefix
799 ret.update({os.path.join(prefix, k): v for k, v in tree.paths.items()})
800 return ret
801
802 @property
803 def all_projects(self):
804 """All projects for all (sub)manifests. See `projects`."""
805 return list(itertools.chain.from_iterable(x._paths.values() for x in self.all_manifests))
806
807 @property
David James8d201162013-10-11 17:03:19 -0700808 def paths(self):
LaMont Jonescc879a92021-11-18 22:40:18 +0000809 """Return all paths for this manifest.
810
811 Return:
812 A dictionary of {path: Project()}. `path` is relative to this manifest.
813 """
David James8d201162013-10-11 17:03:19 -0700814 self._Load()
815 return self._paths
816
817 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700818 def projects(self):
LaMont Jonescc879a92021-11-18 22:40:18 +0000819 """Return a list of all Projects in this manifest."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700820 self._Load()
Anthony Kingd58bfe52014-05-05 23:30:49 +0100821 return list(self._paths.values())
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700822
823 @property
824 def remotes(self):
825 self._Load()
826 return self._remotes
827
828 @property
829 def default(self):
830 self._Load()
831 return self._default
832
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800833 @property
LaMont Jonescc879a92021-11-18 22:40:18 +0000834 def submanifests(self):
835 """All submanifests in this manifest."""
836 self._Load()
837 return self._submanifests
838
839 @property
Doug Anderson37282b42011-03-04 11:54:18 -0800840 def repo_hooks_project(self):
841 self._Load()
842 return self._repo_hooks_project
843
844 @property
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800845 def superproject(self):
846 self._Load()
847 return self._superproject
848
849 @property
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700850 def contactinfo(self):
851 self._Load()
852 return self._contactinfo
853
854 @property
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700855 def notice(self):
856 self._Load()
857 return self._notice
858
859 @property
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700860 def manifest_server(self):
861 self._Load()
Shawn O. Pearce34fb20f2011-11-30 13:41:02 -0800862 return self._manifest_server
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700863
864 @property
Xin Lid79a4bc2020-05-20 16:03:45 -0700865 def CloneBundle(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000866 clone_bundle = self.manifestProject.clone_bundle
Xin Lid79a4bc2020-05-20 16:03:45 -0700867 if clone_bundle is None:
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000868 return False if self.manifestProject.partial_clone else True
Xin Lid79a4bc2020-05-20 16:03:45 -0700869 else:
870 return clone_bundle
871
872 @property
Xin Li745be2e2019-06-03 11:24:30 -0700873 def CloneFilter(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000874 if self.manifestProject.partial_clone:
875 return self.manifestProject.clone_filter
Xin Li745be2e2019-06-03 11:24:30 -0700876 return None
877
878 @property
Raman Tennetif32f2432021-04-12 20:57:25 -0700879 def PartialCloneExclude(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000880 exclude = self.manifest.manifestProject.partial_clone_exclude or ''
Raman Tennetif32f2432021-04-12 20:57:25 -0700881 return set(x.strip() for x in exclude.split(','))
882
883 @property
Michael Kellyc34b91c2021-07-02 09:25:48 -0700884 def UseLocalManifests(self):
885 return self._load_local_manifests
886
887 def SetUseLocalManifests(self, value):
888 self._load_local_manifests = value
889
890 @property
Raman Tennetifeb28912021-05-02 19:47:29 -0700891 def HasLocalManifests(self):
892 return self._load_local_manifests and self.local_manifests
893
LaMont Jones87cce682022-02-14 17:48:31 +0000894 def IsFromLocalManifest(self, project):
LaMont Jonescc879a92021-11-18 22:40:18 +0000895 """Is the project from a local manifest?"""
LaMont Jones87cce682022-02-14 17:48:31 +0000896 return any(x.startswith(LOCAL_MANIFEST_GROUP_PREFIX)
897 for x in project.groups)
898
Raman Tennetifeb28912021-05-02 19:47:29 -0700899 @property
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800900 def IsMirror(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000901 return self.manifestProject.mirror
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800902
Julien Campergue335f5ef2013-10-16 11:02:35 +0200903 @property
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500904 def UseGitWorktrees(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000905 return self.manifestProject.use_worktree
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500906
907 @property
Julien Campergue335f5ef2013-10-16 11:02:35 +0200908 def IsArchive(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000909 return self.manifestProject.archive
Julien Campergue335f5ef2013-10-16 11:02:35 +0200910
Martin Kellye4e94d22017-03-21 16:05:12 -0700911 @property
912 def HasSubmodules(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000913 return self.manifestProject.submodules
Martin Kellye4e94d22017-03-21 16:05:12 -0700914
XD Trol630876f2022-01-17 23:29:04 +0800915 @property
916 def EnableGitLfs(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000917 return self.manifestProject.git_lfs
XD Trol630876f2022-01-17 23:29:04 +0800918
LaMont Jonescc879a92021-11-18 22:40:18 +0000919 def FindManifestByPath(self, path):
920 """Returns the manifest containing path."""
921 path = os.path.abspath(path)
922 manifest = self._outer_client or self
923 old = None
924 while manifest._submanifests and manifest != old:
925 old = manifest
926 for name in manifest._submanifests:
927 tree = manifest._submanifests[name]
928 if path.startswith(tree.repo_client.manifest.topdir):
929 manifest = tree.repo_client
930 break
931 return manifest
932
933 @property
934 def subdir(self):
935 """Returns the path for per-submanifest objects for this manifest."""
936 return self.SubmanifestInfoDir(self.path_prefix)
937
938 def SubmanifestInfoDir(self, submanifest_path, object_path=''):
939 """Return the path to submanifest-specific info for a submanifest.
940
941 Return the full path of the directory in which to put per-manifest objects.
942
943 Args:
944 submanifest_path: a string, the path of the submanifest, relative to the
945 outermost topdir. If empty, then repodir is returned.
946 object_path: a string, relative path to append to the submanifest info
947 directory path.
948 """
949 if submanifest_path:
950 return os.path.join(self.repodir, SUBMANIFEST_DIR, submanifest_path,
951 object_path)
952 else:
953 return os.path.join(self.repodir, object_path)
954
955 def SubmanifestProject(self, submanifest_path):
956 """Return a manifestProject for a submanifest."""
957 subdir = self.SubmanifestInfoDir(submanifest_path)
LaMont Jones9b72cf22022-03-29 21:54:22 +0000958 mp = ManifestProject(self, 'manifests',
959 gitdir=os.path.join(subdir, 'manifests.git'),
960 worktree=os.path.join(subdir, 'manifests'))
LaMont Jonescc879a92021-11-18 22:40:18 +0000961 return mp
962
Raman Tenneti080877e2021-03-09 15:19:06 -0800963 def GetDefaultGroupsStr(self):
964 """Returns the default group string for the platform."""
965 return 'default,platform-' + platform.system().lower()
966
967 def GetGroupsStr(self):
968 """Returns the manifest group string that should be synced."""
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000969 groups = self.manifestProject.manifest_groups
Raman Tenneti080877e2021-03-09 15:19:06 -0800970 if not groups:
971 groups = self.GetDefaultGroupsStr()
972 return groups
973
LaMont Jonesa2ff20d2022-04-07 16:49:06 +0000974 def Unload(self):
975 """Unload the manifest.
976
977 If the manifest files have been changed since Load() was called, this will
978 cause the new/updated manifest to be used.
979
980 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700981 self._loaded = False
982 self._projects = {}
David James8d201162013-10-11 17:03:19 -0700983 self._paths = {}
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700984 self._remotes = {}
985 self._default = None
LaMont Jonescc879a92021-11-18 22:40:18 +0000986 self._submanifests = {}
Doug Anderson37282b42011-03-04 11:54:18 -0800987 self._repo_hooks_project = None
LaMont Jonesd56e2eb2022-04-07 18:14:46 +0000988 self._superproject = None
Raman Tenneti993af5e2021-05-12 12:00:31 -0700989 self._contactinfo = ContactInfo(Wrapper().BUG_URL)
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700990 self._notice = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700991 self.branch = None
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700992 self._manifest_server = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700993
LaMont Jonesa2ff20d2022-04-07 16:49:06 +0000994 def Load(self):
995 """Read the manifest into memory."""
996 # Do not expose internal arguments.
997 self._Load()
998
LaMont Jonescc879a92021-11-18 22:40:18 +0000999 def _Load(self, initial_client=None, submanifest_depth=0):
1000 if submanifest_depth > MAX_SUBMANIFEST_DEPTH:
1001 raise ManifestParseError('maximum submanifest depth %d exceeded.' %
1002 MAX_SUBMANIFEST_DEPTH)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001003 if not self._loaded:
LaMont Jonescc879a92021-11-18 22:40:18 +00001004 if self._outer_client and self._outer_client != self:
1005 # This will load all clients.
1006 self._outer_client._Load(initial_client=self)
1007
Shawn O. Pearce2450a292008-11-04 08:22:07 -08001008 m = self.manifestProject
1009 b = m.GetBranch(m.CurrentBranch).merge
Shawn O. Pearce21c5c342009-06-25 16:47:30 -07001010 if b is not None and b.startswith(R_HEADS):
Shawn O. Pearce2450a292008-11-04 08:22:07 -08001011 b = b[len(R_HEADS):]
1012 self.branch = b
1013
LaMont Jonescc879a92021-11-18 22:40:18 +00001014 parent_groups = self.parent_groups
LaMont Jonesb308db12022-02-25 17:05:21 +00001015 if self.path_prefix:
1016 parent_groups = f'{SUBMANIFEST_GROUP_PREFIX}:path:{self.path_prefix},{parent_groups}'
LaMont Jonescc879a92021-11-18 22:40:18 +00001017
Mike Frysinger54133972021-03-01 21:38:08 -05001018 # The manifestFile was specified by the user which is why we allow include
1019 # paths to point anywhere.
Colin Cross23acdd32012-04-21 00:33:54 -07001020 nodes = []
Mike Frysinger54133972021-03-01 21:38:08 -05001021 nodes.append(self._ParseManifestXml(
1022 self.manifestFile, self.manifestProject.worktree,
LaMont Jonescc879a92021-11-18 22:40:18 +00001023 parent_groups=parent_groups, restrict_includes=False))
Shawn O. Pearce5cc66792008-10-23 16:19:27 -07001024
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001025 if self._load_local_manifests and self.local_manifests:
Basil Gelloc7453502018-05-25 20:23:52 +03001026 try:
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001027 for local_file in sorted(platform_utils.listdir(self.local_manifests)):
Basil Gelloc7453502018-05-25 20:23:52 +03001028 if local_file.endswith('.xml'):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001029 local = os.path.join(self.local_manifests, local_file)
Mike Frysinger54133972021-03-01 21:38:08 -05001030 # Since local manifests are entirely managed by the user, allow
1031 # them to point anywhere the user wants.
LaMont Jonescc879a92021-11-18 22:40:18 +00001032 local_group = f'{LOCAL_MANIFEST_GROUP_PREFIX}:{local_file[:-4]}'
Mike Frysinger54133972021-03-01 21:38:08 -05001033 nodes.append(self._ParseManifestXml(
LaMont Jonescc879a92021-11-18 22:40:18 +00001034 local, self.subdir,
1035 parent_groups=f'{local_group},{parent_groups}',
Raman Tenneti78f4dd32021-06-07 13:27:37 -07001036 restrict_includes=False))
Basil Gelloc7453502018-05-25 20:23:52 +03001037 except OSError:
1038 pass
David Pursehouse2d5a0df2012-11-13 02:50:36 +09001039
Joe Onorato26e24752013-01-11 12:35:53 -08001040 try:
1041 self._ParseManifest(nodes)
1042 except ManifestParseError as e:
1043 # There was a problem parsing, unload ourselves in case they catch
1044 # this error and try again later, we will show the correct error
LaMont Jonesa2ff20d2022-04-07 16:49:06 +00001045 self.Unload()
Joe Onorato26e24752013-01-11 12:35:53 -08001046 raise e
Shawn O. Pearce5cc66792008-10-23 16:19:27 -07001047
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001048 if self.IsMirror:
1049 self._AddMetaProjectMirror(self.repoProject)
1050 self._AddMetaProjectMirror(self.manifestProject)
1051
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001052 self._loaded = True
1053
LaMont Jonescc879a92021-11-18 22:40:18 +00001054 # Now that we have loaded this manifest, load any submanifest manifests
1055 # as well. We need to do this after self._loaded is set to avoid looping.
LaMont Jonesd56e2eb2022-04-07 18:14:46 +00001056 for name in self._submanifests:
1057 tree = self._submanifests[name]
1058 spec = tree.ToSubmanifestSpec(self)
1059 present = os.path.exists(os.path.join(self.subdir, MANIFEST_FILE_NAME))
1060 if present and tree.present and not tree.repo_client:
1061 if initial_client and initial_client.topdir == self.topdir:
1062 tree.repo_client = self
1063 tree.present = present
1064 elif not os.path.exists(self.subdir):
1065 tree.present = False
1066 if present and tree.present:
1067 tree.repo_client._Load(initial_client=initial_client,
1068 submanifest_depth=submanifest_depth + 1)
LaMont Jonescc879a92021-11-18 22:40:18 +00001069
Mike Frysinger54133972021-03-01 21:38:08 -05001070 def _ParseManifestXml(self, path, include_root, parent_groups='',
1071 restrict_includes=True):
1072 """Parse a manifest XML and return the computed nodes.
1073
1074 Args:
1075 path: The XML file to read & parse.
1076 include_root: The path to interpret include "name"s relative to.
1077 parent_groups: The groups to apply to this projects.
1078 restrict_includes: Whether to constrain the "name" attribute of includes.
1079
1080 Returns:
1081 List of XML nodes.
1082 """
David Pursehousef7fc8a92012-11-13 04:00:28 +09001083 try:
1084 root = xml.dom.minidom.parse(path)
David Pursehouse2d5a0df2012-11-13 02:50:36 +09001085 except (OSError, xml.parsers.expat.ExpatError) as e:
David Pursehousef7fc8a92012-11-13 04:00:28 +09001086 raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
1087
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001088 if not root or not root.childNodes:
Brian Harring26448742011-04-28 05:04:41 -07001089 raise ManifestParseError("no root node in %s" % (path,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001090
Jooncheol Park34acdd22012-08-27 02:25:59 +09001091 for manifest in root.childNodes:
1092 if manifest.nodeName == 'manifest':
1093 break
1094 else:
Brian Harring26448742011-04-28 05:04:41 -07001095 raise ManifestParseError("no <manifest> in %s" % (path,))
1096
Colin Cross23acdd32012-04-21 00:33:54 -07001097 nodes = []
David Pursehouse65b0ba52018-06-24 16:21:51 +09001098 for node in manifest.childNodes:
David Pursehousec1b86a22012-11-14 11:36:51 +09001099 if node.nodeName == 'include':
1100 name = self._reqatt(node, 'name')
Mike Frysinger54133972021-03-01 21:38:08 -05001101 if restrict_includes:
1102 msg = self._CheckLocalPath(name)
1103 if msg:
1104 raise ManifestInvalidPathError(
1105 '<include> invalid "name": %s: %s' % (name, msg))
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001106 include_groups = ''
1107 if parent_groups:
1108 include_groups = parent_groups
1109 if node.hasAttribute('groups'):
1110 include_groups = node.getAttribute('groups') + ',' + include_groups
David Pursehousec1b86a22012-11-14 11:36:51 +09001111 fp = os.path.join(include_root, name)
1112 if not os.path.isfile(fp):
Mike Frysinger54133972021-03-01 21:38:08 -05001113 raise ManifestParseError("include [%s/]%s doesn't exist or isn't a file"
1114 % (include_root, name))
David Pursehousec1b86a22012-11-14 11:36:51 +09001115 try:
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001116 nodes.extend(self._ParseManifestXml(fp, include_root, include_groups))
David Pursehousec1b86a22012-11-14 11:36:51 +09001117 # should isolate this to the exact exception, but that's
1118 # tricky. actual parsing implementation may vary.
Mike Frysinger54133972021-03-01 21:38:08 -05001119 except (KeyboardInterrupt, RuntimeError, SystemExit, ManifestParseError):
David Pursehousec1b86a22012-11-14 11:36:51 +09001120 raise
1121 except Exception as e:
1122 raise ManifestParseError(
Mike Frysingerec558df2019-07-05 01:38:05 -04001123 "failed parsing included manifest %s: %s" % (name, e))
David Pursehousec1b86a22012-11-14 11:36:51 +09001124 else:
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001125 if parent_groups and node.nodeName == 'project':
1126 nodeGroups = parent_groups
1127 if node.hasAttribute('groups'):
1128 nodeGroups = node.getAttribute('groups') + ',' + nodeGroups
1129 node.setAttribute('groups', nodeGroups)
David Pursehousec1b86a22012-11-14 11:36:51 +09001130 nodes.append(node)
Colin Cross23acdd32012-04-21 00:33:54 -07001131 return nodes
Brian Harring26448742011-04-28 05:04:41 -07001132
Colin Cross23acdd32012-04-21 00:33:54 -07001133 def _ParseManifest(self, node_list):
1134 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001135 if node.nodeName == 'remote':
1136 remote = self._ParseRemote(node)
David Pursehouse717ece92012-11-13 08:49:16 +09001137 if remote:
1138 if remote.name in self._remotes:
1139 if remote != self._remotes[remote.name]:
1140 raise ManifestParseError(
1141 'remote %s already exists with different attributes' %
1142 (remote.name))
1143 else:
1144 self._remotes[remote.name] = remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001145
Colin Cross23acdd32012-04-21 00:33:54 -07001146 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001147 if node.nodeName == 'default':
Julien Campergue74879922013-10-09 14:38:46 +02001148 new_default = self._ParseDefault(node)
Jack Neusb8c84482021-06-15 14:28:30 +00001149 emptyDefault = not node.hasAttributes() and not node.hasChildNodes()
Julien Campergue74879922013-10-09 14:38:46 +02001150 if self._default is None:
1151 self._default = new_default
Jack Neusb8c84482021-06-15 14:28:30 +00001152 elif not emptyDefault and new_default != self._default:
David Pursehouse37128b62013-10-15 10:48:40 +09001153 raise ManifestParseError('duplicate default in %s' %
1154 (self.manifestFile))
Julien Campergue74879922013-10-09 14:38:46 +02001155
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001156 if self._default is None:
1157 self._default = _Default()
1158
LaMont Jonescc879a92021-11-18 22:40:18 +00001159 submanifest_paths = set()
1160 for node in itertools.chain(*node_list):
1161 if node.nodeName == 'submanifest':
1162 submanifest = self._ParseSubmanifest(node)
1163 if submanifest:
1164 if submanifest.name in self._submanifests:
1165 if submanifest != self._submanifests[submanifest.name]:
1166 raise ManifestParseError(
1167 'submanifest %s already exists with different attributes' %
1168 (submanifest.name))
1169 else:
1170 self._submanifests[submanifest.name] = submanifest
1171 submanifest_paths.add(submanifest.relpath)
1172
Colin Cross23acdd32012-04-21 00:33:54 -07001173 for node in itertools.chain(*node_list):
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001174 if node.nodeName == 'notice':
1175 if self._notice is not None:
Doug Anderson37282b42011-03-04 11:54:18 -08001176 raise ManifestParseError(
1177 'duplicate notice in %s' %
1178 (self.manifestFile))
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001179 self._notice = self._ParseNotice(node)
1180
Colin Cross23acdd32012-04-21 00:33:54 -07001181 for node in itertools.chain(*node_list):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001182 if node.nodeName == 'manifest-server':
1183 url = self._reqatt(node, 'url')
1184 if self._manifest_server is not None:
David Pursehousec1b86a22012-11-14 11:36:51 +09001185 raise ManifestParseError(
1186 'duplicate manifest-server in %s' %
1187 (self.manifestFile))
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001188 self._manifest_server = url
1189
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001190 def recursively_add_projects(project):
David James8d201162013-10-11 17:03:19 -07001191 projects = self._projects.setdefault(project.name, [])
1192 if project.relpath is None:
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001193 raise ManifestParseError(
David James8d201162013-10-11 17:03:19 -07001194 'missing path for %s in %s' %
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001195 (project.name, self.manifestFile))
David James8d201162013-10-11 17:03:19 -07001196 if project.relpath in self._paths:
1197 raise ManifestParseError(
1198 'duplicate path %s in %s' %
1199 (project.relpath, self.manifestFile))
LaMont Jonescc879a92021-11-18 22:40:18 +00001200 for tree in submanifest_paths:
1201 if project.relpath.startswith(tree):
1202 raise ManifestParseError(
1203 'project %s conflicts with submanifest path %s' %
1204 (project.relpath, tree))
David James8d201162013-10-11 17:03:19 -07001205 self._paths[project.relpath] = project
1206 projects.append(project)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001207 for subproject in project.subprojects:
1208 recursively_add_projects(subproject)
1209
Jack Neusa84f43a2021-09-21 22:23:55 +00001210 repo_hooks_project = None
1211 enabled_repo_hooks = None
Colin Cross23acdd32012-04-21 00:33:54 -07001212 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001213 if node.nodeName == 'project':
1214 project = self._ParseProject(node)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001215 recursively_add_projects(project)
Josh Triplett884a3872014-06-12 14:57:29 -07001216 if node.nodeName == 'extend-project':
1217 name = self._reqatt(node, 'name')
1218
1219 if name not in self._projects:
1220 raise ManifestParseError('extend-project element specifies non-existent '
1221 'project: %s' % name)
1222
1223 path = node.getAttribute('path')
Michael Kelly37c21c22020-06-13 02:10:40 -07001224 dest_path = node.getAttribute('dest-path')
Josh Triplett884a3872014-06-12 14:57:29 -07001225 groups = node.getAttribute('groups')
1226 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -05001227 groups = self._ParseList(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -07001228 revision = node.getAttribute('revision')
LaMont Jonescc879a92021-11-18 22:40:18 +00001229 remote_name = node.getAttribute('remote')
1230 if not remote_name:
1231 remote = self._default.remote
1232 else:
Kyunam Jobd0aae92020-02-04 11:38:53 +09001233 remote = self._get_remote(node)
Josh Triplett884a3872014-06-12 14:57:29 -07001234
Michael Kelly37c21c22020-06-13 02:10:40 -07001235 named_projects = self._projects[name]
1236 if dest_path and not path and len(named_projects) > 1:
1237 raise ManifestParseError('extend-project cannot use dest-path when '
1238 'matching multiple projects: %s' % name)
Josh Triplett884a3872014-06-12 14:57:29 -07001239 for p in self._projects[name]:
1240 if path and p.relpath != path:
1241 continue
1242 if groups:
1243 p.groups.extend(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -07001244 if revision:
Michael Kelly2f3c3312020-07-21 19:40:38 -07001245 p.SetRevision(revision)
1246
LaMont Jonescc879a92021-11-18 22:40:18 +00001247 if remote_name:
Kyunam Jobd0aae92020-02-04 11:38:53 +09001248 p.remote = remote.ToRemoteSpec(name)
Michael Kelly2f3c3312020-07-21 19:40:38 -07001249
Michael Kelly37c21c22020-06-13 02:10:40 -07001250 if dest_path:
1251 del self._paths[p.relpath]
LaMont Jonescc879a92021-11-18 22:40:18 +00001252 relpath, worktree, gitdir, objdir, _ = self.GetProjectPaths(
1253 name, dest_path, remote.name)
Michael Kelly37c21c22020-06-13 02:10:40 -07001254 p.UpdatePaths(relpath, worktree, gitdir, objdir)
1255 self._paths[p.relpath] = p
1256
Doug Anderson37282b42011-03-04 11:54:18 -08001257 if node.nodeName == 'repo-hooks':
Doug Anderson37282b42011-03-04 11:54:18 -08001258 # Only one project can be the hooks project
Jack Neusa84f43a2021-09-21 22:23:55 +00001259 if repo_hooks_project is not None:
Doug Anderson37282b42011-03-04 11:54:18 -08001260 raise ManifestParseError(
1261 'duplicate repo-hooks in %s' %
1262 (self.manifestFile))
1263
Jack Neusa84f43a2021-09-21 22:23:55 +00001264 # Get the name of the project and the (space-separated) list of enabled.
1265 repo_hooks_project = self._reqatt(node, 'in-project')
1266 enabled_repo_hooks = self._ParseList(self._reqatt(node, 'enabled-list'))
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001267 if node.nodeName == 'superproject':
1268 name = self._reqatt(node, 'name')
1269 # There can only be one superproject.
LaMont Jonesd56e2eb2022-04-07 18:14:46 +00001270 if self._superproject:
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001271 raise ManifestParseError(
1272 'duplicate superproject in %s' %
1273 (self.manifestFile))
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001274 remote_name = node.getAttribute('remote')
1275 if not remote_name:
1276 remote = self._default.remote
1277 else:
1278 remote = self._get_remote(node)
1279 if remote is None:
1280 raise ManifestParseError("no remote for superproject %s within %s" %
1281 (name, self.manifestFile))
Xin Lie0b16a22021-09-26 23:20:32 -07001282 revision = node.getAttribute('revision') or remote.revision
1283 if not revision:
1284 revision = self._default.revisionExpr
1285 if not revision:
1286 raise ManifestParseError('no revision for superproject %s within %s' %
1287 (name, self.manifestFile))
LaMont Jonesd56e2eb2022-04-07 18:14:46 +00001288 self._superproject = Superproject(self,
1289 name=name,
1290 remote=remote.ToRemoteSpec(name),
1291 revision=revision)
Raman Tenneti1c3f57e2021-05-04 12:32:13 -07001292 if node.nodeName == 'contactinfo':
1293 bugurl = self._reqatt(node, 'bugurl')
1294 # This element can be repeated, later entries will clobber earlier ones.
Raman Tenneti993af5e2021-05-12 12:00:31 -07001295 self._contactinfo = ContactInfo(bugurl)
1296
Colin Cross23acdd32012-04-21 00:33:54 -07001297 if node.nodeName == 'remove-project':
1298 name = self._reqatt(node, 'name')
David Jamesb8433df2014-01-30 10:11:17 -08001299
Michael Kelly06da9982021-06-30 01:58:28 -07001300 if name in self._projects:
1301 for p in self._projects[name]:
1302 del self._paths[p.relpath]
1303 del self._projects[name]
1304
1305 # If the manifest removes the hooks project, treat it as if it deleted
1306 # the repo-hooks element too.
Jack Neusa84f43a2021-09-21 22:23:55 +00001307 if repo_hooks_project == name:
1308 repo_hooks_project = None
Michael Kelly06da9982021-06-30 01:58:28 -07001309 elif not XmlBool(node, 'optional', False):
David Pursehousef9107482012-11-16 19:12:32 +09001310 raise ManifestParseError('remove-project element specifies non-existent '
1311 'project: %s' % name)
Colin Cross23acdd32012-04-21 00:33:54 -07001312
Jack Neusa84f43a2021-09-21 22:23:55 +00001313 # Store repo hooks project information.
1314 if repo_hooks_project:
1315 # Store a reference to the Project.
1316 try:
1317 repo_hooks_projects = self._projects[repo_hooks_project]
1318 except KeyError:
1319 raise ManifestParseError(
1320 'project %s not found for repo-hooks' %
1321 (repo_hooks_project))
1322
1323 if len(repo_hooks_projects) != 1:
1324 raise ManifestParseError(
1325 'internal error parsing repo-hooks in %s' %
1326 (self.manifestFile))
1327 self._repo_hooks_project = repo_hooks_projects[0]
1328 # Store the enabled hooks in the Project object.
1329 self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
1330
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001331 def _AddMetaProjectMirror(self, m):
1332 name = None
1333 m_url = m.GetRemote(m.remote.name).url
1334 if m_url.endswith('/.git'):
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301335 raise ManifestParseError('refusing to mirror %s' % m_url)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001336
1337 if self._default and self._default.remote:
Conley Owensceea3682011-10-20 10:45:47 -07001338 url = self._default.remote.resolvedFetchUrl
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001339 if not url.endswith('/'):
1340 url += '/'
1341 if m_url.startswith(url):
1342 remote = self._default.remote
1343 name = m_url[len(url):]
1344
1345 if name is None:
1346 s = m_url.rindex('/') + 1
Conley Owensdb728cd2011-09-26 16:34:01 -07001347 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Shawn O. Pearcef35b2d92012-08-02 11:46:22 -07001348 remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001349 name = m_url[s:]
1350
1351 if name.endswith('.git'):
1352 name = name[:-4]
1353
1354 if name not in self._projects:
1355 m.PreSync()
1356 gitdir = os.path.join(self.topdir, '%s.git' % name)
David Pursehousee5913ae2020-02-12 13:56:59 +09001357 project = Project(manifest=self,
1358 name=name,
1359 remote=remote.ToRemoteSpec(name),
1360 gitdir=gitdir,
1361 objdir=gitdir,
1362 worktree=None,
1363 relpath=name or None,
1364 revisionExpr=m.revisionExpr,
1365 revisionId=None)
David James8d201162013-10-11 17:03:19 -07001366 self._projects[project.name] = [project]
Kwanhong Leeccd218c2014-02-17 13:07:32 +09001367 self._paths[project.relpath] = project
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001368
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001369 def _ParseRemote(self, node):
1370 """
1371 reads a <remote> element from the manifest file
1372 """
1373 name = self._reqatt(node, 'name')
Yestin Sunb292b982012-07-02 07:32:50 -07001374 alias = node.getAttribute('alias')
1375 if alias == '':
1376 alias = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001377 fetch = self._reqatt(node, 'fetch')
Steve Raed6480452016-08-10 15:00:00 -07001378 pushUrl = node.getAttribute('pushurl')
1379 if pushUrl == '':
1380 pushUrl = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001381 review = node.getAttribute('review')
Shawn O. Pearceae6e0942008-11-06 10:25:35 -08001382 if review == '':
1383 review = None
Anthony King36ea2fb2014-05-06 11:54:01 +01001384 revision = node.getAttribute('revision')
1385 if revision == '':
1386 revision = None
Conley Owensdb728cd2011-09-26 16:34:01 -07001387 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Jack Neus6ea0cae2021-07-20 20:52:33 +00001388
1389 remote = _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
1390
1391 for n in node.childNodes:
1392 if n.nodeName == 'annotation':
1393 self._ParseAnnotation(remote, n)
1394
1395 return remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001396
1397 def _ParseDefault(self, node):
1398 """
1399 reads a <default> element from the manifest file
1400 """
1401 d = _Default()
1402 d.remote = self._get_remote(node)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001403 d.revisionExpr = node.getAttribute('revision')
1404 if d.revisionExpr == '':
1405 d.revisionExpr = None
Anatol Pomazau79770d22012-04-20 14:41:59 -07001406
Bryan Jacobsf609f912013-05-06 13:36:24 -04001407 d.destBranchExpr = node.getAttribute('dest-branch') or None
Nasser Grainawida403412018-05-04 12:53:29 -06001408 d.upstreamExpr = node.getAttribute('upstream') or None
Bryan Jacobsf609f912013-05-06 13:36:24 -04001409
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001410 d.sync_j = XmlInt(node, 'sync-j', 1)
1411 if d.sync_j <= 0:
1412 raise ManifestParseError('%s: sync-j must be greater than 0, not "%s"' %
1413 (self.manifestFile, d.sync_j))
Anatol Pomazau79770d22012-04-20 14:41:59 -07001414
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001415 d.sync_c = XmlBool(node, 'sync-c', False)
1416 d.sync_s = XmlBool(node, 'sync-s', False)
1417 d.sync_tags = XmlBool(node, 'sync-tags', True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001418 return d
1419
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001420 def _ParseNotice(self, node):
1421 """
1422 reads a <notice> element from the manifest file
1423
1424 The <notice> element is distinct from other tags in the XML in that the
1425 data is conveyed between the start and end tag (it's not an empty-element
1426 tag).
1427
1428 The white space (carriage returns, indentation) for the notice element is
1429 relevant and is parsed in a way that is based on how python docstrings work.
1430 In fact, the code is remarkably similar to here:
1431 http://www.python.org/dev/peps/pep-0257/
1432 """
1433 # Get the data out of the node...
1434 notice = node.childNodes[0].data
1435
1436 # Figure out minimum indentation, skipping the first line (the same line
1437 # as the <notice> tag)...
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301438 minIndent = sys.maxsize
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001439 lines = notice.splitlines()
1440 for line in lines[1:]:
1441 lstrippedLine = line.lstrip()
1442 if lstrippedLine:
1443 indent = len(line) - len(lstrippedLine)
1444 minIndent = min(indent, minIndent)
1445
1446 # Strip leading / trailing blank lines and also indentation.
1447 cleanLines = [lines[0].strip()]
1448 for line in lines[1:]:
1449 cleanLines.append(line[minIndent:].rstrip())
1450
1451 # Clear completely blank lines from front and back...
1452 while cleanLines and not cleanLines[0]:
1453 del cleanLines[0]
1454 while cleanLines and not cleanLines[-1]:
1455 del cleanLines[-1]
1456
1457 return '\n'.join(cleanLines)
1458
LaMont Jonescc879a92021-11-18 22:40:18 +00001459 def _ParseSubmanifest(self, node):
1460 """Reads a <submanifest> element from the manifest file."""
1461 name = self._reqatt(node, 'name')
1462 remote = node.getAttribute('remote')
1463 if remote == '':
1464 remote = None
1465 project = node.getAttribute('project')
1466 if project == '':
1467 project = None
1468 revision = node.getAttribute('revision')
1469 if revision == '':
1470 revision = None
1471 manifestName = node.getAttribute('manifest-name')
1472 if manifestName == '':
1473 manifestName = None
1474 groups = ''
1475 if node.hasAttribute('groups'):
1476 groups = node.getAttribute('groups')
1477 groups = self._ParseList(groups)
1478 path = node.getAttribute('path')
1479 if path == '':
1480 path = None
1481 if revision:
1482 msg = self._CheckLocalPath(revision.split('/')[-1])
1483 if msg:
1484 raise ManifestInvalidPathError(
1485 '<submanifest> invalid "revision": %s: %s' % (revision, msg))
1486 else:
1487 msg = self._CheckLocalPath(name)
1488 if msg:
1489 raise ManifestInvalidPathError(
1490 '<submanifest> invalid "name": %s: %s' % (name, msg))
1491 else:
1492 msg = self._CheckLocalPath(path)
1493 if msg:
1494 raise ManifestInvalidPathError(
1495 '<submanifest> invalid "path": %s: %s' % (path, msg))
1496
1497 submanifest = _XmlSubmanifest(name, remote, project, revision, manifestName,
1498 groups, path, self)
1499
1500 for n in node.childNodes:
1501 if n.nodeName == 'annotation':
1502 self._ParseAnnotation(submanifest, n)
1503
1504 return submanifest
1505
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001506 def _JoinName(self, parent_name, name):
1507 return os.path.join(parent_name, name)
1508
1509 def _UnjoinName(self, parent_name, name):
1510 return os.path.relpath(name, parent_name)
1511
David Pursehousee5913ae2020-02-12 13:56:59 +09001512 def _ParseProject(self, node, parent=None, **extra_proj_attrs):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001513 """
1514 reads a <project> element from the manifest file
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001515 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001516 name = self._reqatt(node, 'name')
Mike Frysingera29424e2021-02-25 21:53:49 -05001517 msg = self._CheckLocalPath(name, dir_ok=True)
1518 if msg:
1519 raise ManifestInvalidPathError(
1520 '<project> invalid "name": %s: %s' % (name, msg))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001521 if parent:
1522 name = self._JoinName(parent.name, name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001523
1524 remote = self._get_remote(node)
1525 if remote is None:
1526 remote = self._default.remote
1527 if remote is None:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301528 raise ManifestParseError("no remote for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001529 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001530
Anthony King36ea2fb2014-05-06 11:54:01 +01001531 revisionExpr = node.getAttribute('revision') or remote.revision
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001532 if not revisionExpr:
1533 revisionExpr = self._default.revisionExpr
1534 if not revisionExpr:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301535 raise ManifestParseError("no revision for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001536 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001537
1538 path = node.getAttribute('path')
1539 if not path:
1540 path = name
Mike Frysingera29424e2021-02-25 21:53:49 -05001541 else:
Mike Frysinger0458faa2021-03-10 23:35:44 -05001542 # NB: The "." project is handled specially in Project.Sync_LocalHalf.
1543 msg = self._CheckLocalPath(path, dir_ok=True, cwd_dot_ok=True)
Mike Frysingera29424e2021-02-25 21:53:49 -05001544 if msg:
1545 raise ManifestInvalidPathError(
1546 '<project> invalid "path": %s: %s' % (path, msg))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001547
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001548 rebase = XmlBool(node, 'rebase', True)
1549 sync_c = XmlBool(node, 'sync-c', False)
1550 sync_s = XmlBool(node, 'sync-s', self._default.sync_s)
1551 sync_tags = XmlBool(node, 'sync-tags', self._default.sync_tags)
Mike Pontillod3153822012-02-28 11:53:24 -08001552
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001553 clone_depth = XmlInt(node, 'clone-depth')
1554 if clone_depth is not None and clone_depth <= 0:
1555 raise ManifestParseError('%s: clone-depth must be greater than 0, not "%s"' %
1556 (self.manifestFile, clone_depth))
David Pursehouseede7f122012-11-27 22:25:30 +09001557
Bryan Jacobsf609f912013-05-06 13:36:24 -04001558 dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
1559
Nasser Grainawida403412018-05-04 12:53:29 -06001560 upstream = node.getAttribute('upstream') or self._default.upstreamExpr
Brian Harring14a66742012-09-28 20:21:57 -07001561
Conley Owens971de8e2012-04-16 10:36:08 -07001562 groups = ''
1563 if node.hasAttribute('groups'):
1564 groups = node.getAttribute('groups')
Mike Frysinger51e39d52020-12-04 05:32:06 -05001565 groups = self._ParseList(groups)
Brian Harring7da13142012-06-15 02:24:20 -07001566
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001567 if parent is None:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001568 relpath, worktree, gitdir, objdir, use_git_worktrees = \
LaMont Jonescc879a92021-11-18 22:40:18 +00001569 self.GetProjectPaths(name, path, remote.name)
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001570 else:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001571 use_git_worktrees = False
David James8d201162013-10-11 17:03:19 -07001572 relpath, worktree, gitdir, objdir = \
1573 self.GetSubprojectPaths(parent, name, path)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001574
1575 default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
1576 groups.extend(set(default_groups).difference(groups))
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001577
Scott Fandb83b1b2013-02-28 09:34:14 +08001578 if self.IsMirror and node.hasAttribute('force-path'):
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001579 if XmlBool(node, 'force-path', False):
Scott Fandb83b1b2013-02-28 09:34:14 +08001580 gitdir = os.path.join(self.topdir, '%s.git' % path)
1581
David Pursehousee5913ae2020-02-12 13:56:59 +09001582 project = Project(manifest=self,
1583 name=name,
1584 remote=remote.ToRemoteSpec(name),
1585 gitdir=gitdir,
1586 objdir=objdir,
1587 worktree=worktree,
1588 relpath=relpath,
1589 revisionExpr=revisionExpr,
1590 revisionId=None,
1591 rebase=rebase,
1592 groups=groups,
1593 sync_c=sync_c,
1594 sync_s=sync_s,
1595 sync_tags=sync_tags,
1596 clone_depth=clone_depth,
1597 upstream=upstream,
1598 parent=parent,
1599 dest_branch=dest_branch,
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001600 use_git_worktrees=use_git_worktrees,
Simran Basib9a1b732015-08-20 12:19:28 -07001601 **extra_proj_attrs)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001602
1603 for n in node.childNodes:
Shawn O. Pearce242b5262009-05-19 13:00:29 -07001604 if n.nodeName == 'copyfile':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001605 self._ParseCopyFile(project, n)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001606 if n.nodeName == 'linkfile':
1607 self._ParseLinkFile(project, n)
James W. Mills24c13082012-04-12 15:04:13 -05001608 if n.nodeName == 'annotation':
1609 self._ParseAnnotation(project, n)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001610 if n.nodeName == 'project':
David Pursehousee5913ae2020-02-12 13:56:59 +09001611 project.subprojects.append(self._ParseProject(n, parent=project))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001612
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001613 return project
1614
LaMont Jonescc879a92021-11-18 22:40:18 +00001615 def GetProjectPaths(self, name, path, remote):
1616 """Return the paths for a project.
1617
1618 Args:
1619 name: a string, the name of the project.
1620 path: a string, the path of the project.
1621 remote: a string, the remote.name of the project.
1622 """
Mike Frysingercebf2272020-05-26 01:02:29 -04001623 # The manifest entries might have trailing slashes. Normalize them to avoid
1624 # unexpected filesystem behavior since we do string concatenation below.
1625 path = path.rstrip('/')
1626 name = name.rstrip('/')
LaMont Jonescc879a92021-11-18 22:40:18 +00001627 remote = remote.rstrip('/')
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001628 use_git_worktrees = False
LaMont Jonescc879a92021-11-18 22:40:18 +00001629 use_remote_name = bool(self._outer_client._submanifests)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001630 relpath = path
1631 if self.IsMirror:
1632 worktree = None
1633 gitdir = os.path.join(self.topdir, '%s.git' % name)
David James8d201162013-10-11 17:03:19 -07001634 objdir = gitdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001635 else:
LaMont Jonescc879a92021-11-18 22:40:18 +00001636 if use_remote_name:
1637 namepath = os.path.join(remote, f'{name}.git')
1638 else:
1639 namepath = f'{name}.git'
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001640 worktree = os.path.join(self.topdir, path).replace('\\', '/')
LaMont Jonescc879a92021-11-18 22:40:18 +00001641 gitdir = os.path.join(self.subdir, 'projects', '%s.git' % path)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001642 # We allow people to mix git worktrees & non-git worktrees for now.
1643 # This allows for in situ migration of repo clients.
1644 if os.path.exists(gitdir) or not self.UseGitWorktrees:
LaMont Jonescc879a92021-11-18 22:40:18 +00001645 objdir = os.path.join(self.subdir, 'project-objects', namepath)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001646 else:
1647 use_git_worktrees = True
LaMont Jonescc879a92021-11-18 22:40:18 +00001648 gitdir = os.path.join(self.repodir, 'worktrees', namepath)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001649 objdir = gitdir
1650 return relpath, worktree, gitdir, objdir, use_git_worktrees
David James8d201162013-10-11 17:03:19 -07001651
LaMont Jonescc879a92021-11-18 22:40:18 +00001652 def GetProjectsWithName(self, name, all_manifests=False):
1653 """All projects with |name|.
1654
1655 Args:
1656 name: a string, the name of the project.
1657 all_manifests: a boolean, if True, then all manifests are searched. If
1658 False, then only this manifest is searched.
1659 """
1660 if all_manifests:
1661 return list(itertools.chain.from_iterable(
1662 x._projects.get(name, []) for x in self.all_manifests))
David James8d201162013-10-11 17:03:19 -07001663 return self._projects.get(name, [])
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001664
1665 def GetSubprojectName(self, parent, submodule_path):
1666 return os.path.join(parent.name, submodule_path)
1667
1668 def _JoinRelpath(self, parent_relpath, relpath):
1669 return os.path.join(parent_relpath, relpath)
1670
1671 def _UnjoinRelpath(self, parent_relpath, relpath):
1672 return os.path.relpath(relpath, parent_relpath)
1673
David James8d201162013-10-11 17:03:19 -07001674 def GetSubprojectPaths(self, parent, name, path):
Mike Frysingercebf2272020-05-26 01:02:29 -04001675 # The manifest entries might have trailing slashes. Normalize them to avoid
1676 # unexpected filesystem behavior since we do string concatenation below.
1677 path = path.rstrip('/')
1678 name = name.rstrip('/')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001679 relpath = self._JoinRelpath(parent.relpath, path)
1680 gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
David James8d201162013-10-11 17:03:19 -07001681 objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001682 if self.IsMirror:
1683 worktree = None
1684 else:
1685 worktree = os.path.join(parent.worktree, path).replace('\\', '/')
David James8d201162013-10-11 17:03:19 -07001686 return relpath, worktree, gitdir, objdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001687
Mike Frysinger04122b72019-07-31 23:32:58 -04001688 @staticmethod
Mike Frysingera00c5f42021-02-25 18:26:31 -05001689 def _CheckLocalPath(path, dir_ok=False, cwd_dot_ok=False):
1690 """Verify |path| is reasonable for use in filesystem paths.
1691
Mike Frysingera29424e2021-02-25 21:53:49 -05001692 Used with <copyfile> & <linkfile> & <project> elements.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001693
1694 This only validates the |path| in isolation: it does not check against the
1695 current filesystem state. Thus it is suitable as a first-past in a parser.
1696
1697 It enforces a number of constraints:
1698 * No empty paths.
1699 * No "~" in paths.
1700 * No Unicode codepoints that filesystems might elide when normalizing.
1701 * No relative path components like "." or "..".
1702 * No absolute paths.
1703 * No ".git" or ".repo*" path components.
1704
1705 Args:
1706 path: The path name to validate.
1707 dir_ok: Whether |path| may force a directory (e.g. end in a /).
1708 cwd_dot_ok: Whether |path| may be just ".".
1709
1710 Returns:
1711 None if |path| is OK, a failure message otherwise.
1712 """
1713 if not path:
1714 return 'empty paths not allowed'
1715
Mike Frysinger04122b72019-07-31 23:32:58 -04001716 if '~' in path:
1717 return '~ not allowed (due to 8.3 filenames on Windows filesystems)'
1718
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001719 path_codepoints = set(path)
1720
Mike Frysinger04122b72019-07-31 23:32:58 -04001721 # Some filesystems (like Apple's HFS+) try to normalize Unicode codepoints
1722 # which means there are alternative names for ".git". Reject paths with
1723 # these in it as there shouldn't be any reasonable need for them here.
1724 # The set of codepoints here was cribbed from jgit's implementation:
1725 # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
1726 BAD_CODEPOINTS = {
1727 u'\u200C', # ZERO WIDTH NON-JOINER
1728 u'\u200D', # ZERO WIDTH JOINER
1729 u'\u200E', # LEFT-TO-RIGHT MARK
1730 u'\u200F', # RIGHT-TO-LEFT MARK
1731 u'\u202A', # LEFT-TO-RIGHT EMBEDDING
1732 u'\u202B', # RIGHT-TO-LEFT EMBEDDING
1733 u'\u202C', # POP DIRECTIONAL FORMATTING
1734 u'\u202D', # LEFT-TO-RIGHT OVERRIDE
1735 u'\u202E', # RIGHT-TO-LEFT OVERRIDE
1736 u'\u206A', # INHIBIT SYMMETRIC SWAPPING
1737 u'\u206B', # ACTIVATE SYMMETRIC SWAPPING
1738 u'\u206C', # INHIBIT ARABIC FORM SHAPING
1739 u'\u206D', # ACTIVATE ARABIC FORM SHAPING
1740 u'\u206E', # NATIONAL DIGIT SHAPES
1741 u'\u206F', # NOMINAL DIGIT SHAPES
1742 u'\uFEFF', # ZERO WIDTH NO-BREAK SPACE
1743 }
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001744 if BAD_CODEPOINTS & path_codepoints:
Mike Frysinger04122b72019-07-31 23:32:58 -04001745 # This message is more expansive than reality, but should be fine.
1746 return 'Unicode combining characters not allowed'
1747
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001748 # Reject newlines as there shouldn't be any legitmate use for them, they'll
1749 # be confusing to users, and they can easily break tools that expect to be
1750 # able to iterate over newline delimited lists. This even applies to our
1751 # own code like .repo/project.list.
1752 if {'\r', '\n'} & path_codepoints:
1753 return 'Newlines not allowed'
1754
Mike Frysinger04122b72019-07-31 23:32:58 -04001755 # Assume paths might be used on case-insensitive filesystems.
1756 path = path.lower()
1757
Mike Frysingerd9254592020-02-19 22:36:26 -05001758 # Split up the path by its components. We can't use os.path.sep exclusively
1759 # as some platforms (like Windows) will convert / to \ and that bypasses all
1760 # our constructed logic here. Especially since manifest authors only use
1761 # / in their paths.
1762 resep = re.compile(r'[/%s]' % re.escape(os.path.sep))
Mike Frysinger0458faa2021-03-10 23:35:44 -05001763 # Strip off trailing slashes as those only produce '' elements, and we use
1764 # parts to look for individual bad components.
1765 parts = resep.split(path.rstrip('/'))
Mike Frysingerd9254592020-02-19 22:36:26 -05001766
Mike Frysingerae625412020-02-10 17:10:03 -05001767 # Some people use src="." to create stable links to projects. Lets allow
1768 # that but reject all other uses of "." to keep things simple.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001769 if not cwd_dot_ok or parts != ['.']:
Mike Frysingerae625412020-02-10 17:10:03 -05001770 for part in set(parts):
1771 if part in {'.', '..', '.git'} or part.startswith('.repo'):
1772 return 'bad component: %s' % (part,)
Mike Frysinger04122b72019-07-31 23:32:58 -04001773
Mike Frysingera00c5f42021-02-25 18:26:31 -05001774 if not dir_ok and resep.match(path[-1]):
Mike Frysinger04122b72019-07-31 23:32:58 -04001775 return 'dirs not allowed'
1776
Mike Frysingerd9254592020-02-19 22:36:26 -05001777 # NB: The two abspath checks here are to handle platforms with multiple
1778 # filesystem path styles (e.g. Windows).
Mike Frysinger04122b72019-07-31 23:32:58 -04001779 norm = os.path.normpath(path)
Mike Frysingerd9254592020-02-19 22:36:26 -05001780 if (norm == '..' or
1781 (len(norm) >= 3 and norm.startswith('..') and resep.match(norm[0])) or
1782 os.path.isabs(norm) or
1783 norm.startswith('/')):
Mike Frysinger04122b72019-07-31 23:32:58 -04001784 return 'path cannot be outside'
1785
1786 @classmethod
1787 def _ValidateFilePaths(cls, element, src, dest):
1788 """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
1789
1790 We verify the path independent of any filesystem state as we won't have a
1791 checkout available to compare to. i.e. This is for parsing validation
1792 purposes only.
1793
1794 We'll do full/live sanity checking before we do the actual filesystem
1795 modifications in _CopyFile/_LinkFile/etc...
1796 """
1797 # |dest| is the file we write to or symlink we create.
1798 # It is relative to the top of the repo client checkout.
1799 msg = cls._CheckLocalPath(dest)
1800 if msg:
1801 raise ManifestInvalidPathError(
1802 '<%s> invalid "dest": %s: %s' % (element, dest, msg))
1803
1804 # |src| is the file we read from or path we point to for symlinks.
1805 # It is relative to the top of the git project checkout.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001806 is_linkfile = element == 'linkfile'
1807 msg = cls._CheckLocalPath(src, dir_ok=is_linkfile, cwd_dot_ok=is_linkfile)
Mike Frysinger04122b72019-07-31 23:32:58 -04001808 if msg:
1809 raise ManifestInvalidPathError(
1810 '<%s> invalid "src": %s: %s' % (element, src, msg))
1811
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001812 def _ParseCopyFile(self, project, node):
1813 src = self._reqatt(node, 'src')
1814 dest = self._reqatt(node, 'dest')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001815 if not self.IsMirror:
1816 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001817 # dest is relative to the top of the tree.
1818 # We only validate paths if we actually plan to process them.
1819 self._ValidateFilePaths('copyfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001820 project.AddCopyFile(src, dest, self.topdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001821
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001822 def _ParseLinkFile(self, project, node):
1823 src = self._reqatt(node, 'src')
1824 dest = self._reqatt(node, 'dest')
1825 if not self.IsMirror:
1826 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001827 # dest is relative to the top of the tree.
1828 # We only validate paths if we actually plan to process them.
1829 self._ValidateFilePaths('linkfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001830 project.AddLinkFile(src, dest, self.topdir)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001831
Jack Neus6ea0cae2021-07-20 20:52:33 +00001832 def _ParseAnnotation(self, element, node):
James W. Mills24c13082012-04-12 15:04:13 -05001833 name = self._reqatt(node, 'name')
1834 value = self._reqatt(node, 'value')
1835 try:
1836 keep = self._reqatt(node, 'keep').lower()
1837 except ManifestParseError:
1838 keep = "true"
1839 if keep != "true" and keep != "false":
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301840 raise ManifestParseError('optional "keep" attribute must be '
David Pursehouseabdf7502020-02-12 14:58:39 +09001841 '"true" or "false"')
Jack Neus6ea0cae2021-07-20 20:52:33 +00001842 element.AddAnnotation(name, value, keep)
James W. Mills24c13082012-04-12 15:04:13 -05001843
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001844 def _get_remote(self, node):
1845 name = node.getAttribute('remote')
1846 if not name:
1847 return None
1848
1849 v = self._remotes.get(name)
1850 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301851 raise ManifestParseError("remote %s not defined in %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001852 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001853 return v
1854
1855 def _reqatt(self, node, attname):
1856 """
1857 reads a required attribute from the node.
1858 """
1859 v = node.getAttribute(attname)
1860 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301861 raise ManifestParseError("no %s in <%s> within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001862 (attname, node.nodeName, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001863 return v
Julien Camperguedd654222014-01-09 16:21:37 +01001864
1865 def projectsDiff(self, manifest):
1866 """return the projects differences between two manifests.
1867
1868 The diff will be from self to given manifest.
1869
1870 """
1871 fromProjects = self.paths
1872 toProjects = manifest.paths
1873
Anthony King7446c592014-05-06 09:19:39 +01001874 fromKeys = sorted(fromProjects.keys())
1875 toKeys = sorted(toProjects.keys())
Julien Camperguedd654222014-01-09 16:21:37 +01001876
1877 diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
1878
1879 for proj in fromKeys:
David Pursehouseeeff3532020-02-12 11:24:10 +09001880 if proj not in toKeys:
Julien Camperguedd654222014-01-09 16:21:37 +01001881 diff['removed'].append(fromProjects[proj])
1882 else:
1883 fromProj = fromProjects[proj]
1884 toProj = toProjects[proj]
1885 try:
1886 fromRevId = fromProj.GetCommitRevisionId()
1887 toRevId = toProj.GetCommitRevisionId()
1888 except ManifestInvalidRevisionError:
1889 diff['unreachable'].append((fromProj, toProj))
1890 else:
1891 if fromRevId != toRevId:
1892 diff['changed'].append((fromProj, toProj))
1893 toKeys.remove(proj)
1894
1895 for proj in toKeys:
1896 diff['added'].append(toProjects[proj])
1897
1898 return diff
Simran Basib9a1b732015-08-20 12:19:28 -07001899
1900
1901class GitcManifest(XmlManifest):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001902 """Parser for GitC (git-in-the-cloud) manifests."""
Simran Basib9a1b732015-08-20 12:19:28 -07001903
David Pursehousee5913ae2020-02-12 13:56:59 +09001904 def _ParseProject(self, node, parent=None):
Simran Basib9a1b732015-08-20 12:19:28 -07001905 """Override _ParseProject and add support for GITC specific attributes."""
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001906 return super()._ParseProject(
Simran Basib9a1b732015-08-20 12:19:28 -07001907 node, parent=parent, old_revision=node.getAttribute('old-revision'))
1908
1909 def _output_manifest_project_extras(self, p, e):
1910 """Output GITC Specific Project attributes"""
1911 if p.old_revision:
Stefan Beller66851062016-06-17 16:40:08 -07001912 e.setAttribute('old-revision', str(p.old_revision))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001913
1914
1915class RepoClient(XmlManifest):
1916 """Manages a repo client checkout."""
1917
LaMont Jonescc879a92021-11-18 22:40:18 +00001918 def __init__(self, repodir, manifest_file=None, submanifest_path='', **kwargs):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001919 self.isGitcClient = False
LaMont Jonescc879a92021-11-18 22:40:18 +00001920 submanifest_path = submanifest_path or ''
1921 if submanifest_path:
1922 self._CheckLocalPath(submanifest_path)
1923 prefix = os.path.join(repodir, SUBMANIFEST_DIR, submanifest_path)
1924 else:
1925 prefix = repodir
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001926
LaMont Jonescc879a92021-11-18 22:40:18 +00001927 if os.path.exists(os.path.join(prefix, LOCAL_MANIFEST_NAME)):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001928 print('error: %s is not supported; put local manifests in `%s` instead' %
LaMont Jonescc879a92021-11-18 22:40:18 +00001929 (LOCAL_MANIFEST_NAME, os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME)),
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001930 file=sys.stderr)
1931 sys.exit(1)
1932
1933 if manifest_file is None:
LaMont Jonescc879a92021-11-18 22:40:18 +00001934 manifest_file = os.path.join(prefix, MANIFEST_FILE_NAME)
1935 local_manifests = os.path.abspath(os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME))
1936 super().__init__(repodir, manifest_file, local_manifests,
1937 submanifest_path=submanifest_path, **kwargs)
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001938
1939 # TODO: Completely separate manifest logic out of the client.
1940 self.manifest = self
1941
1942
1943class GitcClient(RepoClient, GitcManifest):
1944 """Manages a GitC client checkout."""
1945
1946 def __init__(self, repodir, gitc_client_name):
1947 """Initialize the GitcManifest object."""
1948 self.gitc_client_name = gitc_client_name
1949 self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
1950 gitc_client_name)
1951
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001952 super().__init__(repodir, os.path.join(self.gitc_client_dir, '.manifest'))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001953 self.isGitcClient = True