blob: 02f09db96053540cf538aaf928d381c83b193f3e [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
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070027import platform_utils
LaMont Jones9b72cf22022-03-29 21:54:22 +000028from project import (Annotation, RemoteSpec, Project, RepoProject,
29 ManifestProject)
Mike Frysinger04122b72019-07-31 23:32:58 -040030from error import (ManifestParseError, ManifestInvalidPathError,
31 ManifestInvalidRevisionError)
Raman Tenneti993af5e2021-05-12 12:00:31 -070032from wrapper import Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070033
34MANIFEST_FILE_NAME = 'manifest.xml'
Shawn O. Pearce5cc66792008-10-23 16:19:27 -070035LOCAL_MANIFEST_NAME = 'local_manifest.xml'
David Pursehouse2d5a0df2012-11-13 02:50:36 +090036LOCAL_MANIFESTS_DIR_NAME = 'local_manifests'
LaMont Jonescc879a92021-11-18 22:40:18 +000037SUBMANIFEST_DIR = 'submanifests'
38# Limit submanifests to an arbitrary depth for loop detection.
39MAX_SUBMANIFEST_DEPTH = 8
LaMont Jonesb308db12022-02-25 17:05:21 +000040# Add all projects from sub manifest into a group.
41SUBMANIFEST_GROUP_PREFIX = 'submanifest:'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070042
Raman Tenneti78f4dd32021-06-07 13:27:37 -070043# Add all projects from local manifest into a group.
44LOCAL_MANIFEST_GROUP_PREFIX = 'local:'
45
Raman Tenneti993af5e2021-05-12 12:00:31 -070046# ContactInfo has the self-registered bug url, supplied by the manifest authors.
47ContactInfo = collections.namedtuple('ContactInfo', 'bugurl')
48
Anthony Kingcb07ba72015-03-28 23:26:04 +000049# urljoin gets confused if the scheme is not known.
Joe Kilner6e310792016-10-27 15:53:53 -070050urllib.parse.uses_relative.extend([
51 'ssh',
52 'git',
53 'persistent-https',
54 'sso',
55 'rpc'])
56urllib.parse.uses_netloc.extend([
57 'ssh',
58 'git',
59 'persistent-https',
60 'sso',
61 'rpc'])
Conley Owensdb728cd2011-09-26 16:34:01 -070062
David Pursehouse819827a2020-02-12 15:20:19 +090063
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050064def XmlBool(node, attr, default=None):
65 """Determine boolean value of |node|'s |attr|.
66
67 Invalid values will issue a non-fatal warning.
68
69 Args:
70 node: XML node whose attributes we access.
71 attr: The attribute to access.
72 default: If the attribute is not set (value is empty), then use this.
73
74 Returns:
75 True if the attribute is a valid string representing true.
76 False if the attribute is a valid string representing false.
77 |default| otherwise.
78 """
79 value = node.getAttribute(attr)
80 s = value.lower()
81 if s == '':
82 return default
83 elif s in {'yes', 'true', '1'}:
84 return True
85 elif s in {'no', 'false', '0'}:
86 return False
87 else:
88 print('warning: manifest: %s="%s": ignoring invalid XML boolean' %
89 (attr, value), file=sys.stderr)
90 return default
91
92
93def XmlInt(node, attr, default=None):
94 """Determine integer value of |node|'s |attr|.
95
96 Args:
97 node: XML node whose attributes we access.
98 attr: The attribute to access.
99 default: If the attribute is not set (value is empty), then use this.
100
101 Returns:
102 The number if the attribute is a valid number.
103
104 Raises:
105 ManifestParseError: The number is invalid.
106 """
107 value = node.getAttribute(attr)
108 if not value:
109 return default
110
111 try:
112 return int(value)
113 except ValueError:
114 raise ManifestParseError('manifest: invalid %s="%s" integer' %
115 (attr, value))
116
117
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700118class _Default(object):
119 """Project defaults within the manifest."""
120
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700121 revisionExpr = None
Conley Owensb6a16e62013-09-25 15:06:09 -0700122 destBranchExpr = None
Nasser Grainawida403412018-05-04 12:53:29 -0600123 upstreamExpr = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700124 remote = None
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700125 sync_j = 1
Anatol Pomazau79770d22012-04-20 14:41:59 -0700126 sync_c = False
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800127 sync_s = False
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900128 sync_tags = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700129
Julien Campergue74879922013-10-09 14:38:46 +0200130 def __eq__(self, other):
Jack Neus5ba21202021-06-09 15:21:25 +0000131 if not isinstance(other, _Default):
132 return False
Julien Campergue74879922013-10-09 14:38:46 +0200133 return self.__dict__ == other.__dict__
134
135 def __ne__(self, other):
Jack Neus5ba21202021-06-09 15:21:25 +0000136 if not isinstance(other, _Default):
137 return True
Julien Campergue74879922013-10-09 14:38:46 +0200138 return self.__dict__ != other.__dict__
139
David Pursehouse819827a2020-02-12 15:20:19 +0900140
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700141class _XmlRemote(object):
142 def __init__(self,
143 name,
Yestin Sunb292b982012-07-02 07:32:50 -0700144 alias=None,
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700145 fetch=None,
Steve Raed6480452016-08-10 15:00:00 -0700146 pushUrl=None,
Conley Owensdb728cd2011-09-26 16:34:01 -0700147 manifestUrl=None,
Anthony King36ea2fb2014-05-06 11:54:01 +0100148 review=None,
Jonathan Nieder93719792015-03-17 11:29:58 -0700149 revision=None):
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700150 self.name = name
151 self.fetchUrl = fetch
Steve Raed6480452016-08-10 15:00:00 -0700152 self.pushUrl = pushUrl
Conley Owensdb728cd2011-09-26 16:34:01 -0700153 self.manifestUrl = manifestUrl
Yestin Sunb292b982012-07-02 07:32:50 -0700154 self.remoteAlias = alias
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700155 self.reviewUrl = review
Anthony King36ea2fb2014-05-06 11:54:01 +0100156 self.revision = revision
Conley Owensceea3682011-10-20 10:45:47 -0700157 self.resolvedFetchUrl = self._resolveFetchUrl()
Jack Neus6ea0cae2021-07-20 20:52:33 +0000158 self.annotations = []
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700159
David Pursehouse717ece92012-11-13 08:49:16 +0900160 def __eq__(self, other):
Jack Neus5ba21202021-06-09 15:21:25 +0000161 if not isinstance(other, _XmlRemote):
162 return False
Jack Neus6ea0cae2021-07-20 20:52:33 +0000163 return (sorted(self.annotations) == sorted(other.annotations) and
164 self.name == other.name and self.fetchUrl == other.fetchUrl and
165 self.pushUrl == other.pushUrl and self.remoteAlias == other.remoteAlias
166 and self.reviewUrl == other.reviewUrl and self.revision == other.revision)
David Pursehouse717ece92012-11-13 08:49:16 +0900167
168 def __ne__(self, other):
Jack Neus6ea0cae2021-07-20 20:52:33 +0000169 return not self.__eq__(other)
David Pursehouse717ece92012-11-13 08:49:16 +0900170
Conley Owensceea3682011-10-20 10:45:47 -0700171 def _resolveFetchUrl(self):
Jack Neus5ba21202021-06-09 15:21:25 +0000172 if self.fetchUrl is None:
173 return ''
Conley Owensceea3682011-10-20 10:45:47 -0700174 url = self.fetchUrl.rstrip('/')
Conley Owensdb728cd2011-09-26 16:34:01 -0700175 manifestUrl = self.manifestUrl.rstrip('/')
Conley Owens2d0f5082014-01-31 15:03:51 -0800176 # urljoin will gets confused over quite a few things. The ones we care
177 # about here are:
178 # * no scheme in the base url, like <hostname:port>
Anthony Kingcb07ba72015-03-28 23:26:04 +0000179 # We handle no scheme by replacing it with an obscure protocol, gopher
180 # and then replacing it with the original when we are done.
181
Conley Owensdb728cd2011-09-26 16:34:01 -0700182 if manifestUrl.find(':') != manifestUrl.find('/') - 1:
Conley Owens4ccad752015-04-29 10:45:37 -0700183 url = urllib.parse.urljoin('gopher://' + manifestUrl, url)
184 url = re.sub(r'^gopher://', '', url)
Anthony Kingcb07ba72015-03-28 23:26:04 +0000185 else:
186 url = urllib.parse.urljoin(manifestUrl, url)
Shawn Pearcea9f11b32013-01-02 15:40:48 -0800187 return url
Conley Owensceea3682011-10-20 10:45:47 -0700188
189 def ToRemoteSpec(self, projectName):
David Rileye0684ad2017-04-05 00:02:59 -0700190 fetchUrl = self.resolvedFetchUrl.rstrip('/')
191 url = fetchUrl + '/' + projectName
Yestin Sunb292b982012-07-02 07:32:50 -0700192 remoteName = self.name
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700193 if self.remoteAlias:
David Pursehouse37128b62013-10-15 10:48:40 +0900194 remoteName = self.remoteAlias
Dan Willemsen96c2d652016-04-06 16:03:54 -0700195 return RemoteSpec(remoteName,
196 url=url,
Steve Raed6480452016-08-10 15:00:00 -0700197 pushUrl=self.pushUrl,
Dan Willemsen96c2d652016-04-06 16:03:54 -0700198 review=self.reviewUrl,
David Rileye0684ad2017-04-05 00:02:59 -0700199 orig_name=self.name,
200 fetchUrl=self.fetchUrl)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700201
Jack Neus6ea0cae2021-07-20 20:52:33 +0000202 def AddAnnotation(self, name, value, keep):
203 self.annotations.append(Annotation(name, value, keep))
204
David Pursehouse819827a2020-02-12 15:20:19 +0900205
LaMont Jonescc879a92021-11-18 22:40:18 +0000206class _XmlSubmanifest:
207 """Manage the <submanifest> element specified in the manifest.
208
209 Attributes:
210 name: a string, the name for this submanifest.
211 remote: a string, the remote.name for this submanifest.
212 project: a string, the name of the manifest project.
213 revision: a string, the commitish.
214 manifestName: a string, the submanifest file name.
215 groups: a list of strings, the groups to add to all projects in the submanifest.
216 path: a string, the relative path for the submanifest checkout.
217 annotations: (derived) a list of annotations.
218 present: (derived) a boolean, whether the submanifest's manifest file is present.
219 """
220 def __init__(self,
221 name,
222 remote=None,
223 project=None,
224 revision=None,
225 manifestName=None,
226 groups=None,
227 path=None,
228 parent=None):
229 self.name = name
230 self.remote = remote
231 self.project = project
232 self.revision = revision
233 self.manifestName = manifestName
234 self.groups = groups
235 self.path = path
236 self.annotations = []
237 outer_client = parent._outer_client or parent
238 if self.remote and not self.project:
239 raise ManifestParseError(
240 f'Submanifest {name}: must specify project when remote is given.')
LaMont Jones5d3291d2022-03-23 19:03:02 +0000241 # Construct the absolute path to the manifest file using the parent's
242 # method, so that we can correctly create our repo_client.
243 manifestFile = parent.SubmanifestInfoDir(
244 os.path.join(parent.path_prefix, self.relpath),
245 os.path.join('manifests', manifestName or 'default.xml'))
LaMont Jones55ee3042022-04-06 17:10:21 +0000246 linkFile = parent.SubmanifestInfoDir(
247 os.path.join(parent.path_prefix, self.relpath), MANIFEST_FILE_NAME)
LaMont Jonescc879a92021-11-18 22:40:18 +0000248 rc = self.repo_client = RepoClient(
LaMont Jones55ee3042022-04-06 17:10:21 +0000249 parent.repodir, linkFile, parent_groups=','.join(groups) or '',
LaMont Jonescc879a92021-11-18 22:40:18 +0000250 submanifest_path=self.relpath, outer_client=outer_client)
251
LaMont Jones55ee3042022-04-06 17:10:21 +0000252 self.present = os.path.exists(manifestFile)
LaMont Jonescc879a92021-11-18 22:40:18 +0000253
254 def __eq__(self, other):
255 if not isinstance(other, _XmlSubmanifest):
256 return False
257 return (
258 self.name == other.name and
259 self.remote == other.remote and
260 self.project == other.project and
261 self.revision == other.revision and
262 self.manifestName == other.manifestName and
263 self.groups == other.groups and
264 self.path == other.path and
265 sorted(self.annotations) == sorted(other.annotations))
266
267 def __ne__(self, other):
268 return not self.__eq__(other)
269
270 def ToSubmanifestSpec(self, root):
271 """Return a SubmanifestSpec object, populating attributes"""
272 mp = root.manifestProject
273 remote = root.remotes[self.remote or root.default.remote.name]
274 # If a project was given, generate the url from the remote and project.
275 # If not, use this manifestProject's url.
276 if self.project:
277 manifestUrl = remote.ToRemoteSpec(self.project).url
278 else:
279 manifestUrl = mp.GetRemote(mp.remote.name).url
280 manifestName = self.manifestName or 'default.xml'
281 revision = self.revision or self.name
282 path = self.path or revision.split('/')[-1]
283 groups = self.groups or []
284
285 return SubmanifestSpec(self.name, manifestUrl, manifestName, revision, path,
286 groups)
287
288 @property
289 def relpath(self):
290 """The path of this submanifest relative to the parent manifest."""
291 revision = self.revision or self.name
292 return self.path or revision.split('/')[-1]
293
294 def GetGroupsStr(self):
295 """Returns the `groups` given for this submanifest."""
296 if self.groups:
297 return ','.join(self.groups)
298 return ''
299
300 def AddAnnotation(self, name, value, keep):
301 """Add annotations to the submanifest."""
302 self.annotations.append(Annotation(name, value, keep))
303
304
305class SubmanifestSpec:
306 """The submanifest element, with all fields expanded."""
307
308 def __init__(self,
309 name,
310 manifestUrl,
311 manifestName,
312 revision,
313 path,
314 groups):
315 self.name = name
316 self.manifestUrl = manifestUrl
317 self.manifestName = manifestName
318 self.revision = revision
319 self.path = path
320 self.groups = groups or []
321
322
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700323class XmlManifest(object):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700324 """manages the repo configuration file"""
325
LaMont Jonescc879a92021-11-18 22:40:18 +0000326 def __init__(self, repodir, manifest_file, local_manifests=None,
327 outer_client=None, parent_groups='', submanifest_path=''):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400328 """Initialize.
329
330 Args:
331 repodir: Path to the .repo/ dir for holding all internal checkout state.
332 It must be in the top directory of the repo client checkout.
333 manifest_file: Full path to the manifest file to parse. This will usually
334 be |repodir|/|MANIFEST_FILE_NAME|.
335 local_manifests: Full path to the directory of local override manifests.
336 This will usually be |repodir|/|LOCAL_MANIFESTS_DIR_NAME|.
LaMont Jonescc879a92021-11-18 22:40:18 +0000337 outer_client: RepoClient of the outertree.
338 parent_groups: a string, the groups to apply to this projects.
339 submanifest_path: The submanifest root relative to the repo root.
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400340 """
341 # TODO(vapier): Move this out of this class.
342 self.globalConfig = GitConfig.ForUser()
343
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700344 self.repodir = os.path.abspath(repodir)
LaMont Jonescc879a92021-11-18 22:40:18 +0000345 self._CheckLocalPath(submanifest_path)
346 self.topdir = os.path.join(os.path.dirname(self.repodir), submanifest_path)
LaMont Jones5d3291d2022-03-23 19:03:02 +0000347 if manifest_file != os.path.abspath(manifest_file):
348 raise ManifestParseError('manifest_file must be abspath')
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400349 self.manifestFile = manifest_file
350 self.local_manifests = local_manifests
Basil Gelloc7453502018-05-25 20:23:52 +0300351 self._load_local_manifests = True
LaMont Jonescc879a92021-11-18 22:40:18 +0000352 self.parent_groups = parent_groups
353
354 if outer_client and self.isGitcClient:
355 raise ManifestParseError('Multi-manifest is incompatible with `gitc-init`')
356
357 if submanifest_path and not outer_client:
358 # If passing a submanifest_path, there must be an outer_client.
359 raise ManifestParseError(f'Bad call to {self.__class__.__name__}')
360
361 # If self._outer_client is None, this is not a checkout that supports
362 # multi-tree.
363 self._outer_client = outer_client or self
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700364
LaMont Jones9b72cf22022-03-29 21:54:22 +0000365 self.repoProject = RepoProject(self, 'repo',
David Pursehouseabdf7502020-02-12 14:58:39 +0900366 gitdir=os.path.join(repodir, 'repo/.git'),
367 worktree=os.path.join(repodir, 'repo'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700368
LaMont Jonescc879a92021-11-18 22:40:18 +0000369 mp = self.SubmanifestProject(self.path_prefix)
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500370 self.manifestProject = mp
371
372 # This is a bit hacky, but we're in a chicken & egg situation: all the
373 # normal repo settings live in the manifestProject which we just setup
374 # above, so we couldn't easily query before that. We assume Project()
375 # init doesn't care if this changes afterwards.
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000376 if os.path.exists(mp.gitdir) and mp.use_worktree:
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500377 mp.use_git_worktrees = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700378
379 self._Unload()
380
Basil Gelloc7453502018-05-25 20:23:52 +0300381 def Override(self, name, load_local_manifests=True):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700382 """Use a different manifest, just for the current instantiation.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700383 """
Basil Gelloc7453502018-05-25 20:23:52 +0300384 path = None
385
386 # Look for a manifest by path in the filesystem (including the cwd).
387 if not load_local_manifests:
388 local_path = os.path.abspath(name)
389 if os.path.isfile(local_path):
390 path = local_path
391
392 # Look for manifests by name from the manifests repo.
393 if path is None:
394 path = os.path.join(self.manifestProject.worktree, name)
395 if not os.path.isfile(path):
396 raise ManifestParseError('manifest %s not found' % name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700397
398 old = self.manifestFile
399 try:
Basil Gelloc7453502018-05-25 20:23:52 +0300400 self._load_local_manifests = load_local_manifests
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700401 self.manifestFile = path
402 self._Unload()
403 self._Load()
404 finally:
405 self.manifestFile = old
406
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700407 def Link(self, name):
408 """Update the repo metadata to use a different manifest.
409 """
410 self.Override(name)
411
Mike Frysingera269b1c2020-02-21 00:49:41 -0500412 # Old versions of repo would generate symlinks we need to clean up.
Mike Frysinger9d96f582021-09-28 11:27:24 -0400413 platform_utils.remove(self.manifestFile, missing_ok=True)
Mike Frysingera269b1c2020-02-21 00:49:41 -0500414 # This file is interpreted as if it existed inside the manifest repo.
415 # That allows us to use <include> with the relative file name.
416 with open(self.manifestFile, 'w') as fp:
417 fp.write("""<?xml version="1.0" encoding="UTF-8"?>
418<!--
419DO NOT EDIT THIS FILE! It is generated by repo and changes will be discarded.
420If you want to use a different manifest, use `repo init -m <file>` instead.
421
422If you want to customize your checkout by overriding manifest settings, use
423the local_manifests/ directory instead.
424
425For more information on repo manifests, check out:
426https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
427-->
428<manifest>
429 <include name="%s" />
430</manifest>
431""" % (name,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700432
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800433 def _RemoteToXml(self, r, doc, root):
434 e = doc.createElement('remote')
435 root.appendChild(e)
436 e.setAttribute('name', r.name)
437 e.setAttribute('fetch', r.fetchUrl)
Steve Raed6480452016-08-10 15:00:00 -0700438 if r.pushUrl is not None:
439 e.setAttribute('pushurl', r.pushUrl)
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700440 if r.remoteAlias is not None:
441 e.setAttribute('alias', r.remoteAlias)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800442 if r.reviewUrl is not None:
443 e.setAttribute('review', r.reviewUrl)
Anthony King36ea2fb2014-05-06 11:54:01 +0100444 if r.revision is not None:
445 e.setAttribute('revision', r.revision)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800446
Jack Neus6ea0cae2021-07-20 20:52:33 +0000447 for a in r.annotations:
448 if a.keep == 'true':
449 ae = doc.createElement('annotation')
450 ae.setAttribute('name', a.name)
451 ae.setAttribute('value', a.value)
452 e.appendChild(ae)
453
LaMont Jonescc879a92021-11-18 22:40:18 +0000454 def _SubmanifestToXml(self, r, doc, root):
455 """Generate XML <submanifest/> node."""
456 e = doc.createElement('submanifest')
457 root.appendChild(e)
458 e.setAttribute('name', r.name)
459 if r.remote is not None:
460 e.setAttribute('remote', r.remote)
461 if r.project is not None:
462 e.setAttribute('project', r.project)
463 if r.manifestName is not None:
464 e.setAttribute('manifest-name', r.manifestName)
465 if r.revision is not None:
466 e.setAttribute('revision', r.revision)
467 if r.path is not None:
468 e.setAttribute('path', r.path)
469 if r.groups:
470 e.setAttribute('groups', r.GetGroupsStr())
471
472 for a in r.annotations:
473 if a.keep == 'true':
474 ae = doc.createElement('annotation')
475 ae.setAttribute('name', a.name)
476 ae.setAttribute('value', a.value)
477 e.appendChild(ae)
478
Mike Frysinger51e39d52020-12-04 05:32:06 -0500479 def _ParseList(self, field):
480 """Parse fields that contain flattened lists.
481
482 These are whitespace & comma separated. Empty elements will be discarded.
483 """
484 return [x for x in re.split(r'[,\s]+', field) if x]
Josh Triplett884a3872014-06-12 14:57:29 -0700485
Mike Frysinger23411d32020-09-02 04:31:10 -0400486 def ToXml(self, peg_rev=False, peg_rev_upstream=True, peg_rev_dest_branch=True, groups=None):
487 """Return the current manifest XML."""
Colin Cross5acde752012-03-28 20:15:45 -0700488 mp = self.manifestProject
489
Dan Willemsen5ea32d12015-09-08 13:27:20 -0700490 if groups is None:
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000491 groups = mp.manifest_groups
Matt Gumbel0c635bb2012-12-21 10:14:53 -0800492 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -0500493 groups = self._ParseList(groups)
Colin Cross5acde752012-03-28 20:15:45 -0700494
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800495 doc = xml.dom.minidom.Document()
496 root = doc.createElement('manifest')
LaMont Jonescc879a92021-11-18 22:40:18 +0000497 if self.is_submanifest:
498 root.setAttribute('path', self.path_prefix)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800499 doc.appendChild(root)
500
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700501 # Save out the notice. There's a little bit of work here to give it the
502 # right whitespace, which assumes that the notice is automatically indented
503 # by 4 by minidom.
504 if self.notice:
505 notice_element = root.appendChild(doc.createElement('notice'))
506 notice_lines = self.notice.splitlines()
David Pursehouse54a4e602020-02-12 14:31:05 +0900507 indented_notice = ('\n'.join(" " * 4 + line for line in notice_lines))[4:]
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700508 notice_element.appendChild(doc.createTextNode(indented_notice))
509
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800510 d = self.default
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800511
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530512 for r in sorted(self.remotes):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800513 self._RemoteToXml(self.remotes[r], doc, root)
514 if self.remotes:
515 root.appendChild(doc.createTextNode(''))
516
517 have_default = False
518 e = doc.createElement('default')
519 if d.remote:
520 have_default = True
521 e.setAttribute('remote', d.remote.name)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700522 if d.revisionExpr:
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800523 have_default = True
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700524 e.setAttribute('revision', d.revisionExpr)
Simon Ruggier7e59de22015-07-24 12:50:06 +0200525 if d.destBranchExpr:
526 have_default = True
527 e.setAttribute('dest-branch', d.destBranchExpr)
Nasser Grainawida403412018-05-04 12:53:29 -0600528 if d.upstreamExpr:
529 have_default = True
530 e.setAttribute('upstream', d.upstreamExpr)
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700531 if d.sync_j > 1:
532 have_default = True
533 e.setAttribute('sync-j', '%d' % d.sync_j)
Anatol Pomazau79770d22012-04-20 14:41:59 -0700534 if d.sync_c:
535 have_default = True
536 e.setAttribute('sync-c', 'true')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800537 if d.sync_s:
538 have_default = True
539 e.setAttribute('sync-s', 'true')
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900540 if not d.sync_tags:
541 have_default = True
542 e.setAttribute('sync-tags', 'false')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800543 if have_default:
544 root.appendChild(e)
545 root.appendChild(doc.createTextNode(''))
546
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700547 if self._manifest_server:
548 e = doc.createElement('manifest-server')
549 e.setAttribute('url', self._manifest_server)
550 root.appendChild(e)
551 root.appendChild(doc.createTextNode(''))
552
LaMont Jonescc879a92021-11-18 22:40:18 +0000553 for r in sorted(self.submanifests):
554 self._SubmanifestToXml(self.submanifests[r], doc, root)
555 if self.submanifests:
556 root.appendChild(doc.createTextNode(''))
557
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800558 def output_projects(parent, parent_node, projects):
David James8d201162013-10-11 17:03:19 -0700559 for project_name in projects:
560 for project in self._projects[project_name]:
561 output_project(parent, parent_node, project)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800562
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800563 def output_project(parent, parent_node, p):
Colin Cross5acde752012-03-28 20:15:45 -0700564 if not p.MatchesGroups(groups):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800565 return
566
567 name = p.name
568 relpath = p.relpath
569 if parent:
570 name = self._UnjoinName(parent.name, name)
571 relpath = self._UnjoinRelpath(parent.relpath, relpath)
Colin Cross5acde752012-03-28 20:15:45 -0700572
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800573 e = doc.createElement('project')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800574 parent_node.appendChild(e)
575 e.setAttribute('name', name)
576 if relpath != name:
577 e.setAttribute('path', relpath)
Conley Owensa17d7af2013-10-16 14:38:09 -0700578 remoteName = None
579 if d.remote:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700580 remoteName = d.remote.name
581 if not d.remote or p.remote.orig_name != remoteName:
582 remoteName = p.remote.orig_name
Anthony King36ea2fb2014-05-06 11:54:01 +0100583 e.setAttribute('remote', remoteName)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800584 if peg_rev:
585 if self.IsMirror:
Brian Harring14a66742012-09-28 20:21:57 -0700586 value = p.bare_git.rev_parse(p.revisionExpr + '^0')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800587 else:
Brian Harring14a66742012-09-28 20:21:57 -0700588 value = p.work_git.rev_parse(HEAD + '^0')
589 e.setAttribute('revision', value)
Conley Owens551dfec2015-07-10 14:54:54 -0700590 if peg_rev_upstream:
591 if p.upstream:
592 e.setAttribute('upstream', p.upstream)
593 elif value != p.revisionExpr:
594 # Only save the origin if the origin is not a sha1, and the default
595 # isn't our value
596 e.setAttribute('upstream', p.revisionExpr)
Sean McAllisteraf908cb2020-04-20 08:41:58 -0600597
598 if peg_rev_dest_branch:
599 if p.dest_branch:
600 e.setAttribute('dest-branch', p.dest_branch)
601 elif value != p.revisionExpr:
602 e.setAttribute('dest-branch', p.revisionExpr)
603
Anthony King36ea2fb2014-05-06 11:54:01 +0100604 else:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700605 revision = self.remotes[p.remote.orig_name].revision or d.revisionExpr
Anthony King36ea2fb2014-05-06 11:54:01 +0100606 if not revision or revision != p.revisionExpr:
607 e.setAttribute('revision', p.revisionExpr)
Raman Tennetib5c5a5e2021-02-06 09:44:15 -0800608 elif p.revisionId:
609 e.setAttribute('revision', p.revisionId)
Nasser Grainawida403412018-05-04 12:53:29 -0600610 if (p.upstream and (p.upstream != p.revisionExpr or
611 p.upstream != d.upstreamExpr)):
Mani Chandel7a91d512014-07-24 16:27:08 +0530612 e.setAttribute('upstream', p.upstream)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800613
Simon Ruggier7e59de22015-07-24 12:50:06 +0200614 if p.dest_branch and p.dest_branch != d.destBranchExpr:
615 e.setAttribute('dest-branch', p.dest_branch)
616
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800617 for c in p.copyfiles:
618 ce = doc.createElement('copyfile')
619 ce.setAttribute('src', c.src)
620 ce.setAttribute('dest', c.dest)
621 e.appendChild(ce)
622
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500623 for l in p.linkfiles:
624 le = doc.createElement('linkfile')
625 le.setAttribute('src', l.src)
626 le.setAttribute('dest', l.dest)
627 e.appendChild(le)
628
Conley Owensbb1b5f52012-08-13 13:11:18 -0700629 default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
Dmitry Fink17f85ea2012-08-06 14:52:29 -0700630 egroups = [g for g in p.groups if g not in default_groups]
Conley Owens971de8e2012-04-16 10:36:08 -0700631 if egroups:
632 e.setAttribute('groups', ','.join(egroups))
Colin Cross5acde752012-03-28 20:15:45 -0700633
James W. Mills24c13082012-04-12 15:04:13 -0500634 for a in p.annotations:
635 if a.keep == "true":
636 ae = doc.createElement('annotation')
637 ae.setAttribute('name', a.name)
638 ae.setAttribute('value', a.value)
639 e.appendChild(ae)
640
Anatol Pomazau79770d22012-04-20 14:41:59 -0700641 if p.sync_c:
642 e.setAttribute('sync-c', 'true')
643
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800644 if p.sync_s:
645 e.setAttribute('sync-s', 'true')
646
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900647 if not p.sync_tags:
648 e.setAttribute('sync-tags', 'false')
649
Dan Willemsen88409222015-08-17 15:29:10 -0700650 if p.clone_depth:
651 e.setAttribute('clone-depth', str(p.clone_depth))
652
Simran Basib9a1b732015-08-20 12:19:28 -0700653 self._output_manifest_project_extras(p, e)
654
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800655 if p.subprojects:
David James8d201162013-10-11 17:03:19 -0700656 subprojects = set(subp.name for subp in p.subprojects)
657 output_projects(p, e, list(sorted(subprojects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800658
David James8d201162013-10-11 17:03:19 -0700659 projects = set(p.name for p in self._paths.values() if not p.parent)
660 output_projects(None, root, list(sorted(projects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800661
Doug Anderson37282b42011-03-04 11:54:18 -0800662 if self._repo_hooks_project:
663 root.appendChild(doc.createTextNode(''))
664 e = doc.createElement('repo-hooks')
665 e.setAttribute('in-project', self._repo_hooks_project.name)
666 e.setAttribute('enabled-list',
667 ' '.join(self._repo_hooks_project.enabled_repo_hooks))
668 root.appendChild(e)
669
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800670 if self._superproject:
671 root.appendChild(doc.createTextNode(''))
672 e = doc.createElement('superproject')
673 e.setAttribute('name', self._superproject['name'])
674 remoteName = None
675 if d.remote:
676 remoteName = d.remote.name
677 remote = self._superproject.get('remote')
678 if not d.remote or remote.orig_name != remoteName:
679 remoteName = remote.orig_name
680 e.setAttribute('remote', remoteName)
Xin Lie0b16a22021-09-26 23:20:32 -0700681 revision = remote.revision or d.revisionExpr
682 if not revision or revision != self._superproject['revision']:
683 e.setAttribute('revision', self._superproject['revision'])
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800684 root.appendChild(e)
685
Raman Tenneti993af5e2021-05-12 12:00:31 -0700686 if self._contactinfo.bugurl != Wrapper().BUG_URL:
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700687 root.appendChild(doc.createTextNode(''))
688 e = doc.createElement('contactinfo')
Raman Tenneti993af5e2021-05-12 12:00:31 -0700689 e.setAttribute('bugurl', self._contactinfo.bugurl)
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700690 root.appendChild(e)
691
Mike Frysinger23411d32020-09-02 04:31:10 -0400692 return doc
693
694 def ToDict(self, **kwargs):
695 """Return the current manifest as a dictionary."""
696 # Elements that may only appear once.
697 SINGLE_ELEMENTS = {
698 'notice',
699 'default',
700 'manifest-server',
701 'repo-hooks',
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800702 'superproject',
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700703 'contactinfo',
Mike Frysinger23411d32020-09-02 04:31:10 -0400704 }
705 # Elements that may be repeated.
706 MULTI_ELEMENTS = {
707 'remote',
708 'remove-project',
709 'project',
710 'extend-project',
711 'include',
LaMont Jonescc879a92021-11-18 22:40:18 +0000712 'submanifest',
Mike Frysinger23411d32020-09-02 04:31:10 -0400713 # These are children of 'project' nodes.
714 'annotation',
715 'project',
716 'copyfile',
717 'linkfile',
718 }
719
720 doc = self.ToXml(**kwargs)
721 ret = {}
722
723 def append_children(ret, node):
724 for child in node.childNodes:
725 if child.nodeType == xml.dom.Node.ELEMENT_NODE:
726 attrs = child.attributes
727 element = dict((attrs.item(i).localName, attrs.item(i).value)
728 for i in range(attrs.length))
729 if child.nodeName in SINGLE_ELEMENTS:
730 ret[child.nodeName] = element
731 elif child.nodeName in MULTI_ELEMENTS:
732 ret.setdefault(child.nodeName, []).append(element)
733 else:
734 raise ManifestParseError('Unhandled element "%s"' % (child.nodeName,))
735
736 append_children(element, child)
737
738 append_children(ret, doc.firstChild)
739
740 return ret
741
742 def Save(self, fd, **kwargs):
743 """Write the current manifest out to the given file descriptor."""
744 doc = self.ToXml(**kwargs)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800745 doc.writexml(fd, '', ' ', '\n', 'UTF-8')
746
Simran Basib9a1b732015-08-20 12:19:28 -0700747 def _output_manifest_project_extras(self, p, e):
748 """Manifests can modify e if they support extra project attributes."""
Simran Basib9a1b732015-08-20 12:19:28 -0700749
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700750 @property
LaMont Jonescc879a92021-11-18 22:40:18 +0000751 def is_multimanifest(self):
752 """Whether this is a multimanifest checkout"""
753 return bool(self.outer_client.submanifests)
754
755 @property
756 def is_submanifest(self):
757 """Whether this manifest is a submanifest"""
758 return self._outer_client and self._outer_client != self
759
760 @property
761 def outer_client(self):
762 """The instance of the outermost manifest client"""
763 self._Load()
764 return self._outer_client
765
766 @property
767 def all_manifests(self):
768 """Generator yielding all (sub)manifests."""
769 self._Load()
770 outer = self._outer_client
771 yield outer
772 for tree in outer.all_children:
773 yield tree
774
775 @property
776 def all_children(self):
777 """Generator yielding all child submanifests."""
778 self._Load()
779 for child in self._submanifests.values():
780 if child.repo_client:
781 yield child.repo_client
782 for tree in child.repo_client.all_children:
783 yield tree
784
785 @property
786 def path_prefix(self):
787 """The path of this submanifest, relative to the outermost manifest."""
788 if not self._outer_client or self == self._outer_client:
789 return ''
790 return os.path.relpath(self.topdir, self._outer_client.topdir)
791
792 @property
793 def all_paths(self):
794 """All project paths for all (sub)manifests. See `paths`."""
795 ret = {}
796 for tree in self.all_manifests:
797 prefix = tree.path_prefix
798 ret.update({os.path.join(prefix, k): v for k, v in tree.paths.items()})
799 return ret
800
801 @property
802 def all_projects(self):
803 """All projects for all (sub)manifests. See `projects`."""
804 return list(itertools.chain.from_iterable(x._paths.values() for x in self.all_manifests))
805
806 @property
David James8d201162013-10-11 17:03:19 -0700807 def paths(self):
LaMont Jonescc879a92021-11-18 22:40:18 +0000808 """Return all paths for this manifest.
809
810 Return:
811 A dictionary of {path: Project()}. `path` is relative to this manifest.
812 """
David James8d201162013-10-11 17:03:19 -0700813 self._Load()
814 return self._paths
815
816 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700817 def projects(self):
LaMont Jonescc879a92021-11-18 22:40:18 +0000818 """Return a list of all Projects in this manifest."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700819 self._Load()
Anthony Kingd58bfe52014-05-05 23:30:49 +0100820 return list(self._paths.values())
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700821
822 @property
823 def remotes(self):
824 self._Load()
825 return self._remotes
826
827 @property
828 def default(self):
829 self._Load()
830 return self._default
831
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800832 @property
LaMont Jonescc879a92021-11-18 22:40:18 +0000833 def submanifests(self):
834 """All submanifests in this manifest."""
835 self._Load()
836 return self._submanifests
837
838 @property
Doug Anderson37282b42011-03-04 11:54:18 -0800839 def repo_hooks_project(self):
840 self._Load()
841 return self._repo_hooks_project
842
843 @property
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800844 def superproject(self):
845 self._Load()
846 return self._superproject
847
848 @property
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700849 def contactinfo(self):
850 self._Load()
851 return self._contactinfo
852
853 @property
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700854 def notice(self):
855 self._Load()
856 return self._notice
857
858 @property
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700859 def manifest_server(self):
860 self._Load()
Shawn O. Pearce34fb20f2011-11-30 13:41:02 -0800861 return self._manifest_server
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700862
863 @property
Xin Lid79a4bc2020-05-20 16:03:45 -0700864 def CloneBundle(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000865 clone_bundle = self.manifestProject.clone_bundle
Xin Lid79a4bc2020-05-20 16:03:45 -0700866 if clone_bundle is None:
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000867 return False if self.manifestProject.partial_clone else True
Xin Lid79a4bc2020-05-20 16:03:45 -0700868 else:
869 return clone_bundle
870
871 @property
Xin Li745be2e2019-06-03 11:24:30 -0700872 def CloneFilter(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000873 if self.manifestProject.partial_clone:
874 return self.manifestProject.clone_filter
Xin Li745be2e2019-06-03 11:24:30 -0700875 return None
876
877 @property
Raman Tennetif32f2432021-04-12 20:57:25 -0700878 def PartialCloneExclude(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000879 exclude = self.manifest.manifestProject.partial_clone_exclude or ''
Raman Tennetif32f2432021-04-12 20:57:25 -0700880 return set(x.strip() for x in exclude.split(','))
881
882 @property
Michael Kellyc34b91c2021-07-02 09:25:48 -0700883 def UseLocalManifests(self):
884 return self._load_local_manifests
885
886 def SetUseLocalManifests(self, value):
887 self._load_local_manifests = value
888
889 @property
Raman Tennetifeb28912021-05-02 19:47:29 -0700890 def HasLocalManifests(self):
891 return self._load_local_manifests and self.local_manifests
892
LaMont Jones87cce682022-02-14 17:48:31 +0000893 def IsFromLocalManifest(self, project):
LaMont Jonescc879a92021-11-18 22:40:18 +0000894 """Is the project from a local manifest?"""
LaMont Jones87cce682022-02-14 17:48:31 +0000895 return any(x.startswith(LOCAL_MANIFEST_GROUP_PREFIX)
896 for x in project.groups)
897
Raman Tennetifeb28912021-05-02 19:47:29 -0700898 @property
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800899 def IsMirror(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000900 return self.manifestProject.mirror
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800901
Julien Campergue335f5ef2013-10-16 11:02:35 +0200902 @property
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500903 def UseGitWorktrees(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000904 return self.manifestProject.use_worktree
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500905
906 @property
Julien Campergue335f5ef2013-10-16 11:02:35 +0200907 def IsArchive(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000908 return self.manifestProject.archive
Julien Campergue335f5ef2013-10-16 11:02:35 +0200909
Martin Kellye4e94d22017-03-21 16:05:12 -0700910 @property
911 def HasSubmodules(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000912 return self.manifestProject.submodules
Martin Kellye4e94d22017-03-21 16:05:12 -0700913
XD Trol630876f2022-01-17 23:29:04 +0800914 @property
915 def EnableGitLfs(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000916 return self.manifestProject.git_lfs
XD Trol630876f2022-01-17 23:29:04 +0800917
LaMont Jonescc879a92021-11-18 22:40:18 +0000918 def FindManifestByPath(self, path):
919 """Returns the manifest containing path."""
920 path = os.path.abspath(path)
921 manifest = self._outer_client or self
922 old = None
923 while manifest._submanifests and manifest != old:
924 old = manifest
925 for name in manifest._submanifests:
926 tree = manifest._submanifests[name]
927 if path.startswith(tree.repo_client.manifest.topdir):
928 manifest = tree.repo_client
929 break
930 return manifest
931
932 @property
933 def subdir(self):
934 """Returns the path for per-submanifest objects for this manifest."""
935 return self.SubmanifestInfoDir(self.path_prefix)
936
937 def SubmanifestInfoDir(self, submanifest_path, object_path=''):
938 """Return the path to submanifest-specific info for a submanifest.
939
940 Return the full path of the directory in which to put per-manifest objects.
941
942 Args:
943 submanifest_path: a string, the path of the submanifest, relative to the
944 outermost topdir. If empty, then repodir is returned.
945 object_path: a string, relative path to append to the submanifest info
946 directory path.
947 """
948 if submanifest_path:
949 return os.path.join(self.repodir, SUBMANIFEST_DIR, submanifest_path,
950 object_path)
951 else:
952 return os.path.join(self.repodir, object_path)
953
954 def SubmanifestProject(self, submanifest_path):
955 """Return a manifestProject for a submanifest."""
956 subdir = self.SubmanifestInfoDir(submanifest_path)
LaMont Jones9b72cf22022-03-29 21:54:22 +0000957 mp = ManifestProject(self, 'manifests',
958 gitdir=os.path.join(subdir, 'manifests.git'),
959 worktree=os.path.join(subdir, 'manifests'))
LaMont Jonescc879a92021-11-18 22:40:18 +0000960 return mp
961
Raman Tenneti080877e2021-03-09 15:19:06 -0800962 def GetDefaultGroupsStr(self):
963 """Returns the default group string for the platform."""
964 return 'default,platform-' + platform.system().lower()
965
966 def GetGroupsStr(self):
967 """Returns the manifest group string that should be synced."""
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000968 groups = self.manifestProject.manifest_groups
Raman Tenneti080877e2021-03-09 15:19:06 -0800969 if not groups:
970 groups = self.GetDefaultGroupsStr()
971 return groups
972
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700973 def _Unload(self):
974 self._loaded = False
975 self._projects = {}
David James8d201162013-10-11 17:03:19 -0700976 self._paths = {}
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700977 self._remotes = {}
978 self._default = None
LaMont Jonescc879a92021-11-18 22:40:18 +0000979 self._submanifests = {}
Doug Anderson37282b42011-03-04 11:54:18 -0800980 self._repo_hooks_project = None
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800981 self._superproject = {}
Raman Tenneti993af5e2021-05-12 12:00:31 -0700982 self._contactinfo = ContactInfo(Wrapper().BUG_URL)
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700983 self._notice = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700984 self.branch = None
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700985 self._manifest_server = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700986
LaMont Jonescc879a92021-11-18 22:40:18 +0000987 def _Load(self, initial_client=None, submanifest_depth=0):
988 if submanifest_depth > MAX_SUBMANIFEST_DEPTH:
989 raise ManifestParseError('maximum submanifest depth %d exceeded.' %
990 MAX_SUBMANIFEST_DEPTH)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700991 if not self._loaded:
LaMont Jonescc879a92021-11-18 22:40:18 +0000992 if self._outer_client and self._outer_client != self:
993 # This will load all clients.
994 self._outer_client._Load(initial_client=self)
995
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800996 m = self.manifestProject
997 b = m.GetBranch(m.CurrentBranch).merge
Shawn O. Pearce21c5c342009-06-25 16:47:30 -0700998 if b is not None and b.startswith(R_HEADS):
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800999 b = b[len(R_HEADS):]
1000 self.branch = b
1001
LaMont Jonescc879a92021-11-18 22:40:18 +00001002 parent_groups = self.parent_groups
LaMont Jonesb308db12022-02-25 17:05:21 +00001003 if self.path_prefix:
1004 parent_groups = f'{SUBMANIFEST_GROUP_PREFIX}:path:{self.path_prefix},{parent_groups}'
LaMont Jonescc879a92021-11-18 22:40:18 +00001005
Mike Frysinger54133972021-03-01 21:38:08 -05001006 # The manifestFile was specified by the user which is why we allow include
1007 # paths to point anywhere.
Colin Cross23acdd32012-04-21 00:33:54 -07001008 nodes = []
Mike Frysinger54133972021-03-01 21:38:08 -05001009 nodes.append(self._ParseManifestXml(
1010 self.manifestFile, self.manifestProject.worktree,
LaMont Jonescc879a92021-11-18 22:40:18 +00001011 parent_groups=parent_groups, restrict_includes=False))
Shawn O. Pearce5cc66792008-10-23 16:19:27 -07001012
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001013 if self._load_local_manifests and self.local_manifests:
Basil Gelloc7453502018-05-25 20:23:52 +03001014 try:
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001015 for local_file in sorted(platform_utils.listdir(self.local_manifests)):
Basil Gelloc7453502018-05-25 20:23:52 +03001016 if local_file.endswith('.xml'):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001017 local = os.path.join(self.local_manifests, local_file)
Mike Frysinger54133972021-03-01 21:38:08 -05001018 # Since local manifests are entirely managed by the user, allow
1019 # them to point anywhere the user wants.
LaMont Jonescc879a92021-11-18 22:40:18 +00001020 local_group = f'{LOCAL_MANIFEST_GROUP_PREFIX}:{local_file[:-4]}'
Mike Frysinger54133972021-03-01 21:38:08 -05001021 nodes.append(self._ParseManifestXml(
LaMont Jonescc879a92021-11-18 22:40:18 +00001022 local, self.subdir,
1023 parent_groups=f'{local_group},{parent_groups}',
Raman Tenneti78f4dd32021-06-07 13:27:37 -07001024 restrict_includes=False))
Basil Gelloc7453502018-05-25 20:23:52 +03001025 except OSError:
1026 pass
David Pursehouse2d5a0df2012-11-13 02:50:36 +09001027
Joe Onorato26e24752013-01-11 12:35:53 -08001028 try:
1029 self._ParseManifest(nodes)
1030 except ManifestParseError as e:
1031 # There was a problem parsing, unload ourselves in case they catch
1032 # this error and try again later, we will show the correct error
1033 self._Unload()
1034 raise e
Shawn O. Pearce5cc66792008-10-23 16:19:27 -07001035
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001036 if self.IsMirror:
1037 self._AddMetaProjectMirror(self.repoProject)
1038 self._AddMetaProjectMirror(self.manifestProject)
1039
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001040 self._loaded = True
1041
LaMont Jonescc879a92021-11-18 22:40:18 +00001042 # Now that we have loaded this manifest, load any submanifest manifests
1043 # as well. We need to do this after self._loaded is set to avoid looping.
1044 if self._outer_client:
1045 for name in self._submanifests:
1046 tree = self._submanifests[name]
1047 spec = tree.ToSubmanifestSpec(self)
1048 present = os.path.exists(os.path.join(self.subdir, MANIFEST_FILE_NAME))
1049 if present and tree.present and not tree.repo_client:
1050 if initial_client and initial_client.topdir == self.topdir:
1051 tree.repo_client = self
1052 tree.present = present
1053 elif not os.path.exists(self.subdir):
1054 tree.present = False
LaMont Jones55ee3042022-04-06 17:10:21 +00001055 if present and tree.present:
LaMont Jonescc879a92021-11-18 22:40:18 +00001056 tree.repo_client._Load(initial_client=initial_client,
1057 submanifest_depth=submanifest_depth + 1)
1058
Mike Frysinger54133972021-03-01 21:38:08 -05001059 def _ParseManifestXml(self, path, include_root, parent_groups='',
1060 restrict_includes=True):
1061 """Parse a manifest XML and return the computed nodes.
1062
1063 Args:
1064 path: The XML file to read & parse.
1065 include_root: The path to interpret include "name"s relative to.
1066 parent_groups: The groups to apply to this projects.
1067 restrict_includes: Whether to constrain the "name" attribute of includes.
1068
1069 Returns:
1070 List of XML nodes.
1071 """
David Pursehousef7fc8a92012-11-13 04:00:28 +09001072 try:
1073 root = xml.dom.minidom.parse(path)
David Pursehouse2d5a0df2012-11-13 02:50:36 +09001074 except (OSError, xml.parsers.expat.ExpatError) as e:
David Pursehousef7fc8a92012-11-13 04:00:28 +09001075 raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
1076
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001077 if not root or not root.childNodes:
Brian Harring26448742011-04-28 05:04:41 -07001078 raise ManifestParseError("no root node in %s" % (path,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001079
Jooncheol Park34acdd22012-08-27 02:25:59 +09001080 for manifest in root.childNodes:
1081 if manifest.nodeName == 'manifest':
1082 break
1083 else:
Brian Harring26448742011-04-28 05:04:41 -07001084 raise ManifestParseError("no <manifest> in %s" % (path,))
1085
Colin Cross23acdd32012-04-21 00:33:54 -07001086 nodes = []
David Pursehouse65b0ba52018-06-24 16:21:51 +09001087 for node in manifest.childNodes:
David Pursehousec1b86a22012-11-14 11:36:51 +09001088 if node.nodeName == 'include':
1089 name = self._reqatt(node, 'name')
Mike Frysinger54133972021-03-01 21:38:08 -05001090 if restrict_includes:
1091 msg = self._CheckLocalPath(name)
1092 if msg:
1093 raise ManifestInvalidPathError(
1094 '<include> invalid "name": %s: %s' % (name, msg))
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001095 include_groups = ''
1096 if parent_groups:
1097 include_groups = parent_groups
1098 if node.hasAttribute('groups'):
1099 include_groups = node.getAttribute('groups') + ',' + include_groups
David Pursehousec1b86a22012-11-14 11:36:51 +09001100 fp = os.path.join(include_root, name)
1101 if not os.path.isfile(fp):
Mike Frysinger54133972021-03-01 21:38:08 -05001102 raise ManifestParseError("include [%s/]%s doesn't exist or isn't a file"
1103 % (include_root, name))
David Pursehousec1b86a22012-11-14 11:36:51 +09001104 try:
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001105 nodes.extend(self._ParseManifestXml(fp, include_root, include_groups))
David Pursehousec1b86a22012-11-14 11:36:51 +09001106 # should isolate this to the exact exception, but that's
1107 # tricky. actual parsing implementation may vary.
Mike Frysinger54133972021-03-01 21:38:08 -05001108 except (KeyboardInterrupt, RuntimeError, SystemExit, ManifestParseError):
David Pursehousec1b86a22012-11-14 11:36:51 +09001109 raise
1110 except Exception as e:
1111 raise ManifestParseError(
Mike Frysingerec558df2019-07-05 01:38:05 -04001112 "failed parsing included manifest %s: %s" % (name, e))
David Pursehousec1b86a22012-11-14 11:36:51 +09001113 else:
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001114 if parent_groups and node.nodeName == 'project':
1115 nodeGroups = parent_groups
1116 if node.hasAttribute('groups'):
1117 nodeGroups = node.getAttribute('groups') + ',' + nodeGroups
1118 node.setAttribute('groups', nodeGroups)
David Pursehousec1b86a22012-11-14 11:36:51 +09001119 nodes.append(node)
Colin Cross23acdd32012-04-21 00:33:54 -07001120 return nodes
Brian Harring26448742011-04-28 05:04:41 -07001121
Colin Cross23acdd32012-04-21 00:33:54 -07001122 def _ParseManifest(self, node_list):
1123 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001124 if node.nodeName == 'remote':
1125 remote = self._ParseRemote(node)
David Pursehouse717ece92012-11-13 08:49:16 +09001126 if remote:
1127 if remote.name in self._remotes:
1128 if remote != self._remotes[remote.name]:
1129 raise ManifestParseError(
1130 'remote %s already exists with different attributes' %
1131 (remote.name))
1132 else:
1133 self._remotes[remote.name] = remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001134
Colin Cross23acdd32012-04-21 00:33:54 -07001135 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001136 if node.nodeName == 'default':
Julien Campergue74879922013-10-09 14:38:46 +02001137 new_default = self._ParseDefault(node)
Jack Neusb8c84482021-06-15 14:28:30 +00001138 emptyDefault = not node.hasAttributes() and not node.hasChildNodes()
Julien Campergue74879922013-10-09 14:38:46 +02001139 if self._default is None:
1140 self._default = new_default
Jack Neusb8c84482021-06-15 14:28:30 +00001141 elif not emptyDefault and new_default != self._default:
David Pursehouse37128b62013-10-15 10:48:40 +09001142 raise ManifestParseError('duplicate default in %s' %
1143 (self.manifestFile))
Julien Campergue74879922013-10-09 14:38:46 +02001144
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001145 if self._default is None:
1146 self._default = _Default()
1147
LaMont Jonescc879a92021-11-18 22:40:18 +00001148 submanifest_paths = set()
1149 for node in itertools.chain(*node_list):
1150 if node.nodeName == 'submanifest':
1151 submanifest = self._ParseSubmanifest(node)
1152 if submanifest:
1153 if submanifest.name in self._submanifests:
1154 if submanifest != self._submanifests[submanifest.name]:
1155 raise ManifestParseError(
1156 'submanifest %s already exists with different attributes' %
1157 (submanifest.name))
1158 else:
1159 self._submanifests[submanifest.name] = submanifest
1160 submanifest_paths.add(submanifest.relpath)
1161
Colin Cross23acdd32012-04-21 00:33:54 -07001162 for node in itertools.chain(*node_list):
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001163 if node.nodeName == 'notice':
1164 if self._notice is not None:
Doug Anderson37282b42011-03-04 11:54:18 -08001165 raise ManifestParseError(
1166 'duplicate notice in %s' %
1167 (self.manifestFile))
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001168 self._notice = self._ParseNotice(node)
1169
Colin Cross23acdd32012-04-21 00:33:54 -07001170 for node in itertools.chain(*node_list):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001171 if node.nodeName == 'manifest-server':
1172 url = self._reqatt(node, 'url')
1173 if self._manifest_server is not None:
David Pursehousec1b86a22012-11-14 11:36:51 +09001174 raise ManifestParseError(
1175 'duplicate manifest-server in %s' %
1176 (self.manifestFile))
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001177 self._manifest_server = url
1178
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001179 def recursively_add_projects(project):
David James8d201162013-10-11 17:03:19 -07001180 projects = self._projects.setdefault(project.name, [])
1181 if project.relpath is None:
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001182 raise ManifestParseError(
David James8d201162013-10-11 17:03:19 -07001183 'missing path for %s in %s' %
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001184 (project.name, self.manifestFile))
David James8d201162013-10-11 17:03:19 -07001185 if project.relpath in self._paths:
1186 raise ManifestParseError(
1187 'duplicate path %s in %s' %
1188 (project.relpath, self.manifestFile))
LaMont Jonescc879a92021-11-18 22:40:18 +00001189 for tree in submanifest_paths:
1190 if project.relpath.startswith(tree):
1191 raise ManifestParseError(
1192 'project %s conflicts with submanifest path %s' %
1193 (project.relpath, tree))
David James8d201162013-10-11 17:03:19 -07001194 self._paths[project.relpath] = project
1195 projects.append(project)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001196 for subproject in project.subprojects:
1197 recursively_add_projects(subproject)
1198
Jack Neusa84f43a2021-09-21 22:23:55 +00001199 repo_hooks_project = None
1200 enabled_repo_hooks = None
Colin Cross23acdd32012-04-21 00:33:54 -07001201 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001202 if node.nodeName == 'project':
1203 project = self._ParseProject(node)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001204 recursively_add_projects(project)
Josh Triplett884a3872014-06-12 14:57:29 -07001205 if node.nodeName == 'extend-project':
1206 name = self._reqatt(node, 'name')
1207
1208 if name not in self._projects:
1209 raise ManifestParseError('extend-project element specifies non-existent '
1210 'project: %s' % name)
1211
1212 path = node.getAttribute('path')
Michael Kelly37c21c22020-06-13 02:10:40 -07001213 dest_path = node.getAttribute('dest-path')
Josh Triplett884a3872014-06-12 14:57:29 -07001214 groups = node.getAttribute('groups')
1215 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -05001216 groups = self._ParseList(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -07001217 revision = node.getAttribute('revision')
LaMont Jonescc879a92021-11-18 22:40:18 +00001218 remote_name = node.getAttribute('remote')
1219 if not remote_name:
1220 remote = self._default.remote
1221 else:
Kyunam Jobd0aae92020-02-04 11:38:53 +09001222 remote = self._get_remote(node)
Josh Triplett884a3872014-06-12 14:57:29 -07001223
Michael Kelly37c21c22020-06-13 02:10:40 -07001224 named_projects = self._projects[name]
1225 if dest_path and not path and len(named_projects) > 1:
1226 raise ManifestParseError('extend-project cannot use dest-path when '
1227 'matching multiple projects: %s' % name)
Josh Triplett884a3872014-06-12 14:57:29 -07001228 for p in self._projects[name]:
1229 if path and p.relpath != path:
1230 continue
1231 if groups:
1232 p.groups.extend(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -07001233 if revision:
Michael Kelly2f3c3312020-07-21 19:40:38 -07001234 p.SetRevision(revision)
1235
LaMont Jonescc879a92021-11-18 22:40:18 +00001236 if remote_name:
Kyunam Jobd0aae92020-02-04 11:38:53 +09001237 p.remote = remote.ToRemoteSpec(name)
Michael Kelly2f3c3312020-07-21 19:40:38 -07001238
Michael Kelly37c21c22020-06-13 02:10:40 -07001239 if dest_path:
1240 del self._paths[p.relpath]
LaMont Jonescc879a92021-11-18 22:40:18 +00001241 relpath, worktree, gitdir, objdir, _ = self.GetProjectPaths(
1242 name, dest_path, remote.name)
Michael Kelly37c21c22020-06-13 02:10:40 -07001243 p.UpdatePaths(relpath, worktree, gitdir, objdir)
1244 self._paths[p.relpath] = p
1245
Doug Anderson37282b42011-03-04 11:54:18 -08001246 if node.nodeName == 'repo-hooks':
Doug Anderson37282b42011-03-04 11:54:18 -08001247 # Only one project can be the hooks project
Jack Neusa84f43a2021-09-21 22:23:55 +00001248 if repo_hooks_project is not None:
Doug Anderson37282b42011-03-04 11:54:18 -08001249 raise ManifestParseError(
1250 'duplicate repo-hooks in %s' %
1251 (self.manifestFile))
1252
Jack Neusa84f43a2021-09-21 22:23:55 +00001253 # Get the name of the project and the (space-separated) list of enabled.
1254 repo_hooks_project = self._reqatt(node, 'in-project')
1255 enabled_repo_hooks = self._ParseList(self._reqatt(node, 'enabled-list'))
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001256 if node.nodeName == 'superproject':
1257 name = self._reqatt(node, 'name')
1258 # There can only be one superproject.
1259 if self._superproject.get('name'):
1260 raise ManifestParseError(
1261 'duplicate superproject in %s' %
1262 (self.manifestFile))
1263 self._superproject['name'] = name
1264 remote_name = node.getAttribute('remote')
1265 if not remote_name:
1266 remote = self._default.remote
1267 else:
1268 remote = self._get_remote(node)
1269 if remote is None:
1270 raise ManifestParseError("no remote for superproject %s within %s" %
1271 (name, self.manifestFile))
1272 self._superproject['remote'] = remote.ToRemoteSpec(name)
Xin Lie0b16a22021-09-26 23:20:32 -07001273 revision = node.getAttribute('revision') or remote.revision
1274 if not revision:
1275 revision = self._default.revisionExpr
1276 if not revision:
1277 raise ManifestParseError('no revision for superproject %s within %s' %
1278 (name, self.manifestFile))
1279 self._superproject['revision'] = revision
Raman Tenneti1c3f57e2021-05-04 12:32:13 -07001280 if node.nodeName == 'contactinfo':
1281 bugurl = self._reqatt(node, 'bugurl')
1282 # This element can be repeated, later entries will clobber earlier ones.
Raman Tenneti993af5e2021-05-12 12:00:31 -07001283 self._contactinfo = ContactInfo(bugurl)
1284
Colin Cross23acdd32012-04-21 00:33:54 -07001285 if node.nodeName == 'remove-project':
1286 name = self._reqatt(node, 'name')
David Jamesb8433df2014-01-30 10:11:17 -08001287
Michael Kelly06da9982021-06-30 01:58:28 -07001288 if name in self._projects:
1289 for p in self._projects[name]:
1290 del self._paths[p.relpath]
1291 del self._projects[name]
1292
1293 # If the manifest removes the hooks project, treat it as if it deleted
1294 # the repo-hooks element too.
Jack Neusa84f43a2021-09-21 22:23:55 +00001295 if repo_hooks_project == name:
1296 repo_hooks_project = None
Michael Kelly06da9982021-06-30 01:58:28 -07001297 elif not XmlBool(node, 'optional', False):
David Pursehousef9107482012-11-16 19:12:32 +09001298 raise ManifestParseError('remove-project element specifies non-existent '
1299 'project: %s' % name)
Colin Cross23acdd32012-04-21 00:33:54 -07001300
Jack Neusa84f43a2021-09-21 22:23:55 +00001301 # Store repo hooks project information.
1302 if repo_hooks_project:
1303 # Store a reference to the Project.
1304 try:
1305 repo_hooks_projects = self._projects[repo_hooks_project]
1306 except KeyError:
1307 raise ManifestParseError(
1308 'project %s not found for repo-hooks' %
1309 (repo_hooks_project))
1310
1311 if len(repo_hooks_projects) != 1:
1312 raise ManifestParseError(
1313 'internal error parsing repo-hooks in %s' %
1314 (self.manifestFile))
1315 self._repo_hooks_project = repo_hooks_projects[0]
1316 # Store the enabled hooks in the Project object.
1317 self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
1318
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001319 def _AddMetaProjectMirror(self, m):
1320 name = None
1321 m_url = m.GetRemote(m.remote.name).url
1322 if m_url.endswith('/.git'):
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301323 raise ManifestParseError('refusing to mirror %s' % m_url)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001324
1325 if self._default and self._default.remote:
Conley Owensceea3682011-10-20 10:45:47 -07001326 url = self._default.remote.resolvedFetchUrl
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001327 if not url.endswith('/'):
1328 url += '/'
1329 if m_url.startswith(url):
1330 remote = self._default.remote
1331 name = m_url[len(url):]
1332
1333 if name is None:
1334 s = m_url.rindex('/') + 1
Conley Owensdb728cd2011-09-26 16:34:01 -07001335 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Shawn O. Pearcef35b2d92012-08-02 11:46:22 -07001336 remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001337 name = m_url[s:]
1338
1339 if name.endswith('.git'):
1340 name = name[:-4]
1341
1342 if name not in self._projects:
1343 m.PreSync()
1344 gitdir = os.path.join(self.topdir, '%s.git' % name)
David Pursehousee5913ae2020-02-12 13:56:59 +09001345 project = Project(manifest=self,
1346 name=name,
1347 remote=remote.ToRemoteSpec(name),
1348 gitdir=gitdir,
1349 objdir=gitdir,
1350 worktree=None,
1351 relpath=name or None,
1352 revisionExpr=m.revisionExpr,
1353 revisionId=None)
David James8d201162013-10-11 17:03:19 -07001354 self._projects[project.name] = [project]
Kwanhong Leeccd218c2014-02-17 13:07:32 +09001355 self._paths[project.relpath] = project
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001356
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001357 def _ParseRemote(self, node):
1358 """
1359 reads a <remote> element from the manifest file
1360 """
1361 name = self._reqatt(node, 'name')
Yestin Sunb292b982012-07-02 07:32:50 -07001362 alias = node.getAttribute('alias')
1363 if alias == '':
1364 alias = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001365 fetch = self._reqatt(node, 'fetch')
Steve Raed6480452016-08-10 15:00:00 -07001366 pushUrl = node.getAttribute('pushurl')
1367 if pushUrl == '':
1368 pushUrl = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001369 review = node.getAttribute('review')
Shawn O. Pearceae6e0942008-11-06 10:25:35 -08001370 if review == '':
1371 review = None
Anthony King36ea2fb2014-05-06 11:54:01 +01001372 revision = node.getAttribute('revision')
1373 if revision == '':
1374 revision = None
Conley Owensdb728cd2011-09-26 16:34:01 -07001375 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Jack Neus6ea0cae2021-07-20 20:52:33 +00001376
1377 remote = _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
1378
1379 for n in node.childNodes:
1380 if n.nodeName == 'annotation':
1381 self._ParseAnnotation(remote, n)
1382
1383 return remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001384
1385 def _ParseDefault(self, node):
1386 """
1387 reads a <default> element from the manifest file
1388 """
1389 d = _Default()
1390 d.remote = self._get_remote(node)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001391 d.revisionExpr = node.getAttribute('revision')
1392 if d.revisionExpr == '':
1393 d.revisionExpr = None
Anatol Pomazau79770d22012-04-20 14:41:59 -07001394
Bryan Jacobsf609f912013-05-06 13:36:24 -04001395 d.destBranchExpr = node.getAttribute('dest-branch') or None
Nasser Grainawida403412018-05-04 12:53:29 -06001396 d.upstreamExpr = node.getAttribute('upstream') or None
Bryan Jacobsf609f912013-05-06 13:36:24 -04001397
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001398 d.sync_j = XmlInt(node, 'sync-j', 1)
1399 if d.sync_j <= 0:
1400 raise ManifestParseError('%s: sync-j must be greater than 0, not "%s"' %
1401 (self.manifestFile, d.sync_j))
Anatol Pomazau79770d22012-04-20 14:41:59 -07001402
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001403 d.sync_c = XmlBool(node, 'sync-c', False)
1404 d.sync_s = XmlBool(node, 'sync-s', False)
1405 d.sync_tags = XmlBool(node, 'sync-tags', True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001406 return d
1407
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001408 def _ParseNotice(self, node):
1409 """
1410 reads a <notice> element from the manifest file
1411
1412 The <notice> element is distinct from other tags in the XML in that the
1413 data is conveyed between the start and end tag (it's not an empty-element
1414 tag).
1415
1416 The white space (carriage returns, indentation) for the notice element is
1417 relevant and is parsed in a way that is based on how python docstrings work.
1418 In fact, the code is remarkably similar to here:
1419 http://www.python.org/dev/peps/pep-0257/
1420 """
1421 # Get the data out of the node...
1422 notice = node.childNodes[0].data
1423
1424 # Figure out minimum indentation, skipping the first line (the same line
1425 # as the <notice> tag)...
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301426 minIndent = sys.maxsize
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001427 lines = notice.splitlines()
1428 for line in lines[1:]:
1429 lstrippedLine = line.lstrip()
1430 if lstrippedLine:
1431 indent = len(line) - len(lstrippedLine)
1432 minIndent = min(indent, minIndent)
1433
1434 # Strip leading / trailing blank lines and also indentation.
1435 cleanLines = [lines[0].strip()]
1436 for line in lines[1:]:
1437 cleanLines.append(line[minIndent:].rstrip())
1438
1439 # Clear completely blank lines from front and back...
1440 while cleanLines and not cleanLines[0]:
1441 del cleanLines[0]
1442 while cleanLines and not cleanLines[-1]:
1443 del cleanLines[-1]
1444
1445 return '\n'.join(cleanLines)
1446
LaMont Jonescc879a92021-11-18 22:40:18 +00001447 def _ParseSubmanifest(self, node):
1448 """Reads a <submanifest> element from the manifest file."""
1449 name = self._reqatt(node, 'name')
1450 remote = node.getAttribute('remote')
1451 if remote == '':
1452 remote = None
1453 project = node.getAttribute('project')
1454 if project == '':
1455 project = None
1456 revision = node.getAttribute('revision')
1457 if revision == '':
1458 revision = None
1459 manifestName = node.getAttribute('manifest-name')
1460 if manifestName == '':
1461 manifestName = None
1462 groups = ''
1463 if node.hasAttribute('groups'):
1464 groups = node.getAttribute('groups')
1465 groups = self._ParseList(groups)
1466 path = node.getAttribute('path')
1467 if path == '':
1468 path = None
1469 if revision:
1470 msg = self._CheckLocalPath(revision.split('/')[-1])
1471 if msg:
1472 raise ManifestInvalidPathError(
1473 '<submanifest> invalid "revision": %s: %s' % (revision, msg))
1474 else:
1475 msg = self._CheckLocalPath(name)
1476 if msg:
1477 raise ManifestInvalidPathError(
1478 '<submanifest> invalid "name": %s: %s' % (name, msg))
1479 else:
1480 msg = self._CheckLocalPath(path)
1481 if msg:
1482 raise ManifestInvalidPathError(
1483 '<submanifest> invalid "path": %s: %s' % (path, msg))
1484
1485 submanifest = _XmlSubmanifest(name, remote, project, revision, manifestName,
1486 groups, path, self)
1487
1488 for n in node.childNodes:
1489 if n.nodeName == 'annotation':
1490 self._ParseAnnotation(submanifest, n)
1491
1492 return submanifest
1493
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001494 def _JoinName(self, parent_name, name):
1495 return os.path.join(parent_name, name)
1496
1497 def _UnjoinName(self, parent_name, name):
1498 return os.path.relpath(name, parent_name)
1499
David Pursehousee5913ae2020-02-12 13:56:59 +09001500 def _ParseProject(self, node, parent=None, **extra_proj_attrs):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001501 """
1502 reads a <project> element from the manifest file
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001503 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001504 name = self._reqatt(node, 'name')
Mike Frysingera29424e2021-02-25 21:53:49 -05001505 msg = self._CheckLocalPath(name, dir_ok=True)
1506 if msg:
1507 raise ManifestInvalidPathError(
1508 '<project> invalid "name": %s: %s' % (name, msg))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001509 if parent:
1510 name = self._JoinName(parent.name, name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001511
1512 remote = self._get_remote(node)
1513 if remote is None:
1514 remote = self._default.remote
1515 if remote is None:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301516 raise ManifestParseError("no remote for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001517 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001518
Anthony King36ea2fb2014-05-06 11:54:01 +01001519 revisionExpr = node.getAttribute('revision') or remote.revision
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001520 if not revisionExpr:
1521 revisionExpr = self._default.revisionExpr
1522 if not revisionExpr:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301523 raise ManifestParseError("no revision for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001524 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001525
1526 path = node.getAttribute('path')
1527 if not path:
1528 path = name
Mike Frysingera29424e2021-02-25 21:53:49 -05001529 else:
Mike Frysinger0458faa2021-03-10 23:35:44 -05001530 # NB: The "." project is handled specially in Project.Sync_LocalHalf.
1531 msg = self._CheckLocalPath(path, dir_ok=True, cwd_dot_ok=True)
Mike Frysingera29424e2021-02-25 21:53:49 -05001532 if msg:
1533 raise ManifestInvalidPathError(
1534 '<project> invalid "path": %s: %s' % (path, msg))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001535
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001536 rebase = XmlBool(node, 'rebase', True)
1537 sync_c = XmlBool(node, 'sync-c', False)
1538 sync_s = XmlBool(node, 'sync-s', self._default.sync_s)
1539 sync_tags = XmlBool(node, 'sync-tags', self._default.sync_tags)
Mike Pontillod3153822012-02-28 11:53:24 -08001540
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001541 clone_depth = XmlInt(node, 'clone-depth')
1542 if clone_depth is not None and clone_depth <= 0:
1543 raise ManifestParseError('%s: clone-depth must be greater than 0, not "%s"' %
1544 (self.manifestFile, clone_depth))
David Pursehouseede7f122012-11-27 22:25:30 +09001545
Bryan Jacobsf609f912013-05-06 13:36:24 -04001546 dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
1547
Nasser Grainawida403412018-05-04 12:53:29 -06001548 upstream = node.getAttribute('upstream') or self._default.upstreamExpr
Brian Harring14a66742012-09-28 20:21:57 -07001549
Conley Owens971de8e2012-04-16 10:36:08 -07001550 groups = ''
1551 if node.hasAttribute('groups'):
1552 groups = node.getAttribute('groups')
Mike Frysinger51e39d52020-12-04 05:32:06 -05001553 groups = self._ParseList(groups)
Brian Harring7da13142012-06-15 02:24:20 -07001554
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001555 if parent is None:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001556 relpath, worktree, gitdir, objdir, use_git_worktrees = \
LaMont Jonescc879a92021-11-18 22:40:18 +00001557 self.GetProjectPaths(name, path, remote.name)
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001558 else:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001559 use_git_worktrees = False
David James8d201162013-10-11 17:03:19 -07001560 relpath, worktree, gitdir, objdir = \
1561 self.GetSubprojectPaths(parent, name, path)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001562
1563 default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
1564 groups.extend(set(default_groups).difference(groups))
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001565
Scott Fandb83b1b2013-02-28 09:34:14 +08001566 if self.IsMirror and node.hasAttribute('force-path'):
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001567 if XmlBool(node, 'force-path', False):
Scott Fandb83b1b2013-02-28 09:34:14 +08001568 gitdir = os.path.join(self.topdir, '%s.git' % path)
1569
David Pursehousee5913ae2020-02-12 13:56:59 +09001570 project = Project(manifest=self,
1571 name=name,
1572 remote=remote.ToRemoteSpec(name),
1573 gitdir=gitdir,
1574 objdir=objdir,
1575 worktree=worktree,
1576 relpath=relpath,
1577 revisionExpr=revisionExpr,
1578 revisionId=None,
1579 rebase=rebase,
1580 groups=groups,
1581 sync_c=sync_c,
1582 sync_s=sync_s,
1583 sync_tags=sync_tags,
1584 clone_depth=clone_depth,
1585 upstream=upstream,
1586 parent=parent,
1587 dest_branch=dest_branch,
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001588 use_git_worktrees=use_git_worktrees,
Simran Basib9a1b732015-08-20 12:19:28 -07001589 **extra_proj_attrs)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001590
1591 for n in node.childNodes:
Shawn O. Pearce242b5262009-05-19 13:00:29 -07001592 if n.nodeName == 'copyfile':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001593 self._ParseCopyFile(project, n)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001594 if n.nodeName == 'linkfile':
1595 self._ParseLinkFile(project, n)
James W. Mills24c13082012-04-12 15:04:13 -05001596 if n.nodeName == 'annotation':
1597 self._ParseAnnotation(project, n)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001598 if n.nodeName == 'project':
David Pursehousee5913ae2020-02-12 13:56:59 +09001599 project.subprojects.append(self._ParseProject(n, parent=project))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001600
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001601 return project
1602
LaMont Jonescc879a92021-11-18 22:40:18 +00001603 def GetProjectPaths(self, name, path, remote):
1604 """Return the paths for a project.
1605
1606 Args:
1607 name: a string, the name of the project.
1608 path: a string, the path of the project.
1609 remote: a string, the remote.name of the project.
1610 """
Mike Frysingercebf2272020-05-26 01:02:29 -04001611 # The manifest entries might have trailing slashes. Normalize them to avoid
1612 # unexpected filesystem behavior since we do string concatenation below.
1613 path = path.rstrip('/')
1614 name = name.rstrip('/')
LaMont Jonescc879a92021-11-18 22:40:18 +00001615 remote = remote.rstrip('/')
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001616 use_git_worktrees = False
LaMont Jonescc879a92021-11-18 22:40:18 +00001617 use_remote_name = bool(self._outer_client._submanifests)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001618 relpath = path
1619 if self.IsMirror:
1620 worktree = None
1621 gitdir = os.path.join(self.topdir, '%s.git' % name)
David James8d201162013-10-11 17:03:19 -07001622 objdir = gitdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001623 else:
LaMont Jonescc879a92021-11-18 22:40:18 +00001624 if use_remote_name:
1625 namepath = os.path.join(remote, f'{name}.git')
1626 else:
1627 namepath = f'{name}.git'
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001628 worktree = os.path.join(self.topdir, path).replace('\\', '/')
LaMont Jonescc879a92021-11-18 22:40:18 +00001629 gitdir = os.path.join(self.subdir, 'projects', '%s.git' % path)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001630 # We allow people to mix git worktrees & non-git worktrees for now.
1631 # This allows for in situ migration of repo clients.
1632 if os.path.exists(gitdir) or not self.UseGitWorktrees:
LaMont Jonescc879a92021-11-18 22:40:18 +00001633 objdir = os.path.join(self.subdir, 'project-objects', namepath)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001634 else:
1635 use_git_worktrees = True
LaMont Jonescc879a92021-11-18 22:40:18 +00001636 gitdir = os.path.join(self.repodir, 'worktrees', namepath)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001637 objdir = gitdir
1638 return relpath, worktree, gitdir, objdir, use_git_worktrees
David James8d201162013-10-11 17:03:19 -07001639
LaMont Jonescc879a92021-11-18 22:40:18 +00001640 def GetProjectsWithName(self, name, all_manifests=False):
1641 """All projects with |name|.
1642
1643 Args:
1644 name: a string, the name of the project.
1645 all_manifests: a boolean, if True, then all manifests are searched. If
1646 False, then only this manifest is searched.
1647 """
1648 if all_manifests:
1649 return list(itertools.chain.from_iterable(
1650 x._projects.get(name, []) for x in self.all_manifests))
David James8d201162013-10-11 17:03:19 -07001651 return self._projects.get(name, [])
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001652
1653 def GetSubprojectName(self, parent, submodule_path):
1654 return os.path.join(parent.name, submodule_path)
1655
1656 def _JoinRelpath(self, parent_relpath, relpath):
1657 return os.path.join(parent_relpath, relpath)
1658
1659 def _UnjoinRelpath(self, parent_relpath, relpath):
1660 return os.path.relpath(relpath, parent_relpath)
1661
David James8d201162013-10-11 17:03:19 -07001662 def GetSubprojectPaths(self, parent, name, path):
Mike Frysingercebf2272020-05-26 01:02:29 -04001663 # The manifest entries might have trailing slashes. Normalize them to avoid
1664 # unexpected filesystem behavior since we do string concatenation below.
1665 path = path.rstrip('/')
1666 name = name.rstrip('/')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001667 relpath = self._JoinRelpath(parent.relpath, path)
1668 gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
David James8d201162013-10-11 17:03:19 -07001669 objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001670 if self.IsMirror:
1671 worktree = None
1672 else:
1673 worktree = os.path.join(parent.worktree, path).replace('\\', '/')
David James8d201162013-10-11 17:03:19 -07001674 return relpath, worktree, gitdir, objdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001675
Mike Frysinger04122b72019-07-31 23:32:58 -04001676 @staticmethod
Mike Frysingera00c5f42021-02-25 18:26:31 -05001677 def _CheckLocalPath(path, dir_ok=False, cwd_dot_ok=False):
1678 """Verify |path| is reasonable for use in filesystem paths.
1679
Mike Frysingera29424e2021-02-25 21:53:49 -05001680 Used with <copyfile> & <linkfile> & <project> elements.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001681
1682 This only validates the |path| in isolation: it does not check against the
1683 current filesystem state. Thus it is suitable as a first-past in a parser.
1684
1685 It enforces a number of constraints:
1686 * No empty paths.
1687 * No "~" in paths.
1688 * No Unicode codepoints that filesystems might elide when normalizing.
1689 * No relative path components like "." or "..".
1690 * No absolute paths.
1691 * No ".git" or ".repo*" path components.
1692
1693 Args:
1694 path: The path name to validate.
1695 dir_ok: Whether |path| may force a directory (e.g. end in a /).
1696 cwd_dot_ok: Whether |path| may be just ".".
1697
1698 Returns:
1699 None if |path| is OK, a failure message otherwise.
1700 """
1701 if not path:
1702 return 'empty paths not allowed'
1703
Mike Frysinger04122b72019-07-31 23:32:58 -04001704 if '~' in path:
1705 return '~ not allowed (due to 8.3 filenames on Windows filesystems)'
1706
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001707 path_codepoints = set(path)
1708
Mike Frysinger04122b72019-07-31 23:32:58 -04001709 # Some filesystems (like Apple's HFS+) try to normalize Unicode codepoints
1710 # which means there are alternative names for ".git". Reject paths with
1711 # these in it as there shouldn't be any reasonable need for them here.
1712 # The set of codepoints here was cribbed from jgit's implementation:
1713 # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
1714 BAD_CODEPOINTS = {
1715 u'\u200C', # ZERO WIDTH NON-JOINER
1716 u'\u200D', # ZERO WIDTH JOINER
1717 u'\u200E', # LEFT-TO-RIGHT MARK
1718 u'\u200F', # RIGHT-TO-LEFT MARK
1719 u'\u202A', # LEFT-TO-RIGHT EMBEDDING
1720 u'\u202B', # RIGHT-TO-LEFT EMBEDDING
1721 u'\u202C', # POP DIRECTIONAL FORMATTING
1722 u'\u202D', # LEFT-TO-RIGHT OVERRIDE
1723 u'\u202E', # RIGHT-TO-LEFT OVERRIDE
1724 u'\u206A', # INHIBIT SYMMETRIC SWAPPING
1725 u'\u206B', # ACTIVATE SYMMETRIC SWAPPING
1726 u'\u206C', # INHIBIT ARABIC FORM SHAPING
1727 u'\u206D', # ACTIVATE ARABIC FORM SHAPING
1728 u'\u206E', # NATIONAL DIGIT SHAPES
1729 u'\u206F', # NOMINAL DIGIT SHAPES
1730 u'\uFEFF', # ZERO WIDTH NO-BREAK SPACE
1731 }
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001732 if BAD_CODEPOINTS & path_codepoints:
Mike Frysinger04122b72019-07-31 23:32:58 -04001733 # This message is more expansive than reality, but should be fine.
1734 return 'Unicode combining characters not allowed'
1735
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001736 # Reject newlines as there shouldn't be any legitmate use for them, they'll
1737 # be confusing to users, and they can easily break tools that expect to be
1738 # able to iterate over newline delimited lists. This even applies to our
1739 # own code like .repo/project.list.
1740 if {'\r', '\n'} & path_codepoints:
1741 return 'Newlines not allowed'
1742
Mike Frysinger04122b72019-07-31 23:32:58 -04001743 # Assume paths might be used on case-insensitive filesystems.
1744 path = path.lower()
1745
Mike Frysingerd9254592020-02-19 22:36:26 -05001746 # Split up the path by its components. We can't use os.path.sep exclusively
1747 # as some platforms (like Windows) will convert / to \ and that bypasses all
1748 # our constructed logic here. Especially since manifest authors only use
1749 # / in their paths.
1750 resep = re.compile(r'[/%s]' % re.escape(os.path.sep))
Mike Frysinger0458faa2021-03-10 23:35:44 -05001751 # Strip off trailing slashes as those only produce '' elements, and we use
1752 # parts to look for individual bad components.
1753 parts = resep.split(path.rstrip('/'))
Mike Frysingerd9254592020-02-19 22:36:26 -05001754
Mike Frysingerae625412020-02-10 17:10:03 -05001755 # Some people use src="." to create stable links to projects. Lets allow
1756 # that but reject all other uses of "." to keep things simple.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001757 if not cwd_dot_ok or parts != ['.']:
Mike Frysingerae625412020-02-10 17:10:03 -05001758 for part in set(parts):
1759 if part in {'.', '..', '.git'} or part.startswith('.repo'):
1760 return 'bad component: %s' % (part,)
Mike Frysinger04122b72019-07-31 23:32:58 -04001761
Mike Frysingera00c5f42021-02-25 18:26:31 -05001762 if not dir_ok and resep.match(path[-1]):
Mike Frysinger04122b72019-07-31 23:32:58 -04001763 return 'dirs not allowed'
1764
Mike Frysingerd9254592020-02-19 22:36:26 -05001765 # NB: The two abspath checks here are to handle platforms with multiple
1766 # filesystem path styles (e.g. Windows).
Mike Frysinger04122b72019-07-31 23:32:58 -04001767 norm = os.path.normpath(path)
Mike Frysingerd9254592020-02-19 22:36:26 -05001768 if (norm == '..' or
1769 (len(norm) >= 3 and norm.startswith('..') and resep.match(norm[0])) or
1770 os.path.isabs(norm) or
1771 norm.startswith('/')):
Mike Frysinger04122b72019-07-31 23:32:58 -04001772 return 'path cannot be outside'
1773
1774 @classmethod
1775 def _ValidateFilePaths(cls, element, src, dest):
1776 """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
1777
1778 We verify the path independent of any filesystem state as we won't have a
1779 checkout available to compare to. i.e. This is for parsing validation
1780 purposes only.
1781
1782 We'll do full/live sanity checking before we do the actual filesystem
1783 modifications in _CopyFile/_LinkFile/etc...
1784 """
1785 # |dest| is the file we write to or symlink we create.
1786 # It is relative to the top of the repo client checkout.
1787 msg = cls._CheckLocalPath(dest)
1788 if msg:
1789 raise ManifestInvalidPathError(
1790 '<%s> invalid "dest": %s: %s' % (element, dest, msg))
1791
1792 # |src| is the file we read from or path we point to for symlinks.
1793 # It is relative to the top of the git project checkout.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001794 is_linkfile = element == 'linkfile'
1795 msg = cls._CheckLocalPath(src, dir_ok=is_linkfile, cwd_dot_ok=is_linkfile)
Mike Frysinger04122b72019-07-31 23:32:58 -04001796 if msg:
1797 raise ManifestInvalidPathError(
1798 '<%s> invalid "src": %s: %s' % (element, src, msg))
1799
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001800 def _ParseCopyFile(self, project, node):
1801 src = self._reqatt(node, 'src')
1802 dest = self._reqatt(node, 'dest')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001803 if not self.IsMirror:
1804 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001805 # dest is relative to the top of the tree.
1806 # We only validate paths if we actually plan to process them.
1807 self._ValidateFilePaths('copyfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001808 project.AddCopyFile(src, dest, self.topdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001809
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001810 def _ParseLinkFile(self, project, node):
1811 src = self._reqatt(node, 'src')
1812 dest = self._reqatt(node, 'dest')
1813 if not self.IsMirror:
1814 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001815 # dest is relative to the top of the tree.
1816 # We only validate paths if we actually plan to process them.
1817 self._ValidateFilePaths('linkfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001818 project.AddLinkFile(src, dest, self.topdir)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001819
Jack Neus6ea0cae2021-07-20 20:52:33 +00001820 def _ParseAnnotation(self, element, node):
James W. Mills24c13082012-04-12 15:04:13 -05001821 name = self._reqatt(node, 'name')
1822 value = self._reqatt(node, 'value')
1823 try:
1824 keep = self._reqatt(node, 'keep').lower()
1825 except ManifestParseError:
1826 keep = "true"
1827 if keep != "true" and keep != "false":
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301828 raise ManifestParseError('optional "keep" attribute must be '
David Pursehouseabdf7502020-02-12 14:58:39 +09001829 '"true" or "false"')
Jack Neus6ea0cae2021-07-20 20:52:33 +00001830 element.AddAnnotation(name, value, keep)
James W. Mills24c13082012-04-12 15:04:13 -05001831
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001832 def _get_remote(self, node):
1833 name = node.getAttribute('remote')
1834 if not name:
1835 return None
1836
1837 v = self._remotes.get(name)
1838 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301839 raise ManifestParseError("remote %s not defined in %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001840 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001841 return v
1842
1843 def _reqatt(self, node, attname):
1844 """
1845 reads a required attribute from the node.
1846 """
1847 v = node.getAttribute(attname)
1848 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301849 raise ManifestParseError("no %s in <%s> within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001850 (attname, node.nodeName, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001851 return v
Julien Camperguedd654222014-01-09 16:21:37 +01001852
1853 def projectsDiff(self, manifest):
1854 """return the projects differences between two manifests.
1855
1856 The diff will be from self to given manifest.
1857
1858 """
1859 fromProjects = self.paths
1860 toProjects = manifest.paths
1861
Anthony King7446c592014-05-06 09:19:39 +01001862 fromKeys = sorted(fromProjects.keys())
1863 toKeys = sorted(toProjects.keys())
Julien Camperguedd654222014-01-09 16:21:37 +01001864
1865 diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
1866
1867 for proj in fromKeys:
David Pursehouseeeff3532020-02-12 11:24:10 +09001868 if proj not in toKeys:
Julien Camperguedd654222014-01-09 16:21:37 +01001869 diff['removed'].append(fromProjects[proj])
1870 else:
1871 fromProj = fromProjects[proj]
1872 toProj = toProjects[proj]
1873 try:
1874 fromRevId = fromProj.GetCommitRevisionId()
1875 toRevId = toProj.GetCommitRevisionId()
1876 except ManifestInvalidRevisionError:
1877 diff['unreachable'].append((fromProj, toProj))
1878 else:
1879 if fromRevId != toRevId:
1880 diff['changed'].append((fromProj, toProj))
1881 toKeys.remove(proj)
1882
1883 for proj in toKeys:
1884 diff['added'].append(toProjects[proj])
1885
1886 return diff
Simran Basib9a1b732015-08-20 12:19:28 -07001887
1888
1889class GitcManifest(XmlManifest):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001890 """Parser for GitC (git-in-the-cloud) manifests."""
Simran Basib9a1b732015-08-20 12:19:28 -07001891
David Pursehousee5913ae2020-02-12 13:56:59 +09001892 def _ParseProject(self, node, parent=None):
Simran Basib9a1b732015-08-20 12:19:28 -07001893 """Override _ParseProject and add support for GITC specific attributes."""
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001894 return super()._ParseProject(
Simran Basib9a1b732015-08-20 12:19:28 -07001895 node, parent=parent, old_revision=node.getAttribute('old-revision'))
1896
1897 def _output_manifest_project_extras(self, p, e):
1898 """Output GITC Specific Project attributes"""
1899 if p.old_revision:
Stefan Beller66851062016-06-17 16:40:08 -07001900 e.setAttribute('old-revision', str(p.old_revision))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001901
1902
1903class RepoClient(XmlManifest):
1904 """Manages a repo client checkout."""
1905
LaMont Jonescc879a92021-11-18 22:40:18 +00001906 def __init__(self, repodir, manifest_file=None, submanifest_path='', **kwargs):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001907 self.isGitcClient = False
LaMont Jonescc879a92021-11-18 22:40:18 +00001908 submanifest_path = submanifest_path or ''
1909 if submanifest_path:
1910 self._CheckLocalPath(submanifest_path)
1911 prefix = os.path.join(repodir, SUBMANIFEST_DIR, submanifest_path)
1912 else:
1913 prefix = repodir
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001914
LaMont Jonescc879a92021-11-18 22:40:18 +00001915 if os.path.exists(os.path.join(prefix, LOCAL_MANIFEST_NAME)):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001916 print('error: %s is not supported; put local manifests in `%s` instead' %
LaMont Jonescc879a92021-11-18 22:40:18 +00001917 (LOCAL_MANIFEST_NAME, os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME)),
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001918 file=sys.stderr)
1919 sys.exit(1)
1920
1921 if manifest_file is None:
LaMont Jonescc879a92021-11-18 22:40:18 +00001922 manifest_file = os.path.join(prefix, MANIFEST_FILE_NAME)
1923 local_manifests = os.path.abspath(os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME))
1924 super().__init__(repodir, manifest_file, local_manifests,
1925 submanifest_path=submanifest_path, **kwargs)
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001926
1927 # TODO: Completely separate manifest logic out of the client.
1928 self.manifest = self
1929
1930
1931class GitcClient(RepoClient, GitcManifest):
1932 """Manages a GitC client checkout."""
1933
1934 def __init__(self, repodir, gitc_client_name):
1935 """Initialize the GitcManifest object."""
1936 self.gitc_client_name = gitc_client_name
1937 self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
1938 gitc_client_name)
1939
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001940 super().__init__(repodir, os.path.join(self.gitc_client_dir, '.manifest'))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001941 self.isGitcClient = True