blob: 022cad20545b92480943ddb2cb308c5b8aad06c3 [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 Jonescc879a92021-11-18 22:40:18 +0000246 rc = self.repo_client = RepoClient(
LaMont Jones5d3291d2022-03-23 19:03:02 +0000247 parent.repodir, manifestFile, parent_groups=','.join(groups) or '',
LaMont Jonescc879a92021-11-18 22:40:18 +0000248 submanifest_path=self.relpath, outer_client=outer_client)
249
250 self.present = os.path.exists(os.path.join(self.repo_client.subdir,
251 MANIFEST_FILE_NAME))
252
253 def __eq__(self, other):
254 if not isinstance(other, _XmlSubmanifest):
255 return False
256 return (
257 self.name == other.name and
258 self.remote == other.remote and
259 self.project == other.project and
260 self.revision == other.revision and
261 self.manifestName == other.manifestName and
262 self.groups == other.groups and
263 self.path == other.path and
264 sorted(self.annotations) == sorted(other.annotations))
265
266 def __ne__(self, other):
267 return not self.__eq__(other)
268
269 def ToSubmanifestSpec(self, root):
270 """Return a SubmanifestSpec object, populating attributes"""
271 mp = root.manifestProject
272 remote = root.remotes[self.remote or root.default.remote.name]
273 # If a project was given, generate the url from the remote and project.
274 # If not, use this manifestProject's url.
275 if self.project:
276 manifestUrl = remote.ToRemoteSpec(self.project).url
277 else:
278 manifestUrl = mp.GetRemote(mp.remote.name).url
279 manifestName = self.manifestName or 'default.xml'
280 revision = self.revision or self.name
281 path = self.path or revision.split('/')[-1]
282 groups = self.groups or []
283
284 return SubmanifestSpec(self.name, manifestUrl, manifestName, revision, path,
285 groups)
286
287 @property
288 def relpath(self):
289 """The path of this submanifest relative to the parent manifest."""
290 revision = self.revision or self.name
291 return self.path or revision.split('/')[-1]
292
293 def GetGroupsStr(self):
294 """Returns the `groups` given for this submanifest."""
295 if self.groups:
296 return ','.join(self.groups)
297 return ''
298
299 def AddAnnotation(self, name, value, keep):
300 """Add annotations to the submanifest."""
301 self.annotations.append(Annotation(name, value, keep))
302
303
304class SubmanifestSpec:
305 """The submanifest element, with all fields expanded."""
306
307 def __init__(self,
308 name,
309 manifestUrl,
310 manifestName,
311 revision,
312 path,
313 groups):
314 self.name = name
315 self.manifestUrl = manifestUrl
316 self.manifestName = manifestName
317 self.revision = revision
318 self.path = path
319 self.groups = groups or []
320
321
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700322class XmlManifest(object):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700323 """manages the repo configuration file"""
324
LaMont Jonescc879a92021-11-18 22:40:18 +0000325 def __init__(self, repodir, manifest_file, local_manifests=None,
326 outer_client=None, parent_groups='', submanifest_path=''):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400327 """Initialize.
328
329 Args:
330 repodir: Path to the .repo/ dir for holding all internal checkout state.
331 It must be in the top directory of the repo client checkout.
332 manifest_file: Full path to the manifest file to parse. This will usually
333 be |repodir|/|MANIFEST_FILE_NAME|.
334 local_manifests: Full path to the directory of local override manifests.
335 This will usually be |repodir|/|LOCAL_MANIFESTS_DIR_NAME|.
LaMont Jonescc879a92021-11-18 22:40:18 +0000336 outer_client: RepoClient of the outertree.
337 parent_groups: a string, the groups to apply to this projects.
338 submanifest_path: The submanifest root relative to the repo root.
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400339 """
340 # TODO(vapier): Move this out of this class.
341 self.globalConfig = GitConfig.ForUser()
342
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700343 self.repodir = os.path.abspath(repodir)
LaMont Jonescc879a92021-11-18 22:40:18 +0000344 self._CheckLocalPath(submanifest_path)
345 self.topdir = os.path.join(os.path.dirname(self.repodir), submanifest_path)
LaMont Jones5d3291d2022-03-23 19:03:02 +0000346 if manifest_file != os.path.abspath(manifest_file):
347 raise ManifestParseError('manifest_file must be abspath')
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400348 self.manifestFile = manifest_file
349 self.local_manifests = local_manifests
Basil Gelloc7453502018-05-25 20:23:52 +0300350 self._load_local_manifests = True
LaMont Jonescc879a92021-11-18 22:40:18 +0000351 self.parent_groups = parent_groups
352
353 if outer_client and self.isGitcClient:
354 raise ManifestParseError('Multi-manifest is incompatible with `gitc-init`')
355
356 if submanifest_path and not outer_client:
357 # If passing a submanifest_path, there must be an outer_client.
358 raise ManifestParseError(f'Bad call to {self.__class__.__name__}')
359
360 # If self._outer_client is None, this is not a checkout that supports
361 # multi-tree.
362 self._outer_client = outer_client or self
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700363
LaMont Jones9b72cf22022-03-29 21:54:22 +0000364 self.repoProject = RepoProject(self, 'repo',
David Pursehouseabdf7502020-02-12 14:58:39 +0900365 gitdir=os.path.join(repodir, 'repo/.git'),
366 worktree=os.path.join(repodir, 'repo'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700367
LaMont Jonescc879a92021-11-18 22:40:18 +0000368 mp = self.SubmanifestProject(self.path_prefix)
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500369 self.manifestProject = mp
370
371 # This is a bit hacky, but we're in a chicken & egg situation: all the
372 # normal repo settings live in the manifestProject which we just setup
373 # above, so we couldn't easily query before that. We assume Project()
374 # init doesn't care if this changes afterwards.
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000375 if os.path.exists(mp.gitdir) and mp.use_worktree:
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500376 mp.use_git_worktrees = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700377
378 self._Unload()
379
Basil Gelloc7453502018-05-25 20:23:52 +0300380 def Override(self, name, load_local_manifests=True):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700381 """Use a different manifest, just for the current instantiation.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700382 """
Basil Gelloc7453502018-05-25 20:23:52 +0300383 path = None
384
385 # Look for a manifest by path in the filesystem (including the cwd).
386 if not load_local_manifests:
387 local_path = os.path.abspath(name)
388 if os.path.isfile(local_path):
389 path = local_path
390
391 # Look for manifests by name from the manifests repo.
392 if path is None:
393 path = os.path.join(self.manifestProject.worktree, name)
394 if not os.path.isfile(path):
395 raise ManifestParseError('manifest %s not found' % name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700396
397 old = self.manifestFile
398 try:
Basil Gelloc7453502018-05-25 20:23:52 +0300399 self._load_local_manifests = load_local_manifests
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700400 self.manifestFile = path
401 self._Unload()
402 self._Load()
403 finally:
404 self.manifestFile = old
405
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700406 def Link(self, name):
407 """Update the repo metadata to use a different manifest.
408 """
409 self.Override(name)
410
Mike Frysingera269b1c2020-02-21 00:49:41 -0500411 # Old versions of repo would generate symlinks we need to clean up.
Mike Frysinger9d96f582021-09-28 11:27:24 -0400412 platform_utils.remove(self.manifestFile, missing_ok=True)
Mike Frysingera269b1c2020-02-21 00:49:41 -0500413 # This file is interpreted as if it existed inside the manifest repo.
414 # That allows us to use <include> with the relative file name.
415 with open(self.manifestFile, 'w') as fp:
416 fp.write("""<?xml version="1.0" encoding="UTF-8"?>
417<!--
418DO NOT EDIT THIS FILE! It is generated by repo and changes will be discarded.
419If you want to use a different manifest, use `repo init -m <file>` instead.
420
421If you want to customize your checkout by overriding manifest settings, use
422the local_manifests/ directory instead.
423
424For more information on repo manifests, check out:
425https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
426-->
427<manifest>
428 <include name="%s" />
429</manifest>
430""" % (name,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700431
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800432 def _RemoteToXml(self, r, doc, root):
433 e = doc.createElement('remote')
434 root.appendChild(e)
435 e.setAttribute('name', r.name)
436 e.setAttribute('fetch', r.fetchUrl)
Steve Raed6480452016-08-10 15:00:00 -0700437 if r.pushUrl is not None:
438 e.setAttribute('pushurl', r.pushUrl)
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700439 if r.remoteAlias is not None:
440 e.setAttribute('alias', r.remoteAlias)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800441 if r.reviewUrl is not None:
442 e.setAttribute('review', r.reviewUrl)
Anthony King36ea2fb2014-05-06 11:54:01 +0100443 if r.revision is not None:
444 e.setAttribute('revision', r.revision)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800445
Jack Neus6ea0cae2021-07-20 20:52:33 +0000446 for a in r.annotations:
447 if a.keep == 'true':
448 ae = doc.createElement('annotation')
449 ae.setAttribute('name', a.name)
450 ae.setAttribute('value', a.value)
451 e.appendChild(ae)
452
LaMont Jonescc879a92021-11-18 22:40:18 +0000453 def _SubmanifestToXml(self, r, doc, root):
454 """Generate XML <submanifest/> node."""
455 e = doc.createElement('submanifest')
456 root.appendChild(e)
457 e.setAttribute('name', r.name)
458 if r.remote is not None:
459 e.setAttribute('remote', r.remote)
460 if r.project is not None:
461 e.setAttribute('project', r.project)
462 if r.manifestName is not None:
463 e.setAttribute('manifest-name', r.manifestName)
464 if r.revision is not None:
465 e.setAttribute('revision', r.revision)
466 if r.path is not None:
467 e.setAttribute('path', r.path)
468 if r.groups:
469 e.setAttribute('groups', r.GetGroupsStr())
470
471 for a in r.annotations:
472 if a.keep == 'true':
473 ae = doc.createElement('annotation')
474 ae.setAttribute('name', a.name)
475 ae.setAttribute('value', a.value)
476 e.appendChild(ae)
477
Mike Frysinger51e39d52020-12-04 05:32:06 -0500478 def _ParseList(self, field):
479 """Parse fields that contain flattened lists.
480
481 These are whitespace & comma separated. Empty elements will be discarded.
482 """
483 return [x for x in re.split(r'[,\s]+', field) if x]
Josh Triplett884a3872014-06-12 14:57:29 -0700484
Mike Frysinger23411d32020-09-02 04:31:10 -0400485 def ToXml(self, peg_rev=False, peg_rev_upstream=True, peg_rev_dest_branch=True, groups=None):
486 """Return the current manifest XML."""
Colin Cross5acde752012-03-28 20:15:45 -0700487 mp = self.manifestProject
488
Dan Willemsen5ea32d12015-09-08 13:27:20 -0700489 if groups is None:
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000490 groups = mp.manifest_groups
Matt Gumbel0c635bb2012-12-21 10:14:53 -0800491 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -0500492 groups = self._ParseList(groups)
Colin Cross5acde752012-03-28 20:15:45 -0700493
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800494 doc = xml.dom.minidom.Document()
495 root = doc.createElement('manifest')
LaMont Jonescc879a92021-11-18 22:40:18 +0000496 if self.is_submanifest:
497 root.setAttribute('path', self.path_prefix)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800498 doc.appendChild(root)
499
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700500 # Save out the notice. There's a little bit of work here to give it the
501 # right whitespace, which assumes that the notice is automatically indented
502 # by 4 by minidom.
503 if self.notice:
504 notice_element = root.appendChild(doc.createElement('notice'))
505 notice_lines = self.notice.splitlines()
David Pursehouse54a4e602020-02-12 14:31:05 +0900506 indented_notice = ('\n'.join(" " * 4 + line for line in notice_lines))[4:]
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700507 notice_element.appendChild(doc.createTextNode(indented_notice))
508
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800509 d = self.default
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800510
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530511 for r in sorted(self.remotes):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800512 self._RemoteToXml(self.remotes[r], doc, root)
513 if self.remotes:
514 root.appendChild(doc.createTextNode(''))
515
516 have_default = False
517 e = doc.createElement('default')
518 if d.remote:
519 have_default = True
520 e.setAttribute('remote', d.remote.name)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700521 if d.revisionExpr:
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800522 have_default = True
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700523 e.setAttribute('revision', d.revisionExpr)
Simon Ruggier7e59de22015-07-24 12:50:06 +0200524 if d.destBranchExpr:
525 have_default = True
526 e.setAttribute('dest-branch', d.destBranchExpr)
Nasser Grainawida403412018-05-04 12:53:29 -0600527 if d.upstreamExpr:
528 have_default = True
529 e.setAttribute('upstream', d.upstreamExpr)
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700530 if d.sync_j > 1:
531 have_default = True
532 e.setAttribute('sync-j', '%d' % d.sync_j)
Anatol Pomazau79770d22012-04-20 14:41:59 -0700533 if d.sync_c:
534 have_default = True
535 e.setAttribute('sync-c', 'true')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800536 if d.sync_s:
537 have_default = True
538 e.setAttribute('sync-s', 'true')
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900539 if not d.sync_tags:
540 have_default = True
541 e.setAttribute('sync-tags', 'false')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800542 if have_default:
543 root.appendChild(e)
544 root.appendChild(doc.createTextNode(''))
545
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700546 if self._manifest_server:
547 e = doc.createElement('manifest-server')
548 e.setAttribute('url', self._manifest_server)
549 root.appendChild(e)
550 root.appendChild(doc.createTextNode(''))
551
LaMont Jonescc879a92021-11-18 22:40:18 +0000552 for r in sorted(self.submanifests):
553 self._SubmanifestToXml(self.submanifests[r], doc, root)
554 if self.submanifests:
555 root.appendChild(doc.createTextNode(''))
556
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800557 def output_projects(parent, parent_node, projects):
David James8d201162013-10-11 17:03:19 -0700558 for project_name in projects:
559 for project in self._projects[project_name]:
560 output_project(parent, parent_node, project)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800561
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800562 def output_project(parent, parent_node, p):
Colin Cross5acde752012-03-28 20:15:45 -0700563 if not p.MatchesGroups(groups):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800564 return
565
566 name = p.name
567 relpath = p.relpath
568 if parent:
569 name = self._UnjoinName(parent.name, name)
570 relpath = self._UnjoinRelpath(parent.relpath, relpath)
Colin Cross5acde752012-03-28 20:15:45 -0700571
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800572 e = doc.createElement('project')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800573 parent_node.appendChild(e)
574 e.setAttribute('name', name)
575 if relpath != name:
576 e.setAttribute('path', relpath)
Conley Owensa17d7af2013-10-16 14:38:09 -0700577 remoteName = None
578 if d.remote:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700579 remoteName = d.remote.name
580 if not d.remote or p.remote.orig_name != remoteName:
581 remoteName = p.remote.orig_name
Anthony King36ea2fb2014-05-06 11:54:01 +0100582 e.setAttribute('remote', remoteName)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800583 if peg_rev:
584 if self.IsMirror:
Brian Harring14a66742012-09-28 20:21:57 -0700585 value = p.bare_git.rev_parse(p.revisionExpr + '^0')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800586 else:
Brian Harring14a66742012-09-28 20:21:57 -0700587 value = p.work_git.rev_parse(HEAD + '^0')
588 e.setAttribute('revision', value)
Conley Owens551dfec2015-07-10 14:54:54 -0700589 if peg_rev_upstream:
590 if p.upstream:
591 e.setAttribute('upstream', p.upstream)
592 elif value != p.revisionExpr:
593 # Only save the origin if the origin is not a sha1, and the default
594 # isn't our value
595 e.setAttribute('upstream', p.revisionExpr)
Sean McAllisteraf908cb2020-04-20 08:41:58 -0600596
597 if peg_rev_dest_branch:
598 if p.dest_branch:
599 e.setAttribute('dest-branch', p.dest_branch)
600 elif value != p.revisionExpr:
601 e.setAttribute('dest-branch', p.revisionExpr)
602
Anthony King36ea2fb2014-05-06 11:54:01 +0100603 else:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700604 revision = self.remotes[p.remote.orig_name].revision or d.revisionExpr
Anthony King36ea2fb2014-05-06 11:54:01 +0100605 if not revision or revision != p.revisionExpr:
606 e.setAttribute('revision', p.revisionExpr)
Raman Tennetib5c5a5e2021-02-06 09:44:15 -0800607 elif p.revisionId:
608 e.setAttribute('revision', p.revisionId)
Nasser Grainawida403412018-05-04 12:53:29 -0600609 if (p.upstream and (p.upstream != p.revisionExpr or
610 p.upstream != d.upstreamExpr)):
Mani Chandel7a91d512014-07-24 16:27:08 +0530611 e.setAttribute('upstream', p.upstream)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800612
Simon Ruggier7e59de22015-07-24 12:50:06 +0200613 if p.dest_branch and p.dest_branch != d.destBranchExpr:
614 e.setAttribute('dest-branch', p.dest_branch)
615
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800616 for c in p.copyfiles:
617 ce = doc.createElement('copyfile')
618 ce.setAttribute('src', c.src)
619 ce.setAttribute('dest', c.dest)
620 e.appendChild(ce)
621
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500622 for l in p.linkfiles:
623 le = doc.createElement('linkfile')
624 le.setAttribute('src', l.src)
625 le.setAttribute('dest', l.dest)
626 e.appendChild(le)
627
Conley Owensbb1b5f52012-08-13 13:11:18 -0700628 default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
Dmitry Fink17f85ea2012-08-06 14:52:29 -0700629 egroups = [g for g in p.groups if g not in default_groups]
Conley Owens971de8e2012-04-16 10:36:08 -0700630 if egroups:
631 e.setAttribute('groups', ','.join(egroups))
Colin Cross5acde752012-03-28 20:15:45 -0700632
James W. Mills24c13082012-04-12 15:04:13 -0500633 for a in p.annotations:
634 if a.keep == "true":
635 ae = doc.createElement('annotation')
636 ae.setAttribute('name', a.name)
637 ae.setAttribute('value', a.value)
638 e.appendChild(ae)
639
Anatol Pomazau79770d22012-04-20 14:41:59 -0700640 if p.sync_c:
641 e.setAttribute('sync-c', 'true')
642
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800643 if p.sync_s:
644 e.setAttribute('sync-s', 'true')
645
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900646 if not p.sync_tags:
647 e.setAttribute('sync-tags', 'false')
648
Dan Willemsen88409222015-08-17 15:29:10 -0700649 if p.clone_depth:
650 e.setAttribute('clone-depth', str(p.clone_depth))
651
Simran Basib9a1b732015-08-20 12:19:28 -0700652 self._output_manifest_project_extras(p, e)
653
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800654 if p.subprojects:
David James8d201162013-10-11 17:03:19 -0700655 subprojects = set(subp.name for subp in p.subprojects)
656 output_projects(p, e, list(sorted(subprojects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800657
David James8d201162013-10-11 17:03:19 -0700658 projects = set(p.name for p in self._paths.values() if not p.parent)
659 output_projects(None, root, list(sorted(projects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800660
Doug Anderson37282b42011-03-04 11:54:18 -0800661 if self._repo_hooks_project:
662 root.appendChild(doc.createTextNode(''))
663 e = doc.createElement('repo-hooks')
664 e.setAttribute('in-project', self._repo_hooks_project.name)
665 e.setAttribute('enabled-list',
666 ' '.join(self._repo_hooks_project.enabled_repo_hooks))
667 root.appendChild(e)
668
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800669 if self._superproject:
670 root.appendChild(doc.createTextNode(''))
671 e = doc.createElement('superproject')
672 e.setAttribute('name', self._superproject['name'])
673 remoteName = None
674 if d.remote:
675 remoteName = d.remote.name
676 remote = self._superproject.get('remote')
677 if not d.remote or remote.orig_name != remoteName:
678 remoteName = remote.orig_name
679 e.setAttribute('remote', remoteName)
Xin Lie0b16a22021-09-26 23:20:32 -0700680 revision = remote.revision or d.revisionExpr
681 if not revision or revision != self._superproject['revision']:
682 e.setAttribute('revision', self._superproject['revision'])
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800683 root.appendChild(e)
684
Raman Tenneti993af5e2021-05-12 12:00:31 -0700685 if self._contactinfo.bugurl != Wrapper().BUG_URL:
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700686 root.appendChild(doc.createTextNode(''))
687 e = doc.createElement('contactinfo')
Raman Tenneti993af5e2021-05-12 12:00:31 -0700688 e.setAttribute('bugurl', self._contactinfo.bugurl)
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700689 root.appendChild(e)
690
Mike Frysinger23411d32020-09-02 04:31:10 -0400691 return doc
692
693 def ToDict(self, **kwargs):
694 """Return the current manifest as a dictionary."""
695 # Elements that may only appear once.
696 SINGLE_ELEMENTS = {
697 'notice',
698 'default',
699 'manifest-server',
700 'repo-hooks',
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800701 'superproject',
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700702 'contactinfo',
Mike Frysinger23411d32020-09-02 04:31:10 -0400703 }
704 # Elements that may be repeated.
705 MULTI_ELEMENTS = {
706 'remote',
707 'remove-project',
708 'project',
709 'extend-project',
710 'include',
LaMont Jonescc879a92021-11-18 22:40:18 +0000711 'submanifest',
Mike Frysinger23411d32020-09-02 04:31:10 -0400712 # These are children of 'project' nodes.
713 'annotation',
714 'project',
715 'copyfile',
716 'linkfile',
717 }
718
719 doc = self.ToXml(**kwargs)
720 ret = {}
721
722 def append_children(ret, node):
723 for child in node.childNodes:
724 if child.nodeType == xml.dom.Node.ELEMENT_NODE:
725 attrs = child.attributes
726 element = dict((attrs.item(i).localName, attrs.item(i).value)
727 for i in range(attrs.length))
728 if child.nodeName in SINGLE_ELEMENTS:
729 ret[child.nodeName] = element
730 elif child.nodeName in MULTI_ELEMENTS:
731 ret.setdefault(child.nodeName, []).append(element)
732 else:
733 raise ManifestParseError('Unhandled element "%s"' % (child.nodeName,))
734
735 append_children(element, child)
736
737 append_children(ret, doc.firstChild)
738
739 return ret
740
741 def Save(self, fd, **kwargs):
742 """Write the current manifest out to the given file descriptor."""
743 doc = self.ToXml(**kwargs)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800744 doc.writexml(fd, '', ' ', '\n', 'UTF-8')
745
Simran Basib9a1b732015-08-20 12:19:28 -0700746 def _output_manifest_project_extras(self, p, e):
747 """Manifests can modify e if they support extra project attributes."""
Simran Basib9a1b732015-08-20 12:19:28 -0700748
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700749 @property
LaMont Jonescc879a92021-11-18 22:40:18 +0000750 def is_multimanifest(self):
751 """Whether this is a multimanifest checkout"""
752 return bool(self.outer_client.submanifests)
753
754 @property
755 def is_submanifest(self):
756 """Whether this manifest is a submanifest"""
757 return self._outer_client and self._outer_client != self
758
759 @property
760 def outer_client(self):
761 """The instance of the outermost manifest client"""
762 self._Load()
763 return self._outer_client
764
765 @property
766 def all_manifests(self):
767 """Generator yielding all (sub)manifests."""
768 self._Load()
769 outer = self._outer_client
770 yield outer
771 for tree in outer.all_children:
772 yield tree
773
774 @property
775 def all_children(self):
776 """Generator yielding all child submanifests."""
777 self._Load()
778 for child in self._submanifests.values():
779 if child.repo_client:
780 yield child.repo_client
781 for tree in child.repo_client.all_children:
782 yield tree
783
784 @property
785 def path_prefix(self):
786 """The path of this submanifest, relative to the outermost manifest."""
787 if not self._outer_client or self == self._outer_client:
788 return ''
789 return os.path.relpath(self.topdir, self._outer_client.topdir)
790
791 @property
792 def all_paths(self):
793 """All project paths for all (sub)manifests. See `paths`."""
794 ret = {}
795 for tree in self.all_manifests:
796 prefix = tree.path_prefix
797 ret.update({os.path.join(prefix, k): v for k, v in tree.paths.items()})
798 return ret
799
800 @property
801 def all_projects(self):
802 """All projects for all (sub)manifests. See `projects`."""
803 return list(itertools.chain.from_iterable(x._paths.values() for x in self.all_manifests))
804
805 @property
David James8d201162013-10-11 17:03:19 -0700806 def paths(self):
LaMont Jonescc879a92021-11-18 22:40:18 +0000807 """Return all paths for this manifest.
808
809 Return:
810 A dictionary of {path: Project()}. `path` is relative to this manifest.
811 """
David James8d201162013-10-11 17:03:19 -0700812 self._Load()
813 return self._paths
814
815 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700816 def projects(self):
LaMont Jonescc879a92021-11-18 22:40:18 +0000817 """Return a list of all Projects in this manifest."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700818 self._Load()
Anthony Kingd58bfe52014-05-05 23:30:49 +0100819 return list(self._paths.values())
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700820
821 @property
822 def remotes(self):
823 self._Load()
824 return self._remotes
825
826 @property
827 def default(self):
828 self._Load()
829 return self._default
830
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800831 @property
LaMont Jonescc879a92021-11-18 22:40:18 +0000832 def submanifests(self):
833 """All submanifests in this manifest."""
834 self._Load()
835 return self._submanifests
836
837 @property
Doug Anderson37282b42011-03-04 11:54:18 -0800838 def repo_hooks_project(self):
839 self._Load()
840 return self._repo_hooks_project
841
842 @property
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800843 def superproject(self):
844 self._Load()
845 return self._superproject
846
847 @property
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700848 def contactinfo(self):
849 self._Load()
850 return self._contactinfo
851
852 @property
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700853 def notice(self):
854 self._Load()
855 return self._notice
856
857 @property
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700858 def manifest_server(self):
859 self._Load()
Shawn O. Pearce34fb20f2011-11-30 13:41:02 -0800860 return self._manifest_server
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700861
862 @property
Xin Lid79a4bc2020-05-20 16:03:45 -0700863 def CloneBundle(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000864 clone_bundle = self.manifestProject.clone_bundle
Xin Lid79a4bc2020-05-20 16:03:45 -0700865 if clone_bundle is None:
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000866 return False if self.manifestProject.partial_clone else True
Xin Lid79a4bc2020-05-20 16:03:45 -0700867 else:
868 return clone_bundle
869
870 @property
Xin Li745be2e2019-06-03 11:24:30 -0700871 def CloneFilter(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000872 if self.manifestProject.partial_clone:
873 return self.manifestProject.clone_filter
Xin Li745be2e2019-06-03 11:24:30 -0700874 return None
875
876 @property
Raman Tennetif32f2432021-04-12 20:57:25 -0700877 def PartialCloneExclude(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000878 exclude = self.manifest.manifestProject.partial_clone_exclude or ''
Raman Tennetif32f2432021-04-12 20:57:25 -0700879 return set(x.strip() for x in exclude.split(','))
880
881 @property
Michael Kellyc34b91c2021-07-02 09:25:48 -0700882 def UseLocalManifests(self):
883 return self._load_local_manifests
884
885 def SetUseLocalManifests(self, value):
886 self._load_local_manifests = value
887
888 @property
Raman Tennetifeb28912021-05-02 19:47:29 -0700889 def HasLocalManifests(self):
890 return self._load_local_manifests and self.local_manifests
891
LaMont Jones87cce682022-02-14 17:48:31 +0000892 def IsFromLocalManifest(self, project):
LaMont Jonescc879a92021-11-18 22:40:18 +0000893 """Is the project from a local manifest?"""
LaMont Jones87cce682022-02-14 17:48:31 +0000894 return any(x.startswith(LOCAL_MANIFEST_GROUP_PREFIX)
895 for x in project.groups)
896
Raman Tennetifeb28912021-05-02 19:47:29 -0700897 @property
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800898 def IsMirror(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000899 return self.manifestProject.mirror
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800900
Julien Campergue335f5ef2013-10-16 11:02:35 +0200901 @property
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500902 def UseGitWorktrees(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000903 return self.manifestProject.use_worktree
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500904
905 @property
Julien Campergue335f5ef2013-10-16 11:02:35 +0200906 def IsArchive(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000907 return self.manifestProject.archive
Julien Campergue335f5ef2013-10-16 11:02:35 +0200908
Martin Kellye4e94d22017-03-21 16:05:12 -0700909 @property
910 def HasSubmodules(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000911 return self.manifestProject.submodules
Martin Kellye4e94d22017-03-21 16:05:12 -0700912
XD Trol630876f2022-01-17 23:29:04 +0800913 @property
914 def EnableGitLfs(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000915 return self.manifestProject.git_lfs
XD Trol630876f2022-01-17 23:29:04 +0800916
LaMont Jonescc879a92021-11-18 22:40:18 +0000917 def FindManifestByPath(self, path):
918 """Returns the manifest containing path."""
919 path = os.path.abspath(path)
920 manifest = self._outer_client or self
921 old = None
922 while manifest._submanifests and manifest != old:
923 old = manifest
924 for name in manifest._submanifests:
925 tree = manifest._submanifests[name]
926 if path.startswith(tree.repo_client.manifest.topdir):
927 manifest = tree.repo_client
928 break
929 return manifest
930
931 @property
932 def subdir(self):
933 """Returns the path for per-submanifest objects for this manifest."""
934 return self.SubmanifestInfoDir(self.path_prefix)
935
936 def SubmanifestInfoDir(self, submanifest_path, object_path=''):
937 """Return the path to submanifest-specific info for a submanifest.
938
939 Return the full path of the directory in which to put per-manifest objects.
940
941 Args:
942 submanifest_path: a string, the path of the submanifest, relative to the
943 outermost topdir. If empty, then repodir is returned.
944 object_path: a string, relative path to append to the submanifest info
945 directory path.
946 """
947 if submanifest_path:
948 return os.path.join(self.repodir, SUBMANIFEST_DIR, submanifest_path,
949 object_path)
950 else:
951 return os.path.join(self.repodir, object_path)
952
953 def SubmanifestProject(self, submanifest_path):
954 """Return a manifestProject for a submanifest."""
955 subdir = self.SubmanifestInfoDir(submanifest_path)
LaMont Jones9b72cf22022-03-29 21:54:22 +0000956 mp = ManifestProject(self, 'manifests',
957 gitdir=os.path.join(subdir, 'manifests.git'),
958 worktree=os.path.join(subdir, 'manifests'))
LaMont Jonescc879a92021-11-18 22:40:18 +0000959 return mp
960
Raman Tenneti080877e2021-03-09 15:19:06 -0800961 def GetDefaultGroupsStr(self):
962 """Returns the default group string for the platform."""
963 return 'default,platform-' + platform.system().lower()
964
965 def GetGroupsStr(self):
966 """Returns the manifest group string that should be synced."""
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000967 groups = self.manifestProject.manifest_groups
Raman Tenneti080877e2021-03-09 15:19:06 -0800968 if not groups:
969 groups = self.GetDefaultGroupsStr()
970 return groups
971
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700972 def _Unload(self):
973 self._loaded = False
974 self._projects = {}
David James8d201162013-10-11 17:03:19 -0700975 self._paths = {}
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700976 self._remotes = {}
977 self._default = None
LaMont Jonescc879a92021-11-18 22:40:18 +0000978 self._submanifests = {}
Doug Anderson37282b42011-03-04 11:54:18 -0800979 self._repo_hooks_project = None
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800980 self._superproject = {}
Raman Tenneti993af5e2021-05-12 12:00:31 -0700981 self._contactinfo = ContactInfo(Wrapper().BUG_URL)
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700982 self._notice = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700983 self.branch = None
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700984 self._manifest_server = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700985
LaMont Jonescc879a92021-11-18 22:40:18 +0000986 def _Load(self, initial_client=None, submanifest_depth=0):
987 if submanifest_depth > MAX_SUBMANIFEST_DEPTH:
988 raise ManifestParseError('maximum submanifest depth %d exceeded.' %
989 MAX_SUBMANIFEST_DEPTH)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700990 if not self._loaded:
LaMont Jonescc879a92021-11-18 22:40:18 +0000991 if self._outer_client and self._outer_client != self:
992 # This will load all clients.
993 self._outer_client._Load(initial_client=self)
994
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800995 m = self.manifestProject
996 b = m.GetBranch(m.CurrentBranch).merge
Shawn O. Pearce21c5c342009-06-25 16:47:30 -0700997 if b is not None and b.startswith(R_HEADS):
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800998 b = b[len(R_HEADS):]
999 self.branch = b
1000
LaMont Jonescc879a92021-11-18 22:40:18 +00001001 parent_groups = self.parent_groups
LaMont Jonesb308db12022-02-25 17:05:21 +00001002 if self.path_prefix:
1003 parent_groups = f'{SUBMANIFEST_GROUP_PREFIX}:path:{self.path_prefix},{parent_groups}'
LaMont Jonescc879a92021-11-18 22:40:18 +00001004
Mike Frysinger54133972021-03-01 21:38:08 -05001005 # The manifestFile was specified by the user which is why we allow include
1006 # paths to point anywhere.
Colin Cross23acdd32012-04-21 00:33:54 -07001007 nodes = []
Mike Frysinger54133972021-03-01 21:38:08 -05001008 nodes.append(self._ParseManifestXml(
1009 self.manifestFile, self.manifestProject.worktree,
LaMont Jonescc879a92021-11-18 22:40:18 +00001010 parent_groups=parent_groups, restrict_includes=False))
Shawn O. Pearce5cc66792008-10-23 16:19:27 -07001011
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001012 if self._load_local_manifests and self.local_manifests:
Basil Gelloc7453502018-05-25 20:23:52 +03001013 try:
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001014 for local_file in sorted(platform_utils.listdir(self.local_manifests)):
Basil Gelloc7453502018-05-25 20:23:52 +03001015 if local_file.endswith('.xml'):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001016 local = os.path.join(self.local_manifests, local_file)
Mike Frysinger54133972021-03-01 21:38:08 -05001017 # Since local manifests are entirely managed by the user, allow
1018 # them to point anywhere the user wants.
LaMont Jonescc879a92021-11-18 22:40:18 +00001019 local_group = f'{LOCAL_MANIFEST_GROUP_PREFIX}:{local_file[:-4]}'
Mike Frysinger54133972021-03-01 21:38:08 -05001020 nodes.append(self._ParseManifestXml(
LaMont Jonescc879a92021-11-18 22:40:18 +00001021 local, self.subdir,
1022 parent_groups=f'{local_group},{parent_groups}',
Raman Tenneti78f4dd32021-06-07 13:27:37 -07001023 restrict_includes=False))
Basil Gelloc7453502018-05-25 20:23:52 +03001024 except OSError:
1025 pass
David Pursehouse2d5a0df2012-11-13 02:50:36 +09001026
Joe Onorato26e24752013-01-11 12:35:53 -08001027 try:
1028 self._ParseManifest(nodes)
1029 except ManifestParseError as e:
1030 # There was a problem parsing, unload ourselves in case they catch
1031 # this error and try again later, we will show the correct error
1032 self._Unload()
1033 raise e
Shawn O. Pearce5cc66792008-10-23 16:19:27 -07001034
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001035 if self.IsMirror:
1036 self._AddMetaProjectMirror(self.repoProject)
1037 self._AddMetaProjectMirror(self.manifestProject)
1038
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001039 self._loaded = True
1040
LaMont Jonescc879a92021-11-18 22:40:18 +00001041 # Now that we have loaded this manifest, load any submanifest manifests
1042 # as well. We need to do this after self._loaded is set to avoid looping.
1043 if self._outer_client:
1044 for name in self._submanifests:
1045 tree = self._submanifests[name]
1046 spec = tree.ToSubmanifestSpec(self)
1047 present = os.path.exists(os.path.join(self.subdir, MANIFEST_FILE_NAME))
1048 if present and tree.present and not tree.repo_client:
1049 if initial_client and initial_client.topdir == self.topdir:
1050 tree.repo_client = self
1051 tree.present = present
1052 elif not os.path.exists(self.subdir):
1053 tree.present = False
1054 if tree.present:
1055 tree.repo_client._Load(initial_client=initial_client,
1056 submanifest_depth=submanifest_depth + 1)
1057
Mike Frysinger54133972021-03-01 21:38:08 -05001058 def _ParseManifestXml(self, path, include_root, parent_groups='',
1059 restrict_includes=True):
1060 """Parse a manifest XML and return the computed nodes.
1061
1062 Args:
1063 path: The XML file to read & parse.
1064 include_root: The path to interpret include "name"s relative to.
1065 parent_groups: The groups to apply to this projects.
1066 restrict_includes: Whether to constrain the "name" attribute of includes.
1067
1068 Returns:
1069 List of XML nodes.
1070 """
David Pursehousef7fc8a92012-11-13 04:00:28 +09001071 try:
1072 root = xml.dom.minidom.parse(path)
David Pursehouse2d5a0df2012-11-13 02:50:36 +09001073 except (OSError, xml.parsers.expat.ExpatError) as e:
David Pursehousef7fc8a92012-11-13 04:00:28 +09001074 raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
1075
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001076 if not root or not root.childNodes:
Brian Harring26448742011-04-28 05:04:41 -07001077 raise ManifestParseError("no root node in %s" % (path,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001078
Jooncheol Park34acdd22012-08-27 02:25:59 +09001079 for manifest in root.childNodes:
1080 if manifest.nodeName == 'manifest':
1081 break
1082 else:
Brian Harring26448742011-04-28 05:04:41 -07001083 raise ManifestParseError("no <manifest> in %s" % (path,))
1084
Colin Cross23acdd32012-04-21 00:33:54 -07001085 nodes = []
David Pursehouse65b0ba52018-06-24 16:21:51 +09001086 for node in manifest.childNodes:
David Pursehousec1b86a22012-11-14 11:36:51 +09001087 if node.nodeName == 'include':
1088 name = self._reqatt(node, 'name')
Mike Frysinger54133972021-03-01 21:38:08 -05001089 if restrict_includes:
1090 msg = self._CheckLocalPath(name)
1091 if msg:
1092 raise ManifestInvalidPathError(
1093 '<include> invalid "name": %s: %s' % (name, msg))
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001094 include_groups = ''
1095 if parent_groups:
1096 include_groups = parent_groups
1097 if node.hasAttribute('groups'):
1098 include_groups = node.getAttribute('groups') + ',' + include_groups
David Pursehousec1b86a22012-11-14 11:36:51 +09001099 fp = os.path.join(include_root, name)
1100 if not os.path.isfile(fp):
Mike Frysinger54133972021-03-01 21:38:08 -05001101 raise ManifestParseError("include [%s/]%s doesn't exist or isn't a file"
1102 % (include_root, name))
David Pursehousec1b86a22012-11-14 11:36:51 +09001103 try:
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001104 nodes.extend(self._ParseManifestXml(fp, include_root, include_groups))
David Pursehousec1b86a22012-11-14 11:36:51 +09001105 # should isolate this to the exact exception, but that's
1106 # tricky. actual parsing implementation may vary.
Mike Frysinger54133972021-03-01 21:38:08 -05001107 except (KeyboardInterrupt, RuntimeError, SystemExit, ManifestParseError):
David Pursehousec1b86a22012-11-14 11:36:51 +09001108 raise
1109 except Exception as e:
1110 raise ManifestParseError(
Mike Frysingerec558df2019-07-05 01:38:05 -04001111 "failed parsing included manifest %s: %s" % (name, e))
David Pursehousec1b86a22012-11-14 11:36:51 +09001112 else:
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001113 if parent_groups and node.nodeName == 'project':
1114 nodeGroups = parent_groups
1115 if node.hasAttribute('groups'):
1116 nodeGroups = node.getAttribute('groups') + ',' + nodeGroups
1117 node.setAttribute('groups', nodeGroups)
David Pursehousec1b86a22012-11-14 11:36:51 +09001118 nodes.append(node)
Colin Cross23acdd32012-04-21 00:33:54 -07001119 return nodes
Brian Harring26448742011-04-28 05:04:41 -07001120
Colin Cross23acdd32012-04-21 00:33:54 -07001121 def _ParseManifest(self, node_list):
1122 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001123 if node.nodeName == 'remote':
1124 remote = self._ParseRemote(node)
David Pursehouse717ece92012-11-13 08:49:16 +09001125 if remote:
1126 if remote.name in self._remotes:
1127 if remote != self._remotes[remote.name]:
1128 raise ManifestParseError(
1129 'remote %s already exists with different attributes' %
1130 (remote.name))
1131 else:
1132 self._remotes[remote.name] = remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001133
Colin Cross23acdd32012-04-21 00:33:54 -07001134 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001135 if node.nodeName == 'default':
Julien Campergue74879922013-10-09 14:38:46 +02001136 new_default = self._ParseDefault(node)
Jack Neusb8c84482021-06-15 14:28:30 +00001137 emptyDefault = not node.hasAttributes() and not node.hasChildNodes()
Julien Campergue74879922013-10-09 14:38:46 +02001138 if self._default is None:
1139 self._default = new_default
Jack Neusb8c84482021-06-15 14:28:30 +00001140 elif not emptyDefault and new_default != self._default:
David Pursehouse37128b62013-10-15 10:48:40 +09001141 raise ManifestParseError('duplicate default in %s' %
1142 (self.manifestFile))
Julien Campergue74879922013-10-09 14:38:46 +02001143
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001144 if self._default is None:
1145 self._default = _Default()
1146
LaMont Jonescc879a92021-11-18 22:40:18 +00001147 submanifest_paths = set()
1148 for node in itertools.chain(*node_list):
1149 if node.nodeName == 'submanifest':
1150 submanifest = self._ParseSubmanifest(node)
1151 if submanifest:
1152 if submanifest.name in self._submanifests:
1153 if submanifest != self._submanifests[submanifest.name]:
1154 raise ManifestParseError(
1155 'submanifest %s already exists with different attributes' %
1156 (submanifest.name))
1157 else:
1158 self._submanifests[submanifest.name] = submanifest
1159 submanifest_paths.add(submanifest.relpath)
1160
Colin Cross23acdd32012-04-21 00:33:54 -07001161 for node in itertools.chain(*node_list):
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001162 if node.nodeName == 'notice':
1163 if self._notice is not None:
Doug Anderson37282b42011-03-04 11:54:18 -08001164 raise ManifestParseError(
1165 'duplicate notice in %s' %
1166 (self.manifestFile))
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001167 self._notice = self._ParseNotice(node)
1168
Colin Cross23acdd32012-04-21 00:33:54 -07001169 for node in itertools.chain(*node_list):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001170 if node.nodeName == 'manifest-server':
1171 url = self._reqatt(node, 'url')
1172 if self._manifest_server is not None:
David Pursehousec1b86a22012-11-14 11:36:51 +09001173 raise ManifestParseError(
1174 'duplicate manifest-server in %s' %
1175 (self.manifestFile))
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001176 self._manifest_server = url
1177
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001178 def recursively_add_projects(project):
David James8d201162013-10-11 17:03:19 -07001179 projects = self._projects.setdefault(project.name, [])
1180 if project.relpath is None:
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001181 raise ManifestParseError(
David James8d201162013-10-11 17:03:19 -07001182 'missing path for %s in %s' %
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001183 (project.name, self.manifestFile))
David James8d201162013-10-11 17:03:19 -07001184 if project.relpath in self._paths:
1185 raise ManifestParseError(
1186 'duplicate path %s in %s' %
1187 (project.relpath, self.manifestFile))
LaMont Jonescc879a92021-11-18 22:40:18 +00001188 for tree in submanifest_paths:
1189 if project.relpath.startswith(tree):
1190 raise ManifestParseError(
1191 'project %s conflicts with submanifest path %s' %
1192 (project.relpath, tree))
David James8d201162013-10-11 17:03:19 -07001193 self._paths[project.relpath] = project
1194 projects.append(project)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001195 for subproject in project.subprojects:
1196 recursively_add_projects(subproject)
1197
Jack Neusa84f43a2021-09-21 22:23:55 +00001198 repo_hooks_project = None
1199 enabled_repo_hooks = None
Colin Cross23acdd32012-04-21 00:33:54 -07001200 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001201 if node.nodeName == 'project':
1202 project = self._ParseProject(node)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001203 recursively_add_projects(project)
Josh Triplett884a3872014-06-12 14:57:29 -07001204 if node.nodeName == 'extend-project':
1205 name = self._reqatt(node, 'name')
1206
1207 if name not in self._projects:
1208 raise ManifestParseError('extend-project element specifies non-existent '
1209 'project: %s' % name)
1210
1211 path = node.getAttribute('path')
Michael Kelly37c21c22020-06-13 02:10:40 -07001212 dest_path = node.getAttribute('dest-path')
Josh Triplett884a3872014-06-12 14:57:29 -07001213 groups = node.getAttribute('groups')
1214 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -05001215 groups = self._ParseList(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -07001216 revision = node.getAttribute('revision')
LaMont Jonescc879a92021-11-18 22:40:18 +00001217 remote_name = node.getAttribute('remote')
1218 if not remote_name:
1219 remote = self._default.remote
1220 else:
Kyunam Jobd0aae92020-02-04 11:38:53 +09001221 remote = self._get_remote(node)
Josh Triplett884a3872014-06-12 14:57:29 -07001222
Michael Kelly37c21c22020-06-13 02:10:40 -07001223 named_projects = self._projects[name]
1224 if dest_path and not path and len(named_projects) > 1:
1225 raise ManifestParseError('extend-project cannot use dest-path when '
1226 'matching multiple projects: %s' % name)
Josh Triplett884a3872014-06-12 14:57:29 -07001227 for p in self._projects[name]:
1228 if path and p.relpath != path:
1229 continue
1230 if groups:
1231 p.groups.extend(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -07001232 if revision:
Michael Kelly2f3c3312020-07-21 19:40:38 -07001233 p.SetRevision(revision)
1234
LaMont Jonescc879a92021-11-18 22:40:18 +00001235 if remote_name:
Kyunam Jobd0aae92020-02-04 11:38:53 +09001236 p.remote = remote.ToRemoteSpec(name)
Michael Kelly2f3c3312020-07-21 19:40:38 -07001237
Michael Kelly37c21c22020-06-13 02:10:40 -07001238 if dest_path:
1239 del self._paths[p.relpath]
LaMont Jonescc879a92021-11-18 22:40:18 +00001240 relpath, worktree, gitdir, objdir, _ = self.GetProjectPaths(
1241 name, dest_path, remote.name)
Michael Kelly37c21c22020-06-13 02:10:40 -07001242 p.UpdatePaths(relpath, worktree, gitdir, objdir)
1243 self._paths[p.relpath] = p
1244
Doug Anderson37282b42011-03-04 11:54:18 -08001245 if node.nodeName == 'repo-hooks':
Doug Anderson37282b42011-03-04 11:54:18 -08001246 # Only one project can be the hooks project
Jack Neusa84f43a2021-09-21 22:23:55 +00001247 if repo_hooks_project is not None:
Doug Anderson37282b42011-03-04 11:54:18 -08001248 raise ManifestParseError(
1249 'duplicate repo-hooks in %s' %
1250 (self.manifestFile))
1251
Jack Neusa84f43a2021-09-21 22:23:55 +00001252 # Get the name of the project and the (space-separated) list of enabled.
1253 repo_hooks_project = self._reqatt(node, 'in-project')
1254 enabled_repo_hooks = self._ParseList(self._reqatt(node, 'enabled-list'))
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001255 if node.nodeName == 'superproject':
1256 name = self._reqatt(node, 'name')
1257 # There can only be one superproject.
1258 if self._superproject.get('name'):
1259 raise ManifestParseError(
1260 'duplicate superproject in %s' %
1261 (self.manifestFile))
1262 self._superproject['name'] = name
1263 remote_name = node.getAttribute('remote')
1264 if not remote_name:
1265 remote = self._default.remote
1266 else:
1267 remote = self._get_remote(node)
1268 if remote is None:
1269 raise ManifestParseError("no remote for superproject %s within %s" %
1270 (name, self.manifestFile))
1271 self._superproject['remote'] = remote.ToRemoteSpec(name)
Xin Lie0b16a22021-09-26 23:20:32 -07001272 revision = node.getAttribute('revision') or remote.revision
1273 if not revision:
1274 revision = self._default.revisionExpr
1275 if not revision:
1276 raise ManifestParseError('no revision for superproject %s within %s' %
1277 (name, self.manifestFile))
1278 self._superproject['revision'] = revision
Raman Tenneti1c3f57e2021-05-04 12:32:13 -07001279 if node.nodeName == 'contactinfo':
1280 bugurl = self._reqatt(node, 'bugurl')
1281 # This element can be repeated, later entries will clobber earlier ones.
Raman Tenneti993af5e2021-05-12 12:00:31 -07001282 self._contactinfo = ContactInfo(bugurl)
1283
Colin Cross23acdd32012-04-21 00:33:54 -07001284 if node.nodeName == 'remove-project':
1285 name = self._reqatt(node, 'name')
David Jamesb8433df2014-01-30 10:11:17 -08001286
Michael Kelly06da9982021-06-30 01:58:28 -07001287 if name in self._projects:
1288 for p in self._projects[name]:
1289 del self._paths[p.relpath]
1290 del self._projects[name]
1291
1292 # If the manifest removes the hooks project, treat it as if it deleted
1293 # the repo-hooks element too.
Jack Neusa84f43a2021-09-21 22:23:55 +00001294 if repo_hooks_project == name:
1295 repo_hooks_project = None
Michael Kelly06da9982021-06-30 01:58:28 -07001296 elif not XmlBool(node, 'optional', False):
David Pursehousef9107482012-11-16 19:12:32 +09001297 raise ManifestParseError('remove-project element specifies non-existent '
1298 'project: %s' % name)
Colin Cross23acdd32012-04-21 00:33:54 -07001299
Jack Neusa84f43a2021-09-21 22:23:55 +00001300 # Store repo hooks project information.
1301 if repo_hooks_project:
1302 # Store a reference to the Project.
1303 try:
1304 repo_hooks_projects = self._projects[repo_hooks_project]
1305 except KeyError:
1306 raise ManifestParseError(
1307 'project %s not found for repo-hooks' %
1308 (repo_hooks_project))
1309
1310 if len(repo_hooks_projects) != 1:
1311 raise ManifestParseError(
1312 'internal error parsing repo-hooks in %s' %
1313 (self.manifestFile))
1314 self._repo_hooks_project = repo_hooks_projects[0]
1315 # Store the enabled hooks in the Project object.
1316 self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
1317
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001318 def _AddMetaProjectMirror(self, m):
1319 name = None
1320 m_url = m.GetRemote(m.remote.name).url
1321 if m_url.endswith('/.git'):
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301322 raise ManifestParseError('refusing to mirror %s' % m_url)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001323
1324 if self._default and self._default.remote:
Conley Owensceea3682011-10-20 10:45:47 -07001325 url = self._default.remote.resolvedFetchUrl
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001326 if not url.endswith('/'):
1327 url += '/'
1328 if m_url.startswith(url):
1329 remote = self._default.remote
1330 name = m_url[len(url):]
1331
1332 if name is None:
1333 s = m_url.rindex('/') + 1
Conley Owensdb728cd2011-09-26 16:34:01 -07001334 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Shawn O. Pearcef35b2d92012-08-02 11:46:22 -07001335 remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001336 name = m_url[s:]
1337
1338 if name.endswith('.git'):
1339 name = name[:-4]
1340
1341 if name not in self._projects:
1342 m.PreSync()
1343 gitdir = os.path.join(self.topdir, '%s.git' % name)
David Pursehousee5913ae2020-02-12 13:56:59 +09001344 project = Project(manifest=self,
1345 name=name,
1346 remote=remote.ToRemoteSpec(name),
1347 gitdir=gitdir,
1348 objdir=gitdir,
1349 worktree=None,
1350 relpath=name or None,
1351 revisionExpr=m.revisionExpr,
1352 revisionId=None)
David James8d201162013-10-11 17:03:19 -07001353 self._projects[project.name] = [project]
Kwanhong Leeccd218c2014-02-17 13:07:32 +09001354 self._paths[project.relpath] = project
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001355
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001356 def _ParseRemote(self, node):
1357 """
1358 reads a <remote> element from the manifest file
1359 """
1360 name = self._reqatt(node, 'name')
Yestin Sunb292b982012-07-02 07:32:50 -07001361 alias = node.getAttribute('alias')
1362 if alias == '':
1363 alias = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001364 fetch = self._reqatt(node, 'fetch')
Steve Raed6480452016-08-10 15:00:00 -07001365 pushUrl = node.getAttribute('pushurl')
1366 if pushUrl == '':
1367 pushUrl = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001368 review = node.getAttribute('review')
Shawn O. Pearceae6e0942008-11-06 10:25:35 -08001369 if review == '':
1370 review = None
Anthony King36ea2fb2014-05-06 11:54:01 +01001371 revision = node.getAttribute('revision')
1372 if revision == '':
1373 revision = None
Conley Owensdb728cd2011-09-26 16:34:01 -07001374 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Jack Neus6ea0cae2021-07-20 20:52:33 +00001375
1376 remote = _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
1377
1378 for n in node.childNodes:
1379 if n.nodeName == 'annotation':
1380 self._ParseAnnotation(remote, n)
1381
1382 return remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001383
1384 def _ParseDefault(self, node):
1385 """
1386 reads a <default> element from the manifest file
1387 """
1388 d = _Default()
1389 d.remote = self._get_remote(node)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001390 d.revisionExpr = node.getAttribute('revision')
1391 if d.revisionExpr == '':
1392 d.revisionExpr = None
Anatol Pomazau79770d22012-04-20 14:41:59 -07001393
Bryan Jacobsf609f912013-05-06 13:36:24 -04001394 d.destBranchExpr = node.getAttribute('dest-branch') or None
Nasser Grainawida403412018-05-04 12:53:29 -06001395 d.upstreamExpr = node.getAttribute('upstream') or None
Bryan Jacobsf609f912013-05-06 13:36:24 -04001396
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001397 d.sync_j = XmlInt(node, 'sync-j', 1)
1398 if d.sync_j <= 0:
1399 raise ManifestParseError('%s: sync-j must be greater than 0, not "%s"' %
1400 (self.manifestFile, d.sync_j))
Anatol Pomazau79770d22012-04-20 14:41:59 -07001401
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001402 d.sync_c = XmlBool(node, 'sync-c', False)
1403 d.sync_s = XmlBool(node, 'sync-s', False)
1404 d.sync_tags = XmlBool(node, 'sync-tags', True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001405 return d
1406
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001407 def _ParseNotice(self, node):
1408 """
1409 reads a <notice> element from the manifest file
1410
1411 The <notice> element is distinct from other tags in the XML in that the
1412 data is conveyed between the start and end tag (it's not an empty-element
1413 tag).
1414
1415 The white space (carriage returns, indentation) for the notice element is
1416 relevant and is parsed in a way that is based on how python docstrings work.
1417 In fact, the code is remarkably similar to here:
1418 http://www.python.org/dev/peps/pep-0257/
1419 """
1420 # Get the data out of the node...
1421 notice = node.childNodes[0].data
1422
1423 # Figure out minimum indentation, skipping the first line (the same line
1424 # as the <notice> tag)...
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301425 minIndent = sys.maxsize
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001426 lines = notice.splitlines()
1427 for line in lines[1:]:
1428 lstrippedLine = line.lstrip()
1429 if lstrippedLine:
1430 indent = len(line) - len(lstrippedLine)
1431 minIndent = min(indent, minIndent)
1432
1433 # Strip leading / trailing blank lines and also indentation.
1434 cleanLines = [lines[0].strip()]
1435 for line in lines[1:]:
1436 cleanLines.append(line[minIndent:].rstrip())
1437
1438 # Clear completely blank lines from front and back...
1439 while cleanLines and not cleanLines[0]:
1440 del cleanLines[0]
1441 while cleanLines and not cleanLines[-1]:
1442 del cleanLines[-1]
1443
1444 return '\n'.join(cleanLines)
1445
LaMont Jonescc879a92021-11-18 22:40:18 +00001446 def _ParseSubmanifest(self, node):
1447 """Reads a <submanifest> element from the manifest file."""
1448 name = self._reqatt(node, 'name')
1449 remote = node.getAttribute('remote')
1450 if remote == '':
1451 remote = None
1452 project = node.getAttribute('project')
1453 if project == '':
1454 project = None
1455 revision = node.getAttribute('revision')
1456 if revision == '':
1457 revision = None
1458 manifestName = node.getAttribute('manifest-name')
1459 if manifestName == '':
1460 manifestName = None
1461 groups = ''
1462 if node.hasAttribute('groups'):
1463 groups = node.getAttribute('groups')
1464 groups = self._ParseList(groups)
1465 path = node.getAttribute('path')
1466 if path == '':
1467 path = None
1468 if revision:
1469 msg = self._CheckLocalPath(revision.split('/')[-1])
1470 if msg:
1471 raise ManifestInvalidPathError(
1472 '<submanifest> invalid "revision": %s: %s' % (revision, msg))
1473 else:
1474 msg = self._CheckLocalPath(name)
1475 if msg:
1476 raise ManifestInvalidPathError(
1477 '<submanifest> invalid "name": %s: %s' % (name, msg))
1478 else:
1479 msg = self._CheckLocalPath(path)
1480 if msg:
1481 raise ManifestInvalidPathError(
1482 '<submanifest> invalid "path": %s: %s' % (path, msg))
1483
1484 submanifest = _XmlSubmanifest(name, remote, project, revision, manifestName,
1485 groups, path, self)
1486
1487 for n in node.childNodes:
1488 if n.nodeName == 'annotation':
1489 self._ParseAnnotation(submanifest, n)
1490
1491 return submanifest
1492
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001493 def _JoinName(self, parent_name, name):
1494 return os.path.join(parent_name, name)
1495
1496 def _UnjoinName(self, parent_name, name):
1497 return os.path.relpath(name, parent_name)
1498
David Pursehousee5913ae2020-02-12 13:56:59 +09001499 def _ParseProject(self, node, parent=None, **extra_proj_attrs):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001500 """
1501 reads a <project> element from the manifest file
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001502 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001503 name = self._reqatt(node, 'name')
Mike Frysingera29424e2021-02-25 21:53:49 -05001504 msg = self._CheckLocalPath(name, dir_ok=True)
1505 if msg:
1506 raise ManifestInvalidPathError(
1507 '<project> invalid "name": %s: %s' % (name, msg))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001508 if parent:
1509 name = self._JoinName(parent.name, name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001510
1511 remote = self._get_remote(node)
1512 if remote is None:
1513 remote = self._default.remote
1514 if remote is None:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301515 raise ManifestParseError("no remote for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001516 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001517
Anthony King36ea2fb2014-05-06 11:54:01 +01001518 revisionExpr = node.getAttribute('revision') or remote.revision
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001519 if not revisionExpr:
1520 revisionExpr = self._default.revisionExpr
1521 if not revisionExpr:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301522 raise ManifestParseError("no revision for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001523 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001524
1525 path = node.getAttribute('path')
1526 if not path:
1527 path = name
Mike Frysingera29424e2021-02-25 21:53:49 -05001528 else:
Mike Frysinger0458faa2021-03-10 23:35:44 -05001529 # NB: The "." project is handled specially in Project.Sync_LocalHalf.
1530 msg = self._CheckLocalPath(path, dir_ok=True, cwd_dot_ok=True)
Mike Frysingera29424e2021-02-25 21:53:49 -05001531 if msg:
1532 raise ManifestInvalidPathError(
1533 '<project> invalid "path": %s: %s' % (path, msg))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001534
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001535 rebase = XmlBool(node, 'rebase', True)
1536 sync_c = XmlBool(node, 'sync-c', False)
1537 sync_s = XmlBool(node, 'sync-s', self._default.sync_s)
1538 sync_tags = XmlBool(node, 'sync-tags', self._default.sync_tags)
Mike Pontillod3153822012-02-28 11:53:24 -08001539
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001540 clone_depth = XmlInt(node, 'clone-depth')
1541 if clone_depth is not None and clone_depth <= 0:
1542 raise ManifestParseError('%s: clone-depth must be greater than 0, not "%s"' %
1543 (self.manifestFile, clone_depth))
David Pursehouseede7f122012-11-27 22:25:30 +09001544
Bryan Jacobsf609f912013-05-06 13:36:24 -04001545 dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
1546
Nasser Grainawida403412018-05-04 12:53:29 -06001547 upstream = node.getAttribute('upstream') or self._default.upstreamExpr
Brian Harring14a66742012-09-28 20:21:57 -07001548
Conley Owens971de8e2012-04-16 10:36:08 -07001549 groups = ''
1550 if node.hasAttribute('groups'):
1551 groups = node.getAttribute('groups')
Mike Frysinger51e39d52020-12-04 05:32:06 -05001552 groups = self._ParseList(groups)
Brian Harring7da13142012-06-15 02:24:20 -07001553
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001554 if parent is None:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001555 relpath, worktree, gitdir, objdir, use_git_worktrees = \
LaMont Jonescc879a92021-11-18 22:40:18 +00001556 self.GetProjectPaths(name, path, remote.name)
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001557 else:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001558 use_git_worktrees = False
David James8d201162013-10-11 17:03:19 -07001559 relpath, worktree, gitdir, objdir = \
1560 self.GetSubprojectPaths(parent, name, path)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001561
1562 default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
1563 groups.extend(set(default_groups).difference(groups))
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001564
Scott Fandb83b1b2013-02-28 09:34:14 +08001565 if self.IsMirror and node.hasAttribute('force-path'):
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001566 if XmlBool(node, 'force-path', False):
Scott Fandb83b1b2013-02-28 09:34:14 +08001567 gitdir = os.path.join(self.topdir, '%s.git' % path)
1568
David Pursehousee5913ae2020-02-12 13:56:59 +09001569 project = Project(manifest=self,
1570 name=name,
1571 remote=remote.ToRemoteSpec(name),
1572 gitdir=gitdir,
1573 objdir=objdir,
1574 worktree=worktree,
1575 relpath=relpath,
1576 revisionExpr=revisionExpr,
1577 revisionId=None,
1578 rebase=rebase,
1579 groups=groups,
1580 sync_c=sync_c,
1581 sync_s=sync_s,
1582 sync_tags=sync_tags,
1583 clone_depth=clone_depth,
1584 upstream=upstream,
1585 parent=parent,
1586 dest_branch=dest_branch,
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001587 use_git_worktrees=use_git_worktrees,
Simran Basib9a1b732015-08-20 12:19:28 -07001588 **extra_proj_attrs)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001589
1590 for n in node.childNodes:
Shawn O. Pearce242b5262009-05-19 13:00:29 -07001591 if n.nodeName == 'copyfile':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001592 self._ParseCopyFile(project, n)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001593 if n.nodeName == 'linkfile':
1594 self._ParseLinkFile(project, n)
James W. Mills24c13082012-04-12 15:04:13 -05001595 if n.nodeName == 'annotation':
1596 self._ParseAnnotation(project, n)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001597 if n.nodeName == 'project':
David Pursehousee5913ae2020-02-12 13:56:59 +09001598 project.subprojects.append(self._ParseProject(n, parent=project))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001599
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001600 return project
1601
LaMont Jonescc879a92021-11-18 22:40:18 +00001602 def GetProjectPaths(self, name, path, remote):
1603 """Return the paths for a project.
1604
1605 Args:
1606 name: a string, the name of the project.
1607 path: a string, the path of the project.
1608 remote: a string, the remote.name of the project.
1609 """
Mike Frysingercebf2272020-05-26 01:02:29 -04001610 # The manifest entries might have trailing slashes. Normalize them to avoid
1611 # unexpected filesystem behavior since we do string concatenation below.
1612 path = path.rstrip('/')
1613 name = name.rstrip('/')
LaMont Jonescc879a92021-11-18 22:40:18 +00001614 remote = remote.rstrip('/')
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001615 use_git_worktrees = False
LaMont Jonescc879a92021-11-18 22:40:18 +00001616 use_remote_name = bool(self._outer_client._submanifests)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001617 relpath = path
1618 if self.IsMirror:
1619 worktree = None
1620 gitdir = os.path.join(self.topdir, '%s.git' % name)
David James8d201162013-10-11 17:03:19 -07001621 objdir = gitdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001622 else:
LaMont Jonescc879a92021-11-18 22:40:18 +00001623 if use_remote_name:
1624 namepath = os.path.join(remote, f'{name}.git')
1625 else:
1626 namepath = f'{name}.git'
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001627 worktree = os.path.join(self.topdir, path).replace('\\', '/')
LaMont Jonescc879a92021-11-18 22:40:18 +00001628 gitdir = os.path.join(self.subdir, 'projects', '%s.git' % path)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001629 # We allow people to mix git worktrees & non-git worktrees for now.
1630 # This allows for in situ migration of repo clients.
1631 if os.path.exists(gitdir) or not self.UseGitWorktrees:
LaMont Jonescc879a92021-11-18 22:40:18 +00001632 objdir = os.path.join(self.subdir, 'project-objects', namepath)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001633 else:
1634 use_git_worktrees = True
LaMont Jonescc879a92021-11-18 22:40:18 +00001635 gitdir = os.path.join(self.repodir, 'worktrees', namepath)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001636 objdir = gitdir
1637 return relpath, worktree, gitdir, objdir, use_git_worktrees
David James8d201162013-10-11 17:03:19 -07001638
LaMont Jonescc879a92021-11-18 22:40:18 +00001639 def GetProjectsWithName(self, name, all_manifests=False):
1640 """All projects with |name|.
1641
1642 Args:
1643 name: a string, the name of the project.
1644 all_manifests: a boolean, if True, then all manifests are searched. If
1645 False, then only this manifest is searched.
1646 """
1647 if all_manifests:
1648 return list(itertools.chain.from_iterable(
1649 x._projects.get(name, []) for x in self.all_manifests))
David James8d201162013-10-11 17:03:19 -07001650 return self._projects.get(name, [])
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001651
1652 def GetSubprojectName(self, parent, submodule_path):
1653 return os.path.join(parent.name, submodule_path)
1654
1655 def _JoinRelpath(self, parent_relpath, relpath):
1656 return os.path.join(parent_relpath, relpath)
1657
1658 def _UnjoinRelpath(self, parent_relpath, relpath):
1659 return os.path.relpath(relpath, parent_relpath)
1660
David James8d201162013-10-11 17:03:19 -07001661 def GetSubprojectPaths(self, parent, name, path):
Mike Frysingercebf2272020-05-26 01:02:29 -04001662 # The manifest entries might have trailing slashes. Normalize them to avoid
1663 # unexpected filesystem behavior since we do string concatenation below.
1664 path = path.rstrip('/')
1665 name = name.rstrip('/')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001666 relpath = self._JoinRelpath(parent.relpath, path)
1667 gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
David James8d201162013-10-11 17:03:19 -07001668 objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001669 if self.IsMirror:
1670 worktree = None
1671 else:
1672 worktree = os.path.join(parent.worktree, path).replace('\\', '/')
David James8d201162013-10-11 17:03:19 -07001673 return relpath, worktree, gitdir, objdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001674
Mike Frysinger04122b72019-07-31 23:32:58 -04001675 @staticmethod
Mike Frysingera00c5f42021-02-25 18:26:31 -05001676 def _CheckLocalPath(path, dir_ok=False, cwd_dot_ok=False):
1677 """Verify |path| is reasonable for use in filesystem paths.
1678
Mike Frysingera29424e2021-02-25 21:53:49 -05001679 Used with <copyfile> & <linkfile> & <project> elements.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001680
1681 This only validates the |path| in isolation: it does not check against the
1682 current filesystem state. Thus it is suitable as a first-past in a parser.
1683
1684 It enforces a number of constraints:
1685 * No empty paths.
1686 * No "~" in paths.
1687 * No Unicode codepoints that filesystems might elide when normalizing.
1688 * No relative path components like "." or "..".
1689 * No absolute paths.
1690 * No ".git" or ".repo*" path components.
1691
1692 Args:
1693 path: The path name to validate.
1694 dir_ok: Whether |path| may force a directory (e.g. end in a /).
1695 cwd_dot_ok: Whether |path| may be just ".".
1696
1697 Returns:
1698 None if |path| is OK, a failure message otherwise.
1699 """
1700 if not path:
1701 return 'empty paths not allowed'
1702
Mike Frysinger04122b72019-07-31 23:32:58 -04001703 if '~' in path:
1704 return '~ not allowed (due to 8.3 filenames on Windows filesystems)'
1705
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001706 path_codepoints = set(path)
1707
Mike Frysinger04122b72019-07-31 23:32:58 -04001708 # Some filesystems (like Apple's HFS+) try to normalize Unicode codepoints
1709 # which means there are alternative names for ".git". Reject paths with
1710 # these in it as there shouldn't be any reasonable need for them here.
1711 # The set of codepoints here was cribbed from jgit's implementation:
1712 # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
1713 BAD_CODEPOINTS = {
1714 u'\u200C', # ZERO WIDTH NON-JOINER
1715 u'\u200D', # ZERO WIDTH JOINER
1716 u'\u200E', # LEFT-TO-RIGHT MARK
1717 u'\u200F', # RIGHT-TO-LEFT MARK
1718 u'\u202A', # LEFT-TO-RIGHT EMBEDDING
1719 u'\u202B', # RIGHT-TO-LEFT EMBEDDING
1720 u'\u202C', # POP DIRECTIONAL FORMATTING
1721 u'\u202D', # LEFT-TO-RIGHT OVERRIDE
1722 u'\u202E', # RIGHT-TO-LEFT OVERRIDE
1723 u'\u206A', # INHIBIT SYMMETRIC SWAPPING
1724 u'\u206B', # ACTIVATE SYMMETRIC SWAPPING
1725 u'\u206C', # INHIBIT ARABIC FORM SHAPING
1726 u'\u206D', # ACTIVATE ARABIC FORM SHAPING
1727 u'\u206E', # NATIONAL DIGIT SHAPES
1728 u'\u206F', # NOMINAL DIGIT SHAPES
1729 u'\uFEFF', # ZERO WIDTH NO-BREAK SPACE
1730 }
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001731 if BAD_CODEPOINTS & path_codepoints:
Mike Frysinger04122b72019-07-31 23:32:58 -04001732 # This message is more expansive than reality, but should be fine.
1733 return 'Unicode combining characters not allowed'
1734
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001735 # Reject newlines as there shouldn't be any legitmate use for them, they'll
1736 # be confusing to users, and they can easily break tools that expect to be
1737 # able to iterate over newline delimited lists. This even applies to our
1738 # own code like .repo/project.list.
1739 if {'\r', '\n'} & path_codepoints:
1740 return 'Newlines not allowed'
1741
Mike Frysinger04122b72019-07-31 23:32:58 -04001742 # Assume paths might be used on case-insensitive filesystems.
1743 path = path.lower()
1744
Mike Frysingerd9254592020-02-19 22:36:26 -05001745 # Split up the path by its components. We can't use os.path.sep exclusively
1746 # as some platforms (like Windows) will convert / to \ and that bypasses all
1747 # our constructed logic here. Especially since manifest authors only use
1748 # / in their paths.
1749 resep = re.compile(r'[/%s]' % re.escape(os.path.sep))
Mike Frysinger0458faa2021-03-10 23:35:44 -05001750 # Strip off trailing slashes as those only produce '' elements, and we use
1751 # parts to look for individual bad components.
1752 parts = resep.split(path.rstrip('/'))
Mike Frysingerd9254592020-02-19 22:36:26 -05001753
Mike Frysingerae625412020-02-10 17:10:03 -05001754 # Some people use src="." to create stable links to projects. Lets allow
1755 # that but reject all other uses of "." to keep things simple.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001756 if not cwd_dot_ok or parts != ['.']:
Mike Frysingerae625412020-02-10 17:10:03 -05001757 for part in set(parts):
1758 if part in {'.', '..', '.git'} or part.startswith('.repo'):
1759 return 'bad component: %s' % (part,)
Mike Frysinger04122b72019-07-31 23:32:58 -04001760
Mike Frysingera00c5f42021-02-25 18:26:31 -05001761 if not dir_ok and resep.match(path[-1]):
Mike Frysinger04122b72019-07-31 23:32:58 -04001762 return 'dirs not allowed'
1763
Mike Frysingerd9254592020-02-19 22:36:26 -05001764 # NB: The two abspath checks here are to handle platforms with multiple
1765 # filesystem path styles (e.g. Windows).
Mike Frysinger04122b72019-07-31 23:32:58 -04001766 norm = os.path.normpath(path)
Mike Frysingerd9254592020-02-19 22:36:26 -05001767 if (norm == '..' or
1768 (len(norm) >= 3 and norm.startswith('..') and resep.match(norm[0])) or
1769 os.path.isabs(norm) or
1770 norm.startswith('/')):
Mike Frysinger04122b72019-07-31 23:32:58 -04001771 return 'path cannot be outside'
1772
1773 @classmethod
1774 def _ValidateFilePaths(cls, element, src, dest):
1775 """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
1776
1777 We verify the path independent of any filesystem state as we won't have a
1778 checkout available to compare to. i.e. This is for parsing validation
1779 purposes only.
1780
1781 We'll do full/live sanity checking before we do the actual filesystem
1782 modifications in _CopyFile/_LinkFile/etc...
1783 """
1784 # |dest| is the file we write to or symlink we create.
1785 # It is relative to the top of the repo client checkout.
1786 msg = cls._CheckLocalPath(dest)
1787 if msg:
1788 raise ManifestInvalidPathError(
1789 '<%s> invalid "dest": %s: %s' % (element, dest, msg))
1790
1791 # |src| is the file we read from or path we point to for symlinks.
1792 # It is relative to the top of the git project checkout.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001793 is_linkfile = element == 'linkfile'
1794 msg = cls._CheckLocalPath(src, dir_ok=is_linkfile, cwd_dot_ok=is_linkfile)
Mike Frysinger04122b72019-07-31 23:32:58 -04001795 if msg:
1796 raise ManifestInvalidPathError(
1797 '<%s> invalid "src": %s: %s' % (element, src, msg))
1798
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001799 def _ParseCopyFile(self, project, node):
1800 src = self._reqatt(node, 'src')
1801 dest = self._reqatt(node, 'dest')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001802 if not self.IsMirror:
1803 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001804 # dest is relative to the top of the tree.
1805 # We only validate paths if we actually plan to process them.
1806 self._ValidateFilePaths('copyfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001807 project.AddCopyFile(src, dest, self.topdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001808
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001809 def _ParseLinkFile(self, project, node):
1810 src = self._reqatt(node, 'src')
1811 dest = self._reqatt(node, 'dest')
1812 if not self.IsMirror:
1813 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001814 # dest is relative to the top of the tree.
1815 # We only validate paths if we actually plan to process them.
1816 self._ValidateFilePaths('linkfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001817 project.AddLinkFile(src, dest, self.topdir)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001818
Jack Neus6ea0cae2021-07-20 20:52:33 +00001819 def _ParseAnnotation(self, element, node):
James W. Mills24c13082012-04-12 15:04:13 -05001820 name = self._reqatt(node, 'name')
1821 value = self._reqatt(node, 'value')
1822 try:
1823 keep = self._reqatt(node, 'keep').lower()
1824 except ManifestParseError:
1825 keep = "true"
1826 if keep != "true" and keep != "false":
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301827 raise ManifestParseError('optional "keep" attribute must be '
David Pursehouseabdf7502020-02-12 14:58:39 +09001828 '"true" or "false"')
Jack Neus6ea0cae2021-07-20 20:52:33 +00001829 element.AddAnnotation(name, value, keep)
James W. Mills24c13082012-04-12 15:04:13 -05001830
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001831 def _get_remote(self, node):
1832 name = node.getAttribute('remote')
1833 if not name:
1834 return None
1835
1836 v = self._remotes.get(name)
1837 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301838 raise ManifestParseError("remote %s not defined in %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001839 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001840 return v
1841
1842 def _reqatt(self, node, attname):
1843 """
1844 reads a required attribute from the node.
1845 """
1846 v = node.getAttribute(attname)
1847 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301848 raise ManifestParseError("no %s in <%s> within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001849 (attname, node.nodeName, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001850 return v
Julien Camperguedd654222014-01-09 16:21:37 +01001851
1852 def projectsDiff(self, manifest):
1853 """return the projects differences between two manifests.
1854
1855 The diff will be from self to given manifest.
1856
1857 """
1858 fromProjects = self.paths
1859 toProjects = manifest.paths
1860
Anthony King7446c592014-05-06 09:19:39 +01001861 fromKeys = sorted(fromProjects.keys())
1862 toKeys = sorted(toProjects.keys())
Julien Camperguedd654222014-01-09 16:21:37 +01001863
1864 diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
1865
1866 for proj in fromKeys:
David Pursehouseeeff3532020-02-12 11:24:10 +09001867 if proj not in toKeys:
Julien Camperguedd654222014-01-09 16:21:37 +01001868 diff['removed'].append(fromProjects[proj])
1869 else:
1870 fromProj = fromProjects[proj]
1871 toProj = toProjects[proj]
1872 try:
1873 fromRevId = fromProj.GetCommitRevisionId()
1874 toRevId = toProj.GetCommitRevisionId()
1875 except ManifestInvalidRevisionError:
1876 diff['unreachable'].append((fromProj, toProj))
1877 else:
1878 if fromRevId != toRevId:
1879 diff['changed'].append((fromProj, toProj))
1880 toKeys.remove(proj)
1881
1882 for proj in toKeys:
1883 diff['added'].append(toProjects[proj])
1884
1885 return diff
Simran Basib9a1b732015-08-20 12:19:28 -07001886
1887
1888class GitcManifest(XmlManifest):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001889 """Parser for GitC (git-in-the-cloud) manifests."""
Simran Basib9a1b732015-08-20 12:19:28 -07001890
David Pursehousee5913ae2020-02-12 13:56:59 +09001891 def _ParseProject(self, node, parent=None):
Simran Basib9a1b732015-08-20 12:19:28 -07001892 """Override _ParseProject and add support for GITC specific attributes."""
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001893 return super()._ParseProject(
Simran Basib9a1b732015-08-20 12:19:28 -07001894 node, parent=parent, old_revision=node.getAttribute('old-revision'))
1895
1896 def _output_manifest_project_extras(self, p, e):
1897 """Output GITC Specific Project attributes"""
1898 if p.old_revision:
Stefan Beller66851062016-06-17 16:40:08 -07001899 e.setAttribute('old-revision', str(p.old_revision))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001900
1901
1902class RepoClient(XmlManifest):
1903 """Manages a repo client checkout."""
1904
LaMont Jonescc879a92021-11-18 22:40:18 +00001905 def __init__(self, repodir, manifest_file=None, submanifest_path='', **kwargs):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001906 self.isGitcClient = False
LaMont Jonescc879a92021-11-18 22:40:18 +00001907 submanifest_path = submanifest_path or ''
1908 if submanifest_path:
1909 self._CheckLocalPath(submanifest_path)
1910 prefix = os.path.join(repodir, SUBMANIFEST_DIR, submanifest_path)
1911 else:
1912 prefix = repodir
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001913
LaMont Jonescc879a92021-11-18 22:40:18 +00001914 if os.path.exists(os.path.join(prefix, LOCAL_MANIFEST_NAME)):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001915 print('error: %s is not supported; put local manifests in `%s` instead' %
LaMont Jonescc879a92021-11-18 22:40:18 +00001916 (LOCAL_MANIFEST_NAME, os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME)),
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001917 file=sys.stderr)
1918 sys.exit(1)
1919
1920 if manifest_file is None:
LaMont Jonescc879a92021-11-18 22:40:18 +00001921 manifest_file = os.path.join(prefix, MANIFEST_FILE_NAME)
1922 local_manifests = os.path.abspath(os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME))
1923 super().__init__(repodir, manifest_file, local_manifests,
1924 submanifest_path=submanifest_path, **kwargs)
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001925
1926 # TODO: Completely separate manifest logic out of the client.
1927 self.manifest = self
1928
1929
1930class GitcClient(RepoClient, GitcManifest):
1931 """Manages a GitC client checkout."""
1932
1933 def __init__(self, repodir, gitc_client_name):
1934 """Initialize the GitcManifest object."""
1935 self.gitc_client_name = gitc_client_name
1936 self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
1937 gitc_client_name)
1938
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001939 super().__init__(repodir, os.path.join(self.gitc_client_dir, '.manifest'))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001940 self.isGitcClient = True