blob: 8718dc545d8ddfca0b2f7836b3c963b09566bcb3 [file] [log] [blame]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001# Copyright (C) 2008 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
Raman Tenneti993af5e2021-05-12 12:00:31 -070015import collections
Colin Cross23acdd32012-04-21 00:33:54 -070016import itertools
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070017import os
Raman Tenneti080877e2021-03-09 15:19:06 -080018import platform
Conley Owensdb728cd2011-09-26 16:34:01 -070019import re
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070020import sys
David Pursehouse59bbb582013-05-17 10:49:33 +090021import xml.dom.minidom
Mike Frysingeracf63b22019-06-13 02:24:21 -040022import urllib.parse
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070023
Simran Basib9a1b732015-08-20 12:19:28 -070024import gitc_utils
Miguel Gaio1f207762020-07-17 14:09:13 +020025from git_config import GitConfig, IsId
David Pursehousee00aa6b2012-09-11 14:33:51 +090026from git_refs import R_HEADS, HEAD
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070027import platform_utils
LaMont Jones9b72cf22022-03-29 21:54:22 +000028from project import (Annotation, RemoteSpec, Project, RepoProject,
29 ManifestProject)
Mike Frysinger04122b72019-07-31 23:32:58 -040030from error import (ManifestParseError, ManifestInvalidPathError,
31 ManifestInvalidRevisionError)
Raman Tenneti993af5e2021-05-12 12:00:31 -070032from wrapper import Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070033
34MANIFEST_FILE_NAME = 'manifest.xml'
Shawn O. Pearce5cc66792008-10-23 16:19:27 -070035LOCAL_MANIFEST_NAME = 'local_manifest.xml'
David Pursehouse2d5a0df2012-11-13 02:50:36 +090036LOCAL_MANIFESTS_DIR_NAME = 'local_manifests'
LaMont Jonescc879a92021-11-18 22:40:18 +000037SUBMANIFEST_DIR = 'submanifests'
38# Limit submanifests to an arbitrary depth for loop detection.
39MAX_SUBMANIFEST_DEPTH = 8
LaMont Jonesb308db12022-02-25 17:05:21 +000040# Add all projects from sub manifest into a group.
41SUBMANIFEST_GROUP_PREFIX = 'submanifest:'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070042
Raman Tenneti78f4dd32021-06-07 13:27:37 -070043# Add all projects from local manifest into a group.
44LOCAL_MANIFEST_GROUP_PREFIX = 'local:'
45
Raman Tenneti993af5e2021-05-12 12:00:31 -070046# ContactInfo has the self-registered bug url, supplied by the manifest authors.
47ContactInfo = collections.namedtuple('ContactInfo', 'bugurl')
48
Anthony Kingcb07ba72015-03-28 23:26:04 +000049# urljoin gets confused if the scheme is not known.
Joe Kilner6e310792016-10-27 15:53:53 -070050urllib.parse.uses_relative.extend([
51 'ssh',
52 'git',
53 'persistent-https',
54 'sso',
55 'rpc'])
56urllib.parse.uses_netloc.extend([
57 'ssh',
58 'git',
59 'persistent-https',
60 'sso',
61 'rpc'])
Conley Owensdb728cd2011-09-26 16:34:01 -070062
David Pursehouse819827a2020-02-12 15:20:19 +090063
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050064def XmlBool(node, attr, default=None):
65 """Determine boolean value of |node|'s |attr|.
66
67 Invalid values will issue a non-fatal warning.
68
69 Args:
70 node: XML node whose attributes we access.
71 attr: The attribute to access.
72 default: If the attribute is not set (value is empty), then use this.
73
74 Returns:
75 True if the attribute is a valid string representing true.
76 False if the attribute is a valid string representing false.
77 |default| otherwise.
78 """
79 value = node.getAttribute(attr)
80 s = value.lower()
81 if s == '':
82 return default
83 elif s in {'yes', 'true', '1'}:
84 return True
85 elif s in {'no', 'false', '0'}:
86 return False
87 else:
88 print('warning: manifest: %s="%s": ignoring invalid XML boolean' %
89 (attr, value), file=sys.stderr)
90 return default
91
92
93def XmlInt(node, attr, default=None):
94 """Determine integer value of |node|'s |attr|.
95
96 Args:
97 node: XML node whose attributes we access.
98 attr: The attribute to access.
99 default: If the attribute is not set (value is empty), then use this.
100
101 Returns:
102 The number if the attribute is a valid number.
103
104 Raises:
105 ManifestParseError: The number is invalid.
106 """
107 value = node.getAttribute(attr)
108 if not value:
109 return default
110
111 try:
112 return int(value)
113 except ValueError:
114 raise ManifestParseError('manifest: invalid %s="%s" integer' %
115 (attr, value))
116
117
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700118class _Default(object):
119 """Project defaults within the manifest."""
120
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700121 revisionExpr = None
Conley Owensb6a16e62013-09-25 15:06:09 -0700122 destBranchExpr = None
Nasser Grainawida403412018-05-04 12:53:29 -0600123 upstreamExpr = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700124 remote = None
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700125 sync_j = 1
Anatol Pomazau79770d22012-04-20 14:41:59 -0700126 sync_c = False
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800127 sync_s = False
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900128 sync_tags = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700129
Julien Campergue74879922013-10-09 14:38:46 +0200130 def __eq__(self, other):
Jack Neus5ba21202021-06-09 15:21:25 +0000131 if not isinstance(other, _Default):
132 return False
Julien Campergue74879922013-10-09 14:38:46 +0200133 return self.__dict__ == other.__dict__
134
135 def __ne__(self, other):
Jack Neus5ba21202021-06-09 15:21:25 +0000136 if not isinstance(other, _Default):
137 return True
Julien Campergue74879922013-10-09 14:38:46 +0200138 return self.__dict__ != other.__dict__
139
David Pursehouse819827a2020-02-12 15:20:19 +0900140
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700141class _XmlRemote(object):
142 def __init__(self,
143 name,
Yestin Sunb292b982012-07-02 07:32:50 -0700144 alias=None,
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700145 fetch=None,
Steve Raed6480452016-08-10 15:00:00 -0700146 pushUrl=None,
Conley Owensdb728cd2011-09-26 16:34:01 -0700147 manifestUrl=None,
Anthony King36ea2fb2014-05-06 11:54:01 +0100148 review=None,
Jonathan Nieder93719792015-03-17 11:29:58 -0700149 revision=None):
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700150 self.name = name
151 self.fetchUrl = fetch
Steve Raed6480452016-08-10 15:00:00 -0700152 self.pushUrl = pushUrl
Conley Owensdb728cd2011-09-26 16:34:01 -0700153 self.manifestUrl = manifestUrl
Yestin Sunb292b982012-07-02 07:32:50 -0700154 self.remoteAlias = alias
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700155 self.reviewUrl = review
Anthony King36ea2fb2014-05-06 11:54:01 +0100156 self.revision = revision
Conley Owensceea3682011-10-20 10:45:47 -0700157 self.resolvedFetchUrl = self._resolveFetchUrl()
Jack Neus6ea0cae2021-07-20 20:52:33 +0000158 self.annotations = []
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700159
David Pursehouse717ece92012-11-13 08:49:16 +0900160 def __eq__(self, other):
Jack Neus5ba21202021-06-09 15:21:25 +0000161 if not isinstance(other, _XmlRemote):
162 return False
Jack Neus6ea0cae2021-07-20 20:52:33 +0000163 return (sorted(self.annotations) == sorted(other.annotations) and
164 self.name == other.name and self.fetchUrl == other.fetchUrl and
165 self.pushUrl == other.pushUrl and self.remoteAlias == other.remoteAlias
166 and self.reviewUrl == other.reviewUrl and self.revision == other.revision)
David Pursehouse717ece92012-11-13 08:49:16 +0900167
168 def __ne__(self, other):
Jack Neus6ea0cae2021-07-20 20:52:33 +0000169 return not self.__eq__(other)
David Pursehouse717ece92012-11-13 08:49:16 +0900170
Conley Owensceea3682011-10-20 10:45:47 -0700171 def _resolveFetchUrl(self):
Jack Neus5ba21202021-06-09 15:21:25 +0000172 if self.fetchUrl is None:
173 return ''
Conley Owensceea3682011-10-20 10:45:47 -0700174 url = self.fetchUrl.rstrip('/')
Conley Owensdb728cd2011-09-26 16:34:01 -0700175 manifestUrl = self.manifestUrl.rstrip('/')
Conley Owens2d0f5082014-01-31 15:03:51 -0800176 # urljoin will gets confused over quite a few things. The ones we care
177 # about here are:
178 # * no scheme in the base url, like <hostname:port>
Anthony Kingcb07ba72015-03-28 23:26:04 +0000179 # We handle no scheme by replacing it with an obscure protocol, gopher
180 # and then replacing it with the original when we are done.
181
Conley Owensdb728cd2011-09-26 16:34:01 -0700182 if manifestUrl.find(':') != manifestUrl.find('/') - 1:
Conley Owens4ccad752015-04-29 10:45:37 -0700183 url = urllib.parse.urljoin('gopher://' + manifestUrl, url)
184 url = re.sub(r'^gopher://', '', url)
Anthony Kingcb07ba72015-03-28 23:26:04 +0000185 else:
186 url = urllib.parse.urljoin(manifestUrl, url)
Shawn Pearcea9f11b32013-01-02 15:40:48 -0800187 return url
Conley Owensceea3682011-10-20 10:45:47 -0700188
189 def ToRemoteSpec(self, projectName):
David Rileye0684ad2017-04-05 00:02:59 -0700190 fetchUrl = self.resolvedFetchUrl.rstrip('/')
191 url = fetchUrl + '/' + projectName
Yestin Sunb292b982012-07-02 07:32:50 -0700192 remoteName = self.name
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700193 if self.remoteAlias:
David Pursehouse37128b62013-10-15 10:48:40 +0900194 remoteName = self.remoteAlias
Dan Willemsen96c2d652016-04-06 16:03:54 -0700195 return RemoteSpec(remoteName,
196 url=url,
Steve Raed6480452016-08-10 15:00:00 -0700197 pushUrl=self.pushUrl,
Dan Willemsen96c2d652016-04-06 16:03:54 -0700198 review=self.reviewUrl,
David Rileye0684ad2017-04-05 00:02:59 -0700199 orig_name=self.name,
200 fetchUrl=self.fetchUrl)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700201
Jack Neus6ea0cae2021-07-20 20:52:33 +0000202 def AddAnnotation(self, name, value, keep):
203 self.annotations.append(Annotation(name, value, keep))
204
David Pursehouse819827a2020-02-12 15:20:19 +0900205
LaMont Jonescc879a92021-11-18 22:40:18 +0000206class _XmlSubmanifest:
207 """Manage the <submanifest> element specified in the manifest.
208
209 Attributes:
210 name: a string, the name for this submanifest.
211 remote: a string, the remote.name for this submanifest.
212 project: a string, the name of the manifest project.
213 revision: a string, the commitish.
214 manifestName: a string, the submanifest file name.
215 groups: a list of strings, the groups to add to all projects in the submanifest.
216 path: a string, the relative path for the submanifest checkout.
217 annotations: (derived) a list of annotations.
218 present: (derived) a boolean, whether the submanifest's manifest file is present.
219 """
220 def __init__(self,
221 name,
222 remote=None,
223 project=None,
224 revision=None,
225 manifestName=None,
226 groups=None,
227 path=None,
228 parent=None):
229 self.name = name
230 self.remote = remote
231 self.project = project
232 self.revision = revision
233 self.manifestName = manifestName
234 self.groups = groups
235 self.path = path
236 self.annotations = []
237 outer_client = parent._outer_client or parent
238 if self.remote and not self.project:
239 raise ManifestParseError(
240 f'Submanifest {name}: must specify project when remote is given.')
LaMont Jones5d3291d2022-03-23 19:03:02 +0000241 # Construct the absolute path to the manifest file using the parent's
242 # method, so that we can correctly create our repo_client.
243 manifestFile = parent.SubmanifestInfoDir(
244 os.path.join(parent.path_prefix, self.relpath),
245 os.path.join('manifests', manifestName or 'default.xml'))
LaMont Jones55ee3042022-04-06 17:10:21 +0000246 linkFile = parent.SubmanifestInfoDir(
247 os.path.join(parent.path_prefix, self.relpath), MANIFEST_FILE_NAME)
LaMont Jonescc879a92021-11-18 22:40:18 +0000248 rc = self.repo_client = RepoClient(
LaMont Jones55ee3042022-04-06 17:10:21 +0000249 parent.repodir, linkFile, parent_groups=','.join(groups) or '',
LaMont Jonescc879a92021-11-18 22:40:18 +0000250 submanifest_path=self.relpath, outer_client=outer_client)
251
LaMont Jones55ee3042022-04-06 17:10:21 +0000252 self.present = os.path.exists(manifestFile)
LaMont Jonescc879a92021-11-18 22:40:18 +0000253
254 def __eq__(self, other):
255 if not isinstance(other, _XmlSubmanifest):
256 return False
257 return (
258 self.name == other.name and
259 self.remote == other.remote and
260 self.project == other.project and
261 self.revision == other.revision and
262 self.manifestName == other.manifestName and
263 self.groups == other.groups and
264 self.path == other.path and
265 sorted(self.annotations) == sorted(other.annotations))
266
267 def __ne__(self, other):
268 return not self.__eq__(other)
269
270 def ToSubmanifestSpec(self, root):
271 """Return a SubmanifestSpec object, populating attributes"""
272 mp = root.manifestProject
273 remote = root.remotes[self.remote or root.default.remote.name]
274 # If a project was given, generate the url from the remote and project.
275 # If not, use this manifestProject's url.
276 if self.project:
277 manifestUrl = remote.ToRemoteSpec(self.project).url
278 else:
279 manifestUrl = mp.GetRemote(mp.remote.name).url
280 manifestName = self.manifestName or 'default.xml'
281 revision = self.revision or self.name
282 path = self.path or revision.split('/')[-1]
283 groups = self.groups or []
284
285 return SubmanifestSpec(self.name, manifestUrl, manifestName, revision, path,
286 groups)
287
288 @property
289 def relpath(self):
290 """The path of this submanifest relative to the parent manifest."""
291 revision = self.revision or self.name
292 return self.path or revision.split('/')[-1]
293
294 def GetGroupsStr(self):
295 """Returns the `groups` given for this submanifest."""
296 if self.groups:
297 return ','.join(self.groups)
298 return ''
299
300 def AddAnnotation(self, name, value, keep):
301 """Add annotations to the submanifest."""
302 self.annotations.append(Annotation(name, value, keep))
303
304
305class SubmanifestSpec:
306 """The submanifest element, with all fields expanded."""
307
308 def __init__(self,
309 name,
310 manifestUrl,
311 manifestName,
312 revision,
313 path,
314 groups):
315 self.name = name
316 self.manifestUrl = manifestUrl
317 self.manifestName = manifestName
318 self.revision = revision
319 self.path = path
320 self.groups = groups or []
321
322
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700323class XmlManifest(object):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700324 """manages the repo configuration file"""
325
LaMont Jonescc879a92021-11-18 22:40:18 +0000326 def __init__(self, repodir, manifest_file, local_manifests=None,
327 outer_client=None, parent_groups='', submanifest_path=''):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400328 """Initialize.
329
330 Args:
331 repodir: Path to the .repo/ dir for holding all internal checkout state.
332 It must be in the top directory of the repo client checkout.
333 manifest_file: Full path to the manifest file to parse. This will usually
334 be |repodir|/|MANIFEST_FILE_NAME|.
335 local_manifests: Full path to the directory of local override manifests.
336 This will usually be |repodir|/|LOCAL_MANIFESTS_DIR_NAME|.
LaMont Jonescc879a92021-11-18 22:40:18 +0000337 outer_client: RepoClient of the outertree.
338 parent_groups: a string, the groups to apply to this projects.
339 submanifest_path: The submanifest root relative to the repo root.
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400340 """
341 # TODO(vapier): Move this out of this class.
342 self.globalConfig = GitConfig.ForUser()
343
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700344 self.repodir = os.path.abspath(repodir)
LaMont Jonescc879a92021-11-18 22:40:18 +0000345 self._CheckLocalPath(submanifest_path)
346 self.topdir = os.path.join(os.path.dirname(self.repodir), submanifest_path)
LaMont Jones5d3291d2022-03-23 19:03:02 +0000347 if manifest_file != os.path.abspath(manifest_file):
348 raise ManifestParseError('manifest_file must be abspath')
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400349 self.manifestFile = manifest_file
350 self.local_manifests = local_manifests
Basil Gelloc7453502018-05-25 20:23:52 +0300351 self._load_local_manifests = True
LaMont Jonescc879a92021-11-18 22:40:18 +0000352 self.parent_groups = parent_groups
353
354 if outer_client and self.isGitcClient:
355 raise ManifestParseError('Multi-manifest is incompatible with `gitc-init`')
356
357 if submanifest_path and not outer_client:
358 # If passing a submanifest_path, there must be an outer_client.
359 raise ManifestParseError(f'Bad call to {self.__class__.__name__}')
360
361 # If self._outer_client is None, this is not a checkout that supports
362 # multi-tree.
363 self._outer_client = outer_client or self
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700364
LaMont Jones9b72cf22022-03-29 21:54:22 +0000365 self.repoProject = RepoProject(self, 'repo',
David Pursehouseabdf7502020-02-12 14:58:39 +0900366 gitdir=os.path.join(repodir, 'repo/.git'),
367 worktree=os.path.join(repodir, 'repo'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700368
LaMont Jonescc879a92021-11-18 22:40:18 +0000369 mp = self.SubmanifestProject(self.path_prefix)
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500370 self.manifestProject = mp
371
372 # This is a bit hacky, but we're in a chicken & egg situation: all the
373 # normal repo settings live in the manifestProject which we just setup
374 # above, so we couldn't easily query before that. We assume Project()
375 # init doesn't care if this changes afterwards.
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000376 if os.path.exists(mp.gitdir) and mp.use_worktree:
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500377 mp.use_git_worktrees = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700378
LaMont Jonesa2ff20d2022-04-07 16:49:06 +0000379 self.Unload()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700380
Basil Gelloc7453502018-05-25 20:23:52 +0300381 def Override(self, name, load_local_manifests=True):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700382 """Use a different manifest, just for the current instantiation.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700383 """
Basil Gelloc7453502018-05-25 20:23:52 +0300384 path = None
385
386 # Look for a manifest by path in the filesystem (including the cwd).
387 if not load_local_manifests:
388 local_path = os.path.abspath(name)
389 if os.path.isfile(local_path):
390 path = local_path
391
392 # Look for manifests by name from the manifests repo.
393 if path is None:
394 path = os.path.join(self.manifestProject.worktree, name)
395 if not os.path.isfile(path):
396 raise ManifestParseError('manifest %s not found' % name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700397
398 old = self.manifestFile
399 try:
Basil Gelloc7453502018-05-25 20:23:52 +0300400 self._load_local_manifests = load_local_manifests
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700401 self.manifestFile = path
LaMont Jonesa2ff20d2022-04-07 16:49:06 +0000402 self.Unload()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700403 self._Load()
404 finally:
405 self.manifestFile = old
406
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700407 def Link(self, name):
408 """Update the repo metadata to use a different manifest.
409 """
410 self.Override(name)
411
Mike Frysingera269b1c2020-02-21 00:49:41 -0500412 # Old versions of repo would generate symlinks we need to clean up.
Mike Frysinger9d96f582021-09-28 11:27:24 -0400413 platform_utils.remove(self.manifestFile, missing_ok=True)
Mike Frysingera269b1c2020-02-21 00:49:41 -0500414 # This file is interpreted as if it existed inside the manifest repo.
415 # That allows us to use <include> with the relative file name.
416 with open(self.manifestFile, 'w') as fp:
417 fp.write("""<?xml version="1.0" encoding="UTF-8"?>
418<!--
419DO NOT EDIT THIS FILE! It is generated by repo and changes will be discarded.
420If you want to use a different manifest, use `repo init -m <file>` instead.
421
422If you want to customize your checkout by overriding manifest settings, use
423the local_manifests/ directory instead.
424
425For more information on repo manifests, check out:
426https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
427-->
428<manifest>
429 <include name="%s" />
430</manifest>
431""" % (name,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700432
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800433 def _RemoteToXml(self, r, doc, root):
434 e = doc.createElement('remote')
435 root.appendChild(e)
436 e.setAttribute('name', r.name)
437 e.setAttribute('fetch', r.fetchUrl)
Steve Raed6480452016-08-10 15:00:00 -0700438 if r.pushUrl is not None:
439 e.setAttribute('pushurl', r.pushUrl)
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700440 if r.remoteAlias is not None:
441 e.setAttribute('alias', r.remoteAlias)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800442 if r.reviewUrl is not None:
443 e.setAttribute('review', r.reviewUrl)
Anthony King36ea2fb2014-05-06 11:54:01 +0100444 if r.revision is not None:
445 e.setAttribute('revision', r.revision)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800446
Jack Neus6ea0cae2021-07-20 20:52:33 +0000447 for a in r.annotations:
448 if a.keep == 'true':
449 ae = doc.createElement('annotation')
450 ae.setAttribute('name', a.name)
451 ae.setAttribute('value', a.value)
452 e.appendChild(ae)
453
LaMont Jonescc879a92021-11-18 22:40:18 +0000454 def _SubmanifestToXml(self, r, doc, root):
455 """Generate XML <submanifest/> node."""
456 e = doc.createElement('submanifest')
457 root.appendChild(e)
458 e.setAttribute('name', r.name)
459 if r.remote is not None:
460 e.setAttribute('remote', r.remote)
461 if r.project is not None:
462 e.setAttribute('project', r.project)
463 if r.manifestName is not None:
464 e.setAttribute('manifest-name', r.manifestName)
465 if r.revision is not None:
466 e.setAttribute('revision', r.revision)
467 if r.path is not None:
468 e.setAttribute('path', r.path)
469 if r.groups:
470 e.setAttribute('groups', r.GetGroupsStr())
471
472 for a in r.annotations:
473 if a.keep == 'true':
474 ae = doc.createElement('annotation')
475 ae.setAttribute('name', a.name)
476 ae.setAttribute('value', a.value)
477 e.appendChild(ae)
478
Mike Frysinger51e39d52020-12-04 05:32:06 -0500479 def _ParseList(self, field):
480 """Parse fields that contain flattened lists.
481
482 These are whitespace & comma separated. Empty elements will be discarded.
483 """
484 return [x for x in re.split(r'[,\s]+', field) if x]
Josh Triplett884a3872014-06-12 14:57:29 -0700485
Mike Frysinger23411d32020-09-02 04:31:10 -0400486 def ToXml(self, peg_rev=False, peg_rev_upstream=True, peg_rev_dest_branch=True, groups=None):
487 """Return the current manifest XML."""
Colin Cross5acde752012-03-28 20:15:45 -0700488 mp = self.manifestProject
489
Dan Willemsen5ea32d12015-09-08 13:27:20 -0700490 if groups is None:
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000491 groups = mp.manifest_groups
Matt Gumbel0c635bb2012-12-21 10:14:53 -0800492 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -0500493 groups = self._ParseList(groups)
Colin Cross5acde752012-03-28 20:15:45 -0700494
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800495 doc = xml.dom.minidom.Document()
496 root = doc.createElement('manifest')
LaMont Jonescc879a92021-11-18 22:40:18 +0000497 if self.is_submanifest:
498 root.setAttribute('path', self.path_prefix)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800499 doc.appendChild(root)
500
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700501 # Save out the notice. There's a little bit of work here to give it the
502 # right whitespace, which assumes that the notice is automatically indented
503 # by 4 by minidom.
504 if self.notice:
505 notice_element = root.appendChild(doc.createElement('notice'))
506 notice_lines = self.notice.splitlines()
David Pursehouse54a4e602020-02-12 14:31:05 +0900507 indented_notice = ('\n'.join(" " * 4 + line for line in notice_lines))[4:]
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700508 notice_element.appendChild(doc.createTextNode(indented_notice))
509
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800510 d = self.default
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800511
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530512 for r in sorted(self.remotes):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800513 self._RemoteToXml(self.remotes[r], doc, root)
514 if self.remotes:
515 root.appendChild(doc.createTextNode(''))
516
517 have_default = False
518 e = doc.createElement('default')
519 if d.remote:
520 have_default = True
521 e.setAttribute('remote', d.remote.name)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700522 if d.revisionExpr:
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800523 have_default = True
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700524 e.setAttribute('revision', d.revisionExpr)
Simon Ruggier7e59de22015-07-24 12:50:06 +0200525 if d.destBranchExpr:
526 have_default = True
527 e.setAttribute('dest-branch', d.destBranchExpr)
Nasser Grainawida403412018-05-04 12:53:29 -0600528 if d.upstreamExpr:
529 have_default = True
530 e.setAttribute('upstream', d.upstreamExpr)
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700531 if d.sync_j > 1:
532 have_default = True
533 e.setAttribute('sync-j', '%d' % d.sync_j)
Anatol Pomazau79770d22012-04-20 14:41:59 -0700534 if d.sync_c:
535 have_default = True
536 e.setAttribute('sync-c', 'true')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800537 if d.sync_s:
538 have_default = True
539 e.setAttribute('sync-s', 'true')
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900540 if not d.sync_tags:
541 have_default = True
542 e.setAttribute('sync-tags', 'false')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800543 if have_default:
544 root.appendChild(e)
545 root.appendChild(doc.createTextNode(''))
546
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700547 if self._manifest_server:
548 e = doc.createElement('manifest-server')
549 e.setAttribute('url', self._manifest_server)
550 root.appendChild(e)
551 root.appendChild(doc.createTextNode(''))
552
LaMont Jonescc879a92021-11-18 22:40:18 +0000553 for r in sorted(self.submanifests):
554 self._SubmanifestToXml(self.submanifests[r], doc, root)
555 if self.submanifests:
556 root.appendChild(doc.createTextNode(''))
557
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800558 def output_projects(parent, parent_node, projects):
David James8d201162013-10-11 17:03:19 -0700559 for project_name in projects:
560 for project in self._projects[project_name]:
561 output_project(parent, parent_node, project)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800562
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800563 def output_project(parent, parent_node, p):
Colin Cross5acde752012-03-28 20:15:45 -0700564 if not p.MatchesGroups(groups):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800565 return
566
567 name = p.name
568 relpath = p.relpath
569 if parent:
570 name = self._UnjoinName(parent.name, name)
571 relpath = self._UnjoinRelpath(parent.relpath, relpath)
Colin Cross5acde752012-03-28 20:15:45 -0700572
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800573 e = doc.createElement('project')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800574 parent_node.appendChild(e)
575 e.setAttribute('name', name)
576 if relpath != name:
577 e.setAttribute('path', relpath)
Conley Owensa17d7af2013-10-16 14:38:09 -0700578 remoteName = None
579 if d.remote:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700580 remoteName = d.remote.name
581 if not d.remote or p.remote.orig_name != remoteName:
582 remoteName = p.remote.orig_name
Anthony King36ea2fb2014-05-06 11:54:01 +0100583 e.setAttribute('remote', remoteName)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800584 if peg_rev:
585 if self.IsMirror:
Brian Harring14a66742012-09-28 20:21:57 -0700586 value = p.bare_git.rev_parse(p.revisionExpr + '^0')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800587 else:
Brian Harring14a66742012-09-28 20:21:57 -0700588 value = p.work_git.rev_parse(HEAD + '^0')
589 e.setAttribute('revision', value)
Conley Owens551dfec2015-07-10 14:54:54 -0700590 if peg_rev_upstream:
591 if p.upstream:
592 e.setAttribute('upstream', p.upstream)
593 elif value != p.revisionExpr:
594 # Only save the origin if the origin is not a sha1, and the default
595 # isn't our value
596 e.setAttribute('upstream', p.revisionExpr)
Sean McAllisteraf908cb2020-04-20 08:41:58 -0600597
598 if peg_rev_dest_branch:
599 if p.dest_branch:
600 e.setAttribute('dest-branch', p.dest_branch)
601 elif value != p.revisionExpr:
602 e.setAttribute('dest-branch', p.revisionExpr)
603
Anthony King36ea2fb2014-05-06 11:54:01 +0100604 else:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700605 revision = self.remotes[p.remote.orig_name].revision or d.revisionExpr
Anthony King36ea2fb2014-05-06 11:54:01 +0100606 if not revision or revision != p.revisionExpr:
607 e.setAttribute('revision', p.revisionExpr)
Raman Tennetib5c5a5e2021-02-06 09:44:15 -0800608 elif p.revisionId:
609 e.setAttribute('revision', p.revisionId)
Nasser Grainawida403412018-05-04 12:53:29 -0600610 if (p.upstream and (p.upstream != p.revisionExpr or
611 p.upstream != d.upstreamExpr)):
Mani Chandel7a91d512014-07-24 16:27:08 +0530612 e.setAttribute('upstream', p.upstream)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800613
Simon Ruggier7e59de22015-07-24 12:50:06 +0200614 if p.dest_branch and p.dest_branch != d.destBranchExpr:
615 e.setAttribute('dest-branch', p.dest_branch)
616
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800617 for c in p.copyfiles:
618 ce = doc.createElement('copyfile')
619 ce.setAttribute('src', c.src)
620 ce.setAttribute('dest', c.dest)
621 e.appendChild(ce)
622
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500623 for l in p.linkfiles:
624 le = doc.createElement('linkfile')
625 le.setAttribute('src', l.src)
626 le.setAttribute('dest', l.dest)
627 e.appendChild(le)
628
Conley Owensbb1b5f52012-08-13 13:11:18 -0700629 default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
Dmitry Fink17f85ea2012-08-06 14:52:29 -0700630 egroups = [g for g in p.groups if g not in default_groups]
Conley Owens971de8e2012-04-16 10:36:08 -0700631 if egroups:
632 e.setAttribute('groups', ','.join(egroups))
Colin Cross5acde752012-03-28 20:15:45 -0700633
James W. Mills24c13082012-04-12 15:04:13 -0500634 for a in p.annotations:
635 if a.keep == "true":
636 ae = doc.createElement('annotation')
637 ae.setAttribute('name', a.name)
638 ae.setAttribute('value', a.value)
639 e.appendChild(ae)
640
Anatol Pomazau79770d22012-04-20 14:41:59 -0700641 if p.sync_c:
642 e.setAttribute('sync-c', 'true')
643
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800644 if p.sync_s:
645 e.setAttribute('sync-s', 'true')
646
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900647 if not p.sync_tags:
648 e.setAttribute('sync-tags', 'false')
649
Dan Willemsen88409222015-08-17 15:29:10 -0700650 if p.clone_depth:
651 e.setAttribute('clone-depth', str(p.clone_depth))
652
Simran Basib9a1b732015-08-20 12:19:28 -0700653 self._output_manifest_project_extras(p, e)
654
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800655 if p.subprojects:
David James8d201162013-10-11 17:03:19 -0700656 subprojects = set(subp.name for subp in p.subprojects)
657 output_projects(p, e, list(sorted(subprojects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800658
David James8d201162013-10-11 17:03:19 -0700659 projects = set(p.name for p in self._paths.values() if not p.parent)
660 output_projects(None, root, list(sorted(projects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800661
Doug Anderson37282b42011-03-04 11:54:18 -0800662 if self._repo_hooks_project:
663 root.appendChild(doc.createTextNode(''))
664 e = doc.createElement('repo-hooks')
665 e.setAttribute('in-project', self._repo_hooks_project.name)
666 e.setAttribute('enabled-list',
667 ' '.join(self._repo_hooks_project.enabled_repo_hooks))
668 root.appendChild(e)
669
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800670 if self._superproject:
671 root.appendChild(doc.createTextNode(''))
672 e = doc.createElement('superproject')
673 e.setAttribute('name', self._superproject['name'])
674 remoteName = None
675 if d.remote:
676 remoteName = d.remote.name
677 remote = self._superproject.get('remote')
678 if not d.remote or remote.orig_name != remoteName:
679 remoteName = remote.orig_name
680 e.setAttribute('remote', remoteName)
Xin Lie0b16a22021-09-26 23:20:32 -0700681 revision = remote.revision or d.revisionExpr
682 if not revision or revision != self._superproject['revision']:
683 e.setAttribute('revision', self._superproject['revision'])
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800684 root.appendChild(e)
685
Raman Tenneti993af5e2021-05-12 12:00:31 -0700686 if self._contactinfo.bugurl != Wrapper().BUG_URL:
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700687 root.appendChild(doc.createTextNode(''))
688 e = doc.createElement('contactinfo')
Raman Tenneti993af5e2021-05-12 12:00:31 -0700689 e.setAttribute('bugurl', self._contactinfo.bugurl)
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700690 root.appendChild(e)
691
Mike Frysinger23411d32020-09-02 04:31:10 -0400692 return doc
693
694 def ToDict(self, **kwargs):
695 """Return the current manifest as a dictionary."""
696 # Elements that may only appear once.
697 SINGLE_ELEMENTS = {
698 'notice',
699 'default',
700 'manifest-server',
701 'repo-hooks',
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800702 'superproject',
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700703 'contactinfo',
Mike Frysinger23411d32020-09-02 04:31:10 -0400704 }
705 # Elements that may be repeated.
706 MULTI_ELEMENTS = {
707 'remote',
708 'remove-project',
709 'project',
710 'extend-project',
711 'include',
LaMont Jonescc879a92021-11-18 22:40:18 +0000712 'submanifest',
Mike Frysinger23411d32020-09-02 04:31:10 -0400713 # These are children of 'project' nodes.
714 'annotation',
715 'project',
716 'copyfile',
717 'linkfile',
718 }
719
720 doc = self.ToXml(**kwargs)
721 ret = {}
722
723 def append_children(ret, node):
724 for child in node.childNodes:
725 if child.nodeType == xml.dom.Node.ELEMENT_NODE:
726 attrs = child.attributes
727 element = dict((attrs.item(i).localName, attrs.item(i).value)
728 for i in range(attrs.length))
729 if child.nodeName in SINGLE_ELEMENTS:
730 ret[child.nodeName] = element
731 elif child.nodeName in MULTI_ELEMENTS:
732 ret.setdefault(child.nodeName, []).append(element)
733 else:
734 raise ManifestParseError('Unhandled element "%s"' % (child.nodeName,))
735
736 append_children(element, child)
737
738 append_children(ret, doc.firstChild)
739
740 return ret
741
742 def Save(self, fd, **kwargs):
743 """Write the current manifest out to the given file descriptor."""
744 doc = self.ToXml(**kwargs)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800745 doc.writexml(fd, '', ' ', '\n', 'UTF-8')
746
Simran Basib9a1b732015-08-20 12:19:28 -0700747 def _output_manifest_project_extras(self, p, e):
748 """Manifests can modify e if they support extra project attributes."""
Simran Basib9a1b732015-08-20 12:19:28 -0700749
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700750 @property
LaMont Jonescc879a92021-11-18 22:40:18 +0000751 def is_multimanifest(self):
752 """Whether this is a multimanifest checkout"""
753 return bool(self.outer_client.submanifests)
754
755 @property
756 def is_submanifest(self):
757 """Whether this manifest is a submanifest"""
758 return self._outer_client and self._outer_client != self
759
760 @property
761 def outer_client(self):
762 """The instance of the outermost manifest client"""
763 self._Load()
764 return self._outer_client
765
766 @property
767 def all_manifests(self):
768 """Generator yielding all (sub)manifests."""
769 self._Load()
770 outer = self._outer_client
771 yield outer
772 for tree in outer.all_children:
773 yield tree
774
775 @property
776 def all_children(self):
777 """Generator yielding all child submanifests."""
778 self._Load()
779 for child in self._submanifests.values():
780 if child.repo_client:
781 yield child.repo_client
782 for tree in child.repo_client.all_children:
783 yield tree
784
785 @property
786 def path_prefix(self):
787 """The path of this submanifest, relative to the outermost manifest."""
788 if not self._outer_client or self == self._outer_client:
789 return ''
790 return os.path.relpath(self.topdir, self._outer_client.topdir)
791
792 @property
793 def all_paths(self):
794 """All project paths for all (sub)manifests. See `paths`."""
795 ret = {}
796 for tree in self.all_manifests:
797 prefix = tree.path_prefix
798 ret.update({os.path.join(prefix, k): v for k, v in tree.paths.items()})
799 return ret
800
801 @property
802 def all_projects(self):
803 """All projects for all (sub)manifests. See `projects`."""
804 return list(itertools.chain.from_iterable(x._paths.values() for x in self.all_manifests))
805
806 @property
David James8d201162013-10-11 17:03:19 -0700807 def paths(self):
LaMont Jonescc879a92021-11-18 22:40:18 +0000808 """Return all paths for this manifest.
809
810 Return:
811 A dictionary of {path: Project()}. `path` is relative to this manifest.
812 """
David James8d201162013-10-11 17:03:19 -0700813 self._Load()
814 return self._paths
815
816 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700817 def projects(self):
LaMont Jonescc879a92021-11-18 22:40:18 +0000818 """Return a list of all Projects in this manifest."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700819 self._Load()
Anthony Kingd58bfe52014-05-05 23:30:49 +0100820 return list(self._paths.values())
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700821
822 @property
823 def remotes(self):
824 self._Load()
825 return self._remotes
826
827 @property
828 def default(self):
829 self._Load()
830 return self._default
831
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800832 @property
LaMont Jonescc879a92021-11-18 22:40:18 +0000833 def submanifests(self):
834 """All submanifests in this manifest."""
835 self._Load()
836 return self._submanifests
837
838 @property
Doug Anderson37282b42011-03-04 11:54:18 -0800839 def repo_hooks_project(self):
840 self._Load()
841 return self._repo_hooks_project
842
843 @property
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800844 def superproject(self):
845 self._Load()
846 return self._superproject
847
848 @property
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700849 def contactinfo(self):
850 self._Load()
851 return self._contactinfo
852
853 @property
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700854 def notice(self):
855 self._Load()
856 return self._notice
857
858 @property
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700859 def manifest_server(self):
860 self._Load()
Shawn O. Pearce34fb20f2011-11-30 13:41:02 -0800861 return self._manifest_server
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700862
863 @property
Xin Lid79a4bc2020-05-20 16:03:45 -0700864 def CloneBundle(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000865 clone_bundle = self.manifestProject.clone_bundle
Xin Lid79a4bc2020-05-20 16:03:45 -0700866 if clone_bundle is None:
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000867 return False if self.manifestProject.partial_clone else True
Xin Lid79a4bc2020-05-20 16:03:45 -0700868 else:
869 return clone_bundle
870
871 @property
Xin Li745be2e2019-06-03 11:24:30 -0700872 def CloneFilter(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000873 if self.manifestProject.partial_clone:
874 return self.manifestProject.clone_filter
Xin Li745be2e2019-06-03 11:24:30 -0700875 return None
876
877 @property
Raman Tennetif32f2432021-04-12 20:57:25 -0700878 def PartialCloneExclude(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000879 exclude = self.manifest.manifestProject.partial_clone_exclude or ''
Raman Tennetif32f2432021-04-12 20:57:25 -0700880 return set(x.strip() for x in exclude.split(','))
881
882 @property
Michael Kellyc34b91c2021-07-02 09:25:48 -0700883 def UseLocalManifests(self):
884 return self._load_local_manifests
885
886 def SetUseLocalManifests(self, value):
887 self._load_local_manifests = value
888
889 @property
Raman Tennetifeb28912021-05-02 19:47:29 -0700890 def HasLocalManifests(self):
891 return self._load_local_manifests and self.local_manifests
892
LaMont Jones87cce682022-02-14 17:48:31 +0000893 def IsFromLocalManifest(self, project):
LaMont Jonescc879a92021-11-18 22:40:18 +0000894 """Is the project from a local manifest?"""
LaMont Jones87cce682022-02-14 17:48:31 +0000895 return any(x.startswith(LOCAL_MANIFEST_GROUP_PREFIX)
896 for x in project.groups)
897
Raman Tennetifeb28912021-05-02 19:47:29 -0700898 @property
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800899 def IsMirror(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000900 return self.manifestProject.mirror
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800901
Julien Campergue335f5ef2013-10-16 11:02:35 +0200902 @property
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500903 def UseGitWorktrees(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000904 return self.manifestProject.use_worktree
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500905
906 @property
Julien Campergue335f5ef2013-10-16 11:02:35 +0200907 def IsArchive(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000908 return self.manifestProject.archive
Julien Campergue335f5ef2013-10-16 11:02:35 +0200909
Martin Kellye4e94d22017-03-21 16:05:12 -0700910 @property
911 def HasSubmodules(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000912 return self.manifestProject.submodules
Martin Kellye4e94d22017-03-21 16:05:12 -0700913
XD Trol630876f2022-01-17 23:29:04 +0800914 @property
915 def EnableGitLfs(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000916 return self.manifestProject.git_lfs
XD Trol630876f2022-01-17 23:29:04 +0800917
LaMont Jonescc879a92021-11-18 22:40:18 +0000918 def FindManifestByPath(self, path):
919 """Returns the manifest containing path."""
920 path = os.path.abspath(path)
921 manifest = self._outer_client or self
922 old = None
923 while manifest._submanifests and manifest != old:
924 old = manifest
925 for name in manifest._submanifests:
926 tree = manifest._submanifests[name]
927 if path.startswith(tree.repo_client.manifest.topdir):
928 manifest = tree.repo_client
929 break
930 return manifest
931
932 @property
933 def subdir(self):
934 """Returns the path for per-submanifest objects for this manifest."""
935 return self.SubmanifestInfoDir(self.path_prefix)
936
937 def SubmanifestInfoDir(self, submanifest_path, object_path=''):
938 """Return the path to submanifest-specific info for a submanifest.
939
940 Return the full path of the directory in which to put per-manifest objects.
941
942 Args:
943 submanifest_path: a string, the path of the submanifest, relative to the
944 outermost topdir. If empty, then repodir is returned.
945 object_path: a string, relative path to append to the submanifest info
946 directory path.
947 """
948 if submanifest_path:
949 return os.path.join(self.repodir, SUBMANIFEST_DIR, submanifest_path,
950 object_path)
951 else:
952 return os.path.join(self.repodir, object_path)
953
954 def SubmanifestProject(self, submanifest_path):
955 """Return a manifestProject for a submanifest."""
956 subdir = self.SubmanifestInfoDir(submanifest_path)
LaMont Jones9b72cf22022-03-29 21:54:22 +0000957 mp = ManifestProject(self, 'manifests',
958 gitdir=os.path.join(subdir, 'manifests.git'),
959 worktree=os.path.join(subdir, 'manifests'))
LaMont Jonescc879a92021-11-18 22:40:18 +0000960 return mp
961
Raman Tenneti080877e2021-03-09 15:19:06 -0800962 def GetDefaultGroupsStr(self):
963 """Returns the default group string for the platform."""
964 return 'default,platform-' + platform.system().lower()
965
966 def GetGroupsStr(self):
967 """Returns the manifest group string that should be synced."""
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000968 groups = self.manifestProject.manifest_groups
Raman Tenneti080877e2021-03-09 15:19:06 -0800969 if not groups:
970 groups = self.GetDefaultGroupsStr()
971 return groups
972
LaMont Jonesa2ff20d2022-04-07 16:49:06 +0000973 def Unload(self):
974 """Unload the manifest.
975
976 If the manifest files have been changed since Load() was called, this will
977 cause the new/updated manifest to be used.
978
979 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700980 self._loaded = False
981 self._projects = {}
David James8d201162013-10-11 17:03:19 -0700982 self._paths = {}
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700983 self._remotes = {}
984 self._default = None
LaMont Jonescc879a92021-11-18 22:40:18 +0000985 self._submanifests = {}
Doug Anderson37282b42011-03-04 11:54:18 -0800986 self._repo_hooks_project = None
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800987 self._superproject = {}
Raman Tenneti993af5e2021-05-12 12:00:31 -0700988 self._contactinfo = ContactInfo(Wrapper().BUG_URL)
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700989 self._notice = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700990 self.branch = None
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700991 self._manifest_server = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700992
LaMont Jonesa2ff20d2022-04-07 16:49:06 +0000993 def Load(self):
994 """Read the manifest into memory."""
995 # Do not expose internal arguments.
996 self._Load()
997
LaMont Jonescc879a92021-11-18 22:40:18 +0000998 def _Load(self, initial_client=None, submanifest_depth=0):
999 if submanifest_depth > MAX_SUBMANIFEST_DEPTH:
1000 raise ManifestParseError('maximum submanifest depth %d exceeded.' %
1001 MAX_SUBMANIFEST_DEPTH)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001002 if not self._loaded:
LaMont Jonescc879a92021-11-18 22:40:18 +00001003 if self._outer_client and self._outer_client != self:
1004 # This will load all clients.
1005 self._outer_client._Load(initial_client=self)
1006
Shawn O. Pearce2450a292008-11-04 08:22:07 -08001007 m = self.manifestProject
1008 b = m.GetBranch(m.CurrentBranch).merge
Shawn O. Pearce21c5c342009-06-25 16:47:30 -07001009 if b is not None and b.startswith(R_HEADS):
Shawn O. Pearce2450a292008-11-04 08:22:07 -08001010 b = b[len(R_HEADS):]
1011 self.branch = b
1012
LaMont Jonescc879a92021-11-18 22:40:18 +00001013 parent_groups = self.parent_groups
LaMont Jonesb308db12022-02-25 17:05:21 +00001014 if self.path_prefix:
1015 parent_groups = f'{SUBMANIFEST_GROUP_PREFIX}:path:{self.path_prefix},{parent_groups}'
LaMont Jonescc879a92021-11-18 22:40:18 +00001016
Mike Frysinger54133972021-03-01 21:38:08 -05001017 # The manifestFile was specified by the user which is why we allow include
1018 # paths to point anywhere.
Colin Cross23acdd32012-04-21 00:33:54 -07001019 nodes = []
Mike Frysinger54133972021-03-01 21:38:08 -05001020 nodes.append(self._ParseManifestXml(
1021 self.manifestFile, self.manifestProject.worktree,
LaMont Jonescc879a92021-11-18 22:40:18 +00001022 parent_groups=parent_groups, restrict_includes=False))
Shawn O. Pearce5cc66792008-10-23 16:19:27 -07001023
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001024 if self._load_local_manifests and self.local_manifests:
Basil Gelloc7453502018-05-25 20:23:52 +03001025 try:
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001026 for local_file in sorted(platform_utils.listdir(self.local_manifests)):
Basil Gelloc7453502018-05-25 20:23:52 +03001027 if local_file.endswith('.xml'):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001028 local = os.path.join(self.local_manifests, local_file)
Mike Frysinger54133972021-03-01 21:38:08 -05001029 # Since local manifests are entirely managed by the user, allow
1030 # them to point anywhere the user wants.
LaMont Jonescc879a92021-11-18 22:40:18 +00001031 local_group = f'{LOCAL_MANIFEST_GROUP_PREFIX}:{local_file[:-4]}'
Mike Frysinger54133972021-03-01 21:38:08 -05001032 nodes.append(self._ParseManifestXml(
LaMont Jonescc879a92021-11-18 22:40:18 +00001033 local, self.subdir,
1034 parent_groups=f'{local_group},{parent_groups}',
Raman Tenneti78f4dd32021-06-07 13:27:37 -07001035 restrict_includes=False))
Basil Gelloc7453502018-05-25 20:23:52 +03001036 except OSError:
1037 pass
David Pursehouse2d5a0df2012-11-13 02:50:36 +09001038
Joe Onorato26e24752013-01-11 12:35:53 -08001039 try:
1040 self._ParseManifest(nodes)
1041 except ManifestParseError as e:
1042 # There was a problem parsing, unload ourselves in case they catch
1043 # this error and try again later, we will show the correct error
LaMont Jonesa2ff20d2022-04-07 16:49:06 +00001044 self.Unload()
Joe Onorato26e24752013-01-11 12:35:53 -08001045 raise e
Shawn O. Pearce5cc66792008-10-23 16:19:27 -07001046
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001047 if self.IsMirror:
1048 self._AddMetaProjectMirror(self.repoProject)
1049 self._AddMetaProjectMirror(self.manifestProject)
1050
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001051 self._loaded = True
1052
LaMont Jonescc879a92021-11-18 22:40:18 +00001053 # Now that we have loaded this manifest, load any submanifest manifests
1054 # as well. We need to do this after self._loaded is set to avoid looping.
1055 if self._outer_client:
1056 for name in self._submanifests:
1057 tree = self._submanifests[name]
1058 spec = tree.ToSubmanifestSpec(self)
1059 present = os.path.exists(os.path.join(self.subdir, MANIFEST_FILE_NAME))
1060 if present and tree.present and not tree.repo_client:
1061 if initial_client and initial_client.topdir == self.topdir:
1062 tree.repo_client = self
1063 tree.present = present
1064 elif not os.path.exists(self.subdir):
1065 tree.present = False
LaMont Jones55ee3042022-04-06 17:10:21 +00001066 if present and tree.present:
LaMont Jonescc879a92021-11-18 22:40:18 +00001067 tree.repo_client._Load(initial_client=initial_client,
1068 submanifest_depth=submanifest_depth + 1)
1069
Mike Frysinger54133972021-03-01 21:38:08 -05001070 def _ParseManifestXml(self, path, include_root, parent_groups='',
1071 restrict_includes=True):
1072 """Parse a manifest XML and return the computed nodes.
1073
1074 Args:
1075 path: The XML file to read & parse.
1076 include_root: The path to interpret include "name"s relative to.
1077 parent_groups: The groups to apply to this projects.
1078 restrict_includes: Whether to constrain the "name" attribute of includes.
1079
1080 Returns:
1081 List of XML nodes.
1082 """
David Pursehousef7fc8a92012-11-13 04:00:28 +09001083 try:
1084 root = xml.dom.minidom.parse(path)
David Pursehouse2d5a0df2012-11-13 02:50:36 +09001085 except (OSError, xml.parsers.expat.ExpatError) as e:
David Pursehousef7fc8a92012-11-13 04:00:28 +09001086 raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
1087
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001088 if not root or not root.childNodes:
Brian Harring26448742011-04-28 05:04:41 -07001089 raise ManifestParseError("no root node in %s" % (path,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001090
Jooncheol Park34acdd22012-08-27 02:25:59 +09001091 for manifest in root.childNodes:
1092 if manifest.nodeName == 'manifest':
1093 break
1094 else:
Brian Harring26448742011-04-28 05:04:41 -07001095 raise ManifestParseError("no <manifest> in %s" % (path,))
1096
Colin Cross23acdd32012-04-21 00:33:54 -07001097 nodes = []
David Pursehouse65b0ba52018-06-24 16:21:51 +09001098 for node in manifest.childNodes:
David Pursehousec1b86a22012-11-14 11:36:51 +09001099 if node.nodeName == 'include':
1100 name = self._reqatt(node, 'name')
Mike Frysinger54133972021-03-01 21:38:08 -05001101 if restrict_includes:
1102 msg = self._CheckLocalPath(name)
1103 if msg:
1104 raise ManifestInvalidPathError(
1105 '<include> invalid "name": %s: %s' % (name, msg))
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001106 include_groups = ''
1107 if parent_groups:
1108 include_groups = parent_groups
1109 if node.hasAttribute('groups'):
1110 include_groups = node.getAttribute('groups') + ',' + include_groups
David Pursehousec1b86a22012-11-14 11:36:51 +09001111 fp = os.path.join(include_root, name)
1112 if not os.path.isfile(fp):
Mike Frysinger54133972021-03-01 21:38:08 -05001113 raise ManifestParseError("include [%s/]%s doesn't exist or isn't a file"
1114 % (include_root, name))
David Pursehousec1b86a22012-11-14 11:36:51 +09001115 try:
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001116 nodes.extend(self._ParseManifestXml(fp, include_root, include_groups))
David Pursehousec1b86a22012-11-14 11:36:51 +09001117 # should isolate this to the exact exception, but that's
1118 # tricky. actual parsing implementation may vary.
Mike Frysinger54133972021-03-01 21:38:08 -05001119 except (KeyboardInterrupt, RuntimeError, SystemExit, ManifestParseError):
David Pursehousec1b86a22012-11-14 11:36:51 +09001120 raise
1121 except Exception as e:
1122 raise ManifestParseError(
Mike Frysingerec558df2019-07-05 01:38:05 -04001123 "failed parsing included manifest %s: %s" % (name, e))
David Pursehousec1b86a22012-11-14 11:36:51 +09001124 else:
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001125 if parent_groups and node.nodeName == 'project':
1126 nodeGroups = parent_groups
1127 if node.hasAttribute('groups'):
1128 nodeGroups = node.getAttribute('groups') + ',' + nodeGroups
1129 node.setAttribute('groups', nodeGroups)
David Pursehousec1b86a22012-11-14 11:36:51 +09001130 nodes.append(node)
Colin Cross23acdd32012-04-21 00:33:54 -07001131 return nodes
Brian Harring26448742011-04-28 05:04:41 -07001132
Colin Cross23acdd32012-04-21 00:33:54 -07001133 def _ParseManifest(self, node_list):
1134 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001135 if node.nodeName == 'remote':
1136 remote = self._ParseRemote(node)
David Pursehouse717ece92012-11-13 08:49:16 +09001137 if remote:
1138 if remote.name in self._remotes:
1139 if remote != self._remotes[remote.name]:
1140 raise ManifestParseError(
1141 'remote %s already exists with different attributes' %
1142 (remote.name))
1143 else:
1144 self._remotes[remote.name] = remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001145
Colin Cross23acdd32012-04-21 00:33:54 -07001146 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001147 if node.nodeName == 'default':
Julien Campergue74879922013-10-09 14:38:46 +02001148 new_default = self._ParseDefault(node)
Jack Neusb8c84482021-06-15 14:28:30 +00001149 emptyDefault = not node.hasAttributes() and not node.hasChildNodes()
Julien Campergue74879922013-10-09 14:38:46 +02001150 if self._default is None:
1151 self._default = new_default
Jack Neusb8c84482021-06-15 14:28:30 +00001152 elif not emptyDefault and new_default != self._default:
David Pursehouse37128b62013-10-15 10:48:40 +09001153 raise ManifestParseError('duplicate default in %s' %
1154 (self.manifestFile))
Julien Campergue74879922013-10-09 14:38:46 +02001155
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001156 if self._default is None:
1157 self._default = _Default()
1158
LaMont Jonescc879a92021-11-18 22:40:18 +00001159 submanifest_paths = set()
1160 for node in itertools.chain(*node_list):
1161 if node.nodeName == 'submanifest':
1162 submanifest = self._ParseSubmanifest(node)
1163 if submanifest:
1164 if submanifest.name in self._submanifests:
1165 if submanifest != self._submanifests[submanifest.name]:
1166 raise ManifestParseError(
1167 'submanifest %s already exists with different attributes' %
1168 (submanifest.name))
1169 else:
1170 self._submanifests[submanifest.name] = submanifest
1171 submanifest_paths.add(submanifest.relpath)
1172
Colin Cross23acdd32012-04-21 00:33:54 -07001173 for node in itertools.chain(*node_list):
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001174 if node.nodeName == 'notice':
1175 if self._notice is not None:
Doug Anderson37282b42011-03-04 11:54:18 -08001176 raise ManifestParseError(
1177 'duplicate notice in %s' %
1178 (self.manifestFile))
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001179 self._notice = self._ParseNotice(node)
1180
Colin Cross23acdd32012-04-21 00:33:54 -07001181 for node in itertools.chain(*node_list):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001182 if node.nodeName == 'manifest-server':
1183 url = self._reqatt(node, 'url')
1184 if self._manifest_server is not None:
David Pursehousec1b86a22012-11-14 11:36:51 +09001185 raise ManifestParseError(
1186 'duplicate manifest-server in %s' %
1187 (self.manifestFile))
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001188 self._manifest_server = url
1189
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001190 def recursively_add_projects(project):
David James8d201162013-10-11 17:03:19 -07001191 projects = self._projects.setdefault(project.name, [])
1192 if project.relpath is None:
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001193 raise ManifestParseError(
David James8d201162013-10-11 17:03:19 -07001194 'missing path for %s in %s' %
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001195 (project.name, self.manifestFile))
David James8d201162013-10-11 17:03:19 -07001196 if project.relpath in self._paths:
1197 raise ManifestParseError(
1198 'duplicate path %s in %s' %
1199 (project.relpath, self.manifestFile))
LaMont Jonescc879a92021-11-18 22:40:18 +00001200 for tree in submanifest_paths:
1201 if project.relpath.startswith(tree):
1202 raise ManifestParseError(
1203 'project %s conflicts with submanifest path %s' %
1204 (project.relpath, tree))
David James8d201162013-10-11 17:03:19 -07001205 self._paths[project.relpath] = project
1206 projects.append(project)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001207 for subproject in project.subprojects:
1208 recursively_add_projects(subproject)
1209
Jack Neusa84f43a2021-09-21 22:23:55 +00001210 repo_hooks_project = None
1211 enabled_repo_hooks = None
Colin Cross23acdd32012-04-21 00:33:54 -07001212 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001213 if node.nodeName == 'project':
1214 project = self._ParseProject(node)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001215 recursively_add_projects(project)
Josh Triplett884a3872014-06-12 14:57:29 -07001216 if node.nodeName == 'extend-project':
1217 name = self._reqatt(node, 'name')
1218
1219 if name not in self._projects:
1220 raise ManifestParseError('extend-project element specifies non-existent '
1221 'project: %s' % name)
1222
1223 path = node.getAttribute('path')
Michael Kelly37c21c22020-06-13 02:10:40 -07001224 dest_path = node.getAttribute('dest-path')
Josh Triplett884a3872014-06-12 14:57:29 -07001225 groups = node.getAttribute('groups')
1226 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -05001227 groups = self._ParseList(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -07001228 revision = node.getAttribute('revision')
LaMont Jonescc879a92021-11-18 22:40:18 +00001229 remote_name = node.getAttribute('remote')
1230 if not remote_name:
1231 remote = self._default.remote
1232 else:
Kyunam Jobd0aae92020-02-04 11:38:53 +09001233 remote = self._get_remote(node)
Josh Triplett884a3872014-06-12 14:57:29 -07001234
Michael Kelly37c21c22020-06-13 02:10:40 -07001235 named_projects = self._projects[name]
1236 if dest_path and not path and len(named_projects) > 1:
1237 raise ManifestParseError('extend-project cannot use dest-path when '
1238 'matching multiple projects: %s' % name)
Josh Triplett884a3872014-06-12 14:57:29 -07001239 for p in self._projects[name]:
1240 if path and p.relpath != path:
1241 continue
1242 if groups:
1243 p.groups.extend(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -07001244 if revision:
Michael Kelly2f3c3312020-07-21 19:40:38 -07001245 p.SetRevision(revision)
1246
LaMont Jonescc879a92021-11-18 22:40:18 +00001247 if remote_name:
Kyunam Jobd0aae92020-02-04 11:38:53 +09001248 p.remote = remote.ToRemoteSpec(name)
Michael Kelly2f3c3312020-07-21 19:40:38 -07001249
Michael Kelly37c21c22020-06-13 02:10:40 -07001250 if dest_path:
1251 del self._paths[p.relpath]
LaMont Jonescc879a92021-11-18 22:40:18 +00001252 relpath, worktree, gitdir, objdir, _ = self.GetProjectPaths(
1253 name, dest_path, remote.name)
Michael Kelly37c21c22020-06-13 02:10:40 -07001254 p.UpdatePaths(relpath, worktree, gitdir, objdir)
1255 self._paths[p.relpath] = p
1256
Doug Anderson37282b42011-03-04 11:54:18 -08001257 if node.nodeName == 'repo-hooks':
Doug Anderson37282b42011-03-04 11:54:18 -08001258 # Only one project can be the hooks project
Jack Neusa84f43a2021-09-21 22:23:55 +00001259 if repo_hooks_project is not None:
Doug Anderson37282b42011-03-04 11:54:18 -08001260 raise ManifestParseError(
1261 'duplicate repo-hooks in %s' %
1262 (self.manifestFile))
1263
Jack Neusa84f43a2021-09-21 22:23:55 +00001264 # Get the name of the project and the (space-separated) list of enabled.
1265 repo_hooks_project = self._reqatt(node, 'in-project')
1266 enabled_repo_hooks = self._ParseList(self._reqatt(node, 'enabled-list'))
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001267 if node.nodeName == 'superproject':
1268 name = self._reqatt(node, 'name')
1269 # There can only be one superproject.
1270 if self._superproject.get('name'):
1271 raise ManifestParseError(
1272 'duplicate superproject in %s' %
1273 (self.manifestFile))
1274 self._superproject['name'] = name
1275 remote_name = node.getAttribute('remote')
1276 if not remote_name:
1277 remote = self._default.remote
1278 else:
1279 remote = self._get_remote(node)
1280 if remote is None:
1281 raise ManifestParseError("no remote for superproject %s within %s" %
1282 (name, self.manifestFile))
1283 self._superproject['remote'] = remote.ToRemoteSpec(name)
Xin Lie0b16a22021-09-26 23:20:32 -07001284 revision = node.getAttribute('revision') or remote.revision
1285 if not revision:
1286 revision = self._default.revisionExpr
1287 if not revision:
1288 raise ManifestParseError('no revision for superproject %s within %s' %
1289 (name, self.manifestFile))
1290 self._superproject['revision'] = revision
Raman Tenneti1c3f57e2021-05-04 12:32:13 -07001291 if node.nodeName == 'contactinfo':
1292 bugurl = self._reqatt(node, 'bugurl')
1293 # This element can be repeated, later entries will clobber earlier ones.
Raman Tenneti993af5e2021-05-12 12:00:31 -07001294 self._contactinfo = ContactInfo(bugurl)
1295
Colin Cross23acdd32012-04-21 00:33:54 -07001296 if node.nodeName == 'remove-project':
1297 name = self._reqatt(node, 'name')
David Jamesb8433df2014-01-30 10:11:17 -08001298
Michael Kelly06da9982021-06-30 01:58:28 -07001299 if name in self._projects:
1300 for p in self._projects[name]:
1301 del self._paths[p.relpath]
1302 del self._projects[name]
1303
1304 # If the manifest removes the hooks project, treat it as if it deleted
1305 # the repo-hooks element too.
Jack Neusa84f43a2021-09-21 22:23:55 +00001306 if repo_hooks_project == name:
1307 repo_hooks_project = None
Michael Kelly06da9982021-06-30 01:58:28 -07001308 elif not XmlBool(node, 'optional', False):
David Pursehousef9107482012-11-16 19:12:32 +09001309 raise ManifestParseError('remove-project element specifies non-existent '
1310 'project: %s' % name)
Colin Cross23acdd32012-04-21 00:33:54 -07001311
Jack Neusa84f43a2021-09-21 22:23:55 +00001312 # Store repo hooks project information.
1313 if repo_hooks_project:
1314 # Store a reference to the Project.
1315 try:
1316 repo_hooks_projects = self._projects[repo_hooks_project]
1317 except KeyError:
1318 raise ManifestParseError(
1319 'project %s not found for repo-hooks' %
1320 (repo_hooks_project))
1321
1322 if len(repo_hooks_projects) != 1:
1323 raise ManifestParseError(
1324 'internal error parsing repo-hooks in %s' %
1325 (self.manifestFile))
1326 self._repo_hooks_project = repo_hooks_projects[0]
1327 # Store the enabled hooks in the Project object.
1328 self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
1329
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001330 def _AddMetaProjectMirror(self, m):
1331 name = None
1332 m_url = m.GetRemote(m.remote.name).url
1333 if m_url.endswith('/.git'):
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301334 raise ManifestParseError('refusing to mirror %s' % m_url)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001335
1336 if self._default and self._default.remote:
Conley Owensceea3682011-10-20 10:45:47 -07001337 url = self._default.remote.resolvedFetchUrl
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001338 if not url.endswith('/'):
1339 url += '/'
1340 if m_url.startswith(url):
1341 remote = self._default.remote
1342 name = m_url[len(url):]
1343
1344 if name is None:
1345 s = m_url.rindex('/') + 1
Conley Owensdb728cd2011-09-26 16:34:01 -07001346 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Shawn O. Pearcef35b2d92012-08-02 11:46:22 -07001347 remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001348 name = m_url[s:]
1349
1350 if name.endswith('.git'):
1351 name = name[:-4]
1352
1353 if name not in self._projects:
1354 m.PreSync()
1355 gitdir = os.path.join(self.topdir, '%s.git' % name)
David Pursehousee5913ae2020-02-12 13:56:59 +09001356 project = Project(manifest=self,
1357 name=name,
1358 remote=remote.ToRemoteSpec(name),
1359 gitdir=gitdir,
1360 objdir=gitdir,
1361 worktree=None,
1362 relpath=name or None,
1363 revisionExpr=m.revisionExpr,
1364 revisionId=None)
David James8d201162013-10-11 17:03:19 -07001365 self._projects[project.name] = [project]
Kwanhong Leeccd218c2014-02-17 13:07:32 +09001366 self._paths[project.relpath] = project
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001367
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001368 def _ParseRemote(self, node):
1369 """
1370 reads a <remote> element from the manifest file
1371 """
1372 name = self._reqatt(node, 'name')
Yestin Sunb292b982012-07-02 07:32:50 -07001373 alias = node.getAttribute('alias')
1374 if alias == '':
1375 alias = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001376 fetch = self._reqatt(node, 'fetch')
Steve Raed6480452016-08-10 15:00:00 -07001377 pushUrl = node.getAttribute('pushurl')
1378 if pushUrl == '':
1379 pushUrl = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001380 review = node.getAttribute('review')
Shawn O. Pearceae6e0942008-11-06 10:25:35 -08001381 if review == '':
1382 review = None
Anthony King36ea2fb2014-05-06 11:54:01 +01001383 revision = node.getAttribute('revision')
1384 if revision == '':
1385 revision = None
Conley Owensdb728cd2011-09-26 16:34:01 -07001386 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Jack Neus6ea0cae2021-07-20 20:52:33 +00001387
1388 remote = _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
1389
1390 for n in node.childNodes:
1391 if n.nodeName == 'annotation':
1392 self._ParseAnnotation(remote, n)
1393
1394 return remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001395
1396 def _ParseDefault(self, node):
1397 """
1398 reads a <default> element from the manifest file
1399 """
1400 d = _Default()
1401 d.remote = self._get_remote(node)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001402 d.revisionExpr = node.getAttribute('revision')
1403 if d.revisionExpr == '':
1404 d.revisionExpr = None
Anatol Pomazau79770d22012-04-20 14:41:59 -07001405
Bryan Jacobsf609f912013-05-06 13:36:24 -04001406 d.destBranchExpr = node.getAttribute('dest-branch') or None
Nasser Grainawida403412018-05-04 12:53:29 -06001407 d.upstreamExpr = node.getAttribute('upstream') or None
Bryan Jacobsf609f912013-05-06 13:36:24 -04001408
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001409 d.sync_j = XmlInt(node, 'sync-j', 1)
1410 if d.sync_j <= 0:
1411 raise ManifestParseError('%s: sync-j must be greater than 0, not "%s"' %
1412 (self.manifestFile, d.sync_j))
Anatol Pomazau79770d22012-04-20 14:41:59 -07001413
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001414 d.sync_c = XmlBool(node, 'sync-c', False)
1415 d.sync_s = XmlBool(node, 'sync-s', False)
1416 d.sync_tags = XmlBool(node, 'sync-tags', True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001417 return d
1418
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001419 def _ParseNotice(self, node):
1420 """
1421 reads a <notice> element from the manifest file
1422
1423 The <notice> element is distinct from other tags in the XML in that the
1424 data is conveyed between the start and end tag (it's not an empty-element
1425 tag).
1426
1427 The white space (carriage returns, indentation) for the notice element is
1428 relevant and is parsed in a way that is based on how python docstrings work.
1429 In fact, the code is remarkably similar to here:
1430 http://www.python.org/dev/peps/pep-0257/
1431 """
1432 # Get the data out of the node...
1433 notice = node.childNodes[0].data
1434
1435 # Figure out minimum indentation, skipping the first line (the same line
1436 # as the <notice> tag)...
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301437 minIndent = sys.maxsize
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001438 lines = notice.splitlines()
1439 for line in lines[1:]:
1440 lstrippedLine = line.lstrip()
1441 if lstrippedLine:
1442 indent = len(line) - len(lstrippedLine)
1443 minIndent = min(indent, minIndent)
1444
1445 # Strip leading / trailing blank lines and also indentation.
1446 cleanLines = [lines[0].strip()]
1447 for line in lines[1:]:
1448 cleanLines.append(line[minIndent:].rstrip())
1449
1450 # Clear completely blank lines from front and back...
1451 while cleanLines and not cleanLines[0]:
1452 del cleanLines[0]
1453 while cleanLines and not cleanLines[-1]:
1454 del cleanLines[-1]
1455
1456 return '\n'.join(cleanLines)
1457
LaMont Jonescc879a92021-11-18 22:40:18 +00001458 def _ParseSubmanifest(self, node):
1459 """Reads a <submanifest> element from the manifest file."""
1460 name = self._reqatt(node, 'name')
1461 remote = node.getAttribute('remote')
1462 if remote == '':
1463 remote = None
1464 project = node.getAttribute('project')
1465 if project == '':
1466 project = None
1467 revision = node.getAttribute('revision')
1468 if revision == '':
1469 revision = None
1470 manifestName = node.getAttribute('manifest-name')
1471 if manifestName == '':
1472 manifestName = None
1473 groups = ''
1474 if node.hasAttribute('groups'):
1475 groups = node.getAttribute('groups')
1476 groups = self._ParseList(groups)
1477 path = node.getAttribute('path')
1478 if path == '':
1479 path = None
1480 if revision:
1481 msg = self._CheckLocalPath(revision.split('/')[-1])
1482 if msg:
1483 raise ManifestInvalidPathError(
1484 '<submanifest> invalid "revision": %s: %s' % (revision, msg))
1485 else:
1486 msg = self._CheckLocalPath(name)
1487 if msg:
1488 raise ManifestInvalidPathError(
1489 '<submanifest> invalid "name": %s: %s' % (name, msg))
1490 else:
1491 msg = self._CheckLocalPath(path)
1492 if msg:
1493 raise ManifestInvalidPathError(
1494 '<submanifest> invalid "path": %s: %s' % (path, msg))
1495
1496 submanifest = _XmlSubmanifest(name, remote, project, revision, manifestName,
1497 groups, path, self)
1498
1499 for n in node.childNodes:
1500 if n.nodeName == 'annotation':
1501 self._ParseAnnotation(submanifest, n)
1502
1503 return submanifest
1504
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001505 def _JoinName(self, parent_name, name):
1506 return os.path.join(parent_name, name)
1507
1508 def _UnjoinName(self, parent_name, name):
1509 return os.path.relpath(name, parent_name)
1510
David Pursehousee5913ae2020-02-12 13:56:59 +09001511 def _ParseProject(self, node, parent=None, **extra_proj_attrs):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001512 """
1513 reads a <project> element from the manifest file
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001514 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001515 name = self._reqatt(node, 'name')
Mike Frysingera29424e2021-02-25 21:53:49 -05001516 msg = self._CheckLocalPath(name, dir_ok=True)
1517 if msg:
1518 raise ManifestInvalidPathError(
1519 '<project> invalid "name": %s: %s' % (name, msg))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001520 if parent:
1521 name = self._JoinName(parent.name, name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001522
1523 remote = self._get_remote(node)
1524 if remote is None:
1525 remote = self._default.remote
1526 if remote is None:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301527 raise ManifestParseError("no remote for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001528 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001529
Anthony King36ea2fb2014-05-06 11:54:01 +01001530 revisionExpr = node.getAttribute('revision') or remote.revision
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001531 if not revisionExpr:
1532 revisionExpr = self._default.revisionExpr
1533 if not revisionExpr:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301534 raise ManifestParseError("no revision for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001535 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001536
1537 path = node.getAttribute('path')
1538 if not path:
1539 path = name
Mike Frysingera29424e2021-02-25 21:53:49 -05001540 else:
Mike Frysinger0458faa2021-03-10 23:35:44 -05001541 # NB: The "." project is handled specially in Project.Sync_LocalHalf.
1542 msg = self._CheckLocalPath(path, dir_ok=True, cwd_dot_ok=True)
Mike Frysingera29424e2021-02-25 21:53:49 -05001543 if msg:
1544 raise ManifestInvalidPathError(
1545 '<project> invalid "path": %s: %s' % (path, msg))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001546
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001547 rebase = XmlBool(node, 'rebase', True)
1548 sync_c = XmlBool(node, 'sync-c', False)
1549 sync_s = XmlBool(node, 'sync-s', self._default.sync_s)
1550 sync_tags = XmlBool(node, 'sync-tags', self._default.sync_tags)
Mike Pontillod3153822012-02-28 11:53:24 -08001551
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001552 clone_depth = XmlInt(node, 'clone-depth')
1553 if clone_depth is not None and clone_depth <= 0:
1554 raise ManifestParseError('%s: clone-depth must be greater than 0, not "%s"' %
1555 (self.manifestFile, clone_depth))
David Pursehouseede7f122012-11-27 22:25:30 +09001556
Bryan Jacobsf609f912013-05-06 13:36:24 -04001557 dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
1558
Nasser Grainawida403412018-05-04 12:53:29 -06001559 upstream = node.getAttribute('upstream') or self._default.upstreamExpr
Brian Harring14a66742012-09-28 20:21:57 -07001560
Conley Owens971de8e2012-04-16 10:36:08 -07001561 groups = ''
1562 if node.hasAttribute('groups'):
1563 groups = node.getAttribute('groups')
Mike Frysinger51e39d52020-12-04 05:32:06 -05001564 groups = self._ParseList(groups)
Brian Harring7da13142012-06-15 02:24:20 -07001565
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001566 if parent is None:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001567 relpath, worktree, gitdir, objdir, use_git_worktrees = \
LaMont Jonescc879a92021-11-18 22:40:18 +00001568 self.GetProjectPaths(name, path, remote.name)
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001569 else:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001570 use_git_worktrees = False
David James8d201162013-10-11 17:03:19 -07001571 relpath, worktree, gitdir, objdir = \
1572 self.GetSubprojectPaths(parent, name, path)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001573
1574 default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
1575 groups.extend(set(default_groups).difference(groups))
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001576
Scott Fandb83b1b2013-02-28 09:34:14 +08001577 if self.IsMirror and node.hasAttribute('force-path'):
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001578 if XmlBool(node, 'force-path', False):
Scott Fandb83b1b2013-02-28 09:34:14 +08001579 gitdir = os.path.join(self.topdir, '%s.git' % path)
1580
David Pursehousee5913ae2020-02-12 13:56:59 +09001581 project = Project(manifest=self,
1582 name=name,
1583 remote=remote.ToRemoteSpec(name),
1584 gitdir=gitdir,
1585 objdir=objdir,
1586 worktree=worktree,
1587 relpath=relpath,
1588 revisionExpr=revisionExpr,
1589 revisionId=None,
1590 rebase=rebase,
1591 groups=groups,
1592 sync_c=sync_c,
1593 sync_s=sync_s,
1594 sync_tags=sync_tags,
1595 clone_depth=clone_depth,
1596 upstream=upstream,
1597 parent=parent,
1598 dest_branch=dest_branch,
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001599 use_git_worktrees=use_git_worktrees,
Simran Basib9a1b732015-08-20 12:19:28 -07001600 **extra_proj_attrs)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001601
1602 for n in node.childNodes:
Shawn O. Pearce242b5262009-05-19 13:00:29 -07001603 if n.nodeName == 'copyfile':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001604 self._ParseCopyFile(project, n)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001605 if n.nodeName == 'linkfile':
1606 self._ParseLinkFile(project, n)
James W. Mills24c13082012-04-12 15:04:13 -05001607 if n.nodeName == 'annotation':
1608 self._ParseAnnotation(project, n)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001609 if n.nodeName == 'project':
David Pursehousee5913ae2020-02-12 13:56:59 +09001610 project.subprojects.append(self._ParseProject(n, parent=project))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001611
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001612 return project
1613
LaMont Jonescc879a92021-11-18 22:40:18 +00001614 def GetProjectPaths(self, name, path, remote):
1615 """Return the paths for a project.
1616
1617 Args:
1618 name: a string, the name of the project.
1619 path: a string, the path of the project.
1620 remote: a string, the remote.name of the project.
1621 """
Mike Frysingercebf2272020-05-26 01:02:29 -04001622 # The manifest entries might have trailing slashes. Normalize them to avoid
1623 # unexpected filesystem behavior since we do string concatenation below.
1624 path = path.rstrip('/')
1625 name = name.rstrip('/')
LaMont Jonescc879a92021-11-18 22:40:18 +00001626 remote = remote.rstrip('/')
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001627 use_git_worktrees = False
LaMont Jonescc879a92021-11-18 22:40:18 +00001628 use_remote_name = bool(self._outer_client._submanifests)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001629 relpath = path
1630 if self.IsMirror:
1631 worktree = None
1632 gitdir = os.path.join(self.topdir, '%s.git' % name)
David James8d201162013-10-11 17:03:19 -07001633 objdir = gitdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001634 else:
LaMont Jonescc879a92021-11-18 22:40:18 +00001635 if use_remote_name:
1636 namepath = os.path.join(remote, f'{name}.git')
1637 else:
1638 namepath = f'{name}.git'
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001639 worktree = os.path.join(self.topdir, path).replace('\\', '/')
LaMont Jonescc879a92021-11-18 22:40:18 +00001640 gitdir = os.path.join(self.subdir, 'projects', '%s.git' % path)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001641 # We allow people to mix git worktrees & non-git worktrees for now.
1642 # This allows for in situ migration of repo clients.
1643 if os.path.exists(gitdir) or not self.UseGitWorktrees:
LaMont Jonescc879a92021-11-18 22:40:18 +00001644 objdir = os.path.join(self.subdir, 'project-objects', namepath)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001645 else:
1646 use_git_worktrees = True
LaMont Jonescc879a92021-11-18 22:40:18 +00001647 gitdir = os.path.join(self.repodir, 'worktrees', namepath)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001648 objdir = gitdir
1649 return relpath, worktree, gitdir, objdir, use_git_worktrees
David James8d201162013-10-11 17:03:19 -07001650
LaMont Jonescc879a92021-11-18 22:40:18 +00001651 def GetProjectsWithName(self, name, all_manifests=False):
1652 """All projects with |name|.
1653
1654 Args:
1655 name: a string, the name of the project.
1656 all_manifests: a boolean, if True, then all manifests are searched. If
1657 False, then only this manifest is searched.
1658 """
1659 if all_manifests:
1660 return list(itertools.chain.from_iterable(
1661 x._projects.get(name, []) for x in self.all_manifests))
David James8d201162013-10-11 17:03:19 -07001662 return self._projects.get(name, [])
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001663
1664 def GetSubprojectName(self, parent, submodule_path):
1665 return os.path.join(parent.name, submodule_path)
1666
1667 def _JoinRelpath(self, parent_relpath, relpath):
1668 return os.path.join(parent_relpath, relpath)
1669
1670 def _UnjoinRelpath(self, parent_relpath, relpath):
1671 return os.path.relpath(relpath, parent_relpath)
1672
David James8d201162013-10-11 17:03:19 -07001673 def GetSubprojectPaths(self, parent, name, path):
Mike Frysingercebf2272020-05-26 01:02:29 -04001674 # The manifest entries might have trailing slashes. Normalize them to avoid
1675 # unexpected filesystem behavior since we do string concatenation below.
1676 path = path.rstrip('/')
1677 name = name.rstrip('/')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001678 relpath = self._JoinRelpath(parent.relpath, path)
1679 gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
David James8d201162013-10-11 17:03:19 -07001680 objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001681 if self.IsMirror:
1682 worktree = None
1683 else:
1684 worktree = os.path.join(parent.worktree, path).replace('\\', '/')
David James8d201162013-10-11 17:03:19 -07001685 return relpath, worktree, gitdir, objdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001686
Mike Frysinger04122b72019-07-31 23:32:58 -04001687 @staticmethod
Mike Frysingera00c5f42021-02-25 18:26:31 -05001688 def _CheckLocalPath(path, dir_ok=False, cwd_dot_ok=False):
1689 """Verify |path| is reasonable for use in filesystem paths.
1690
Mike Frysingera29424e2021-02-25 21:53:49 -05001691 Used with <copyfile> & <linkfile> & <project> elements.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001692
1693 This only validates the |path| in isolation: it does not check against the
1694 current filesystem state. Thus it is suitable as a first-past in a parser.
1695
1696 It enforces a number of constraints:
1697 * No empty paths.
1698 * No "~" in paths.
1699 * No Unicode codepoints that filesystems might elide when normalizing.
1700 * No relative path components like "." or "..".
1701 * No absolute paths.
1702 * No ".git" or ".repo*" path components.
1703
1704 Args:
1705 path: The path name to validate.
1706 dir_ok: Whether |path| may force a directory (e.g. end in a /).
1707 cwd_dot_ok: Whether |path| may be just ".".
1708
1709 Returns:
1710 None if |path| is OK, a failure message otherwise.
1711 """
1712 if not path:
1713 return 'empty paths not allowed'
1714
Mike Frysinger04122b72019-07-31 23:32:58 -04001715 if '~' in path:
1716 return '~ not allowed (due to 8.3 filenames on Windows filesystems)'
1717
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001718 path_codepoints = set(path)
1719
Mike Frysinger04122b72019-07-31 23:32:58 -04001720 # Some filesystems (like Apple's HFS+) try to normalize Unicode codepoints
1721 # which means there are alternative names for ".git". Reject paths with
1722 # these in it as there shouldn't be any reasonable need for them here.
1723 # The set of codepoints here was cribbed from jgit's implementation:
1724 # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
1725 BAD_CODEPOINTS = {
1726 u'\u200C', # ZERO WIDTH NON-JOINER
1727 u'\u200D', # ZERO WIDTH JOINER
1728 u'\u200E', # LEFT-TO-RIGHT MARK
1729 u'\u200F', # RIGHT-TO-LEFT MARK
1730 u'\u202A', # LEFT-TO-RIGHT EMBEDDING
1731 u'\u202B', # RIGHT-TO-LEFT EMBEDDING
1732 u'\u202C', # POP DIRECTIONAL FORMATTING
1733 u'\u202D', # LEFT-TO-RIGHT OVERRIDE
1734 u'\u202E', # RIGHT-TO-LEFT OVERRIDE
1735 u'\u206A', # INHIBIT SYMMETRIC SWAPPING
1736 u'\u206B', # ACTIVATE SYMMETRIC SWAPPING
1737 u'\u206C', # INHIBIT ARABIC FORM SHAPING
1738 u'\u206D', # ACTIVATE ARABIC FORM SHAPING
1739 u'\u206E', # NATIONAL DIGIT SHAPES
1740 u'\u206F', # NOMINAL DIGIT SHAPES
1741 u'\uFEFF', # ZERO WIDTH NO-BREAK SPACE
1742 }
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001743 if BAD_CODEPOINTS & path_codepoints:
Mike Frysinger04122b72019-07-31 23:32:58 -04001744 # This message is more expansive than reality, but should be fine.
1745 return 'Unicode combining characters not allowed'
1746
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001747 # Reject newlines as there shouldn't be any legitmate use for them, they'll
1748 # be confusing to users, and they can easily break tools that expect to be
1749 # able to iterate over newline delimited lists. This even applies to our
1750 # own code like .repo/project.list.
1751 if {'\r', '\n'} & path_codepoints:
1752 return 'Newlines not allowed'
1753
Mike Frysinger04122b72019-07-31 23:32:58 -04001754 # Assume paths might be used on case-insensitive filesystems.
1755 path = path.lower()
1756
Mike Frysingerd9254592020-02-19 22:36:26 -05001757 # Split up the path by its components. We can't use os.path.sep exclusively
1758 # as some platforms (like Windows) will convert / to \ and that bypasses all
1759 # our constructed logic here. Especially since manifest authors only use
1760 # / in their paths.
1761 resep = re.compile(r'[/%s]' % re.escape(os.path.sep))
Mike Frysinger0458faa2021-03-10 23:35:44 -05001762 # Strip off trailing slashes as those only produce '' elements, and we use
1763 # parts to look for individual bad components.
1764 parts = resep.split(path.rstrip('/'))
Mike Frysingerd9254592020-02-19 22:36:26 -05001765
Mike Frysingerae625412020-02-10 17:10:03 -05001766 # Some people use src="." to create stable links to projects. Lets allow
1767 # that but reject all other uses of "." to keep things simple.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001768 if not cwd_dot_ok or parts != ['.']:
Mike Frysingerae625412020-02-10 17:10:03 -05001769 for part in set(parts):
1770 if part in {'.', '..', '.git'} or part.startswith('.repo'):
1771 return 'bad component: %s' % (part,)
Mike Frysinger04122b72019-07-31 23:32:58 -04001772
Mike Frysingera00c5f42021-02-25 18:26:31 -05001773 if not dir_ok and resep.match(path[-1]):
Mike Frysinger04122b72019-07-31 23:32:58 -04001774 return 'dirs not allowed'
1775
Mike Frysingerd9254592020-02-19 22:36:26 -05001776 # NB: The two abspath checks here are to handle platforms with multiple
1777 # filesystem path styles (e.g. Windows).
Mike Frysinger04122b72019-07-31 23:32:58 -04001778 norm = os.path.normpath(path)
Mike Frysingerd9254592020-02-19 22:36:26 -05001779 if (norm == '..' or
1780 (len(norm) >= 3 and norm.startswith('..') and resep.match(norm[0])) or
1781 os.path.isabs(norm) or
1782 norm.startswith('/')):
Mike Frysinger04122b72019-07-31 23:32:58 -04001783 return 'path cannot be outside'
1784
1785 @classmethod
1786 def _ValidateFilePaths(cls, element, src, dest):
1787 """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
1788
1789 We verify the path independent of any filesystem state as we won't have a
1790 checkout available to compare to. i.e. This is for parsing validation
1791 purposes only.
1792
1793 We'll do full/live sanity checking before we do the actual filesystem
1794 modifications in _CopyFile/_LinkFile/etc...
1795 """
1796 # |dest| is the file we write to or symlink we create.
1797 # It is relative to the top of the repo client checkout.
1798 msg = cls._CheckLocalPath(dest)
1799 if msg:
1800 raise ManifestInvalidPathError(
1801 '<%s> invalid "dest": %s: %s' % (element, dest, msg))
1802
1803 # |src| is the file we read from or path we point to for symlinks.
1804 # It is relative to the top of the git project checkout.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001805 is_linkfile = element == 'linkfile'
1806 msg = cls._CheckLocalPath(src, dir_ok=is_linkfile, cwd_dot_ok=is_linkfile)
Mike Frysinger04122b72019-07-31 23:32:58 -04001807 if msg:
1808 raise ManifestInvalidPathError(
1809 '<%s> invalid "src": %s: %s' % (element, src, msg))
1810
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001811 def _ParseCopyFile(self, project, node):
1812 src = self._reqatt(node, 'src')
1813 dest = self._reqatt(node, 'dest')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001814 if not self.IsMirror:
1815 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001816 # dest is relative to the top of the tree.
1817 # We only validate paths if we actually plan to process them.
1818 self._ValidateFilePaths('copyfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001819 project.AddCopyFile(src, dest, self.topdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001820
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001821 def _ParseLinkFile(self, project, node):
1822 src = self._reqatt(node, 'src')
1823 dest = self._reqatt(node, 'dest')
1824 if not self.IsMirror:
1825 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001826 # dest is relative to the top of the tree.
1827 # We only validate paths if we actually plan to process them.
1828 self._ValidateFilePaths('linkfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001829 project.AddLinkFile(src, dest, self.topdir)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001830
Jack Neus6ea0cae2021-07-20 20:52:33 +00001831 def _ParseAnnotation(self, element, node):
James W. Mills24c13082012-04-12 15:04:13 -05001832 name = self._reqatt(node, 'name')
1833 value = self._reqatt(node, 'value')
1834 try:
1835 keep = self._reqatt(node, 'keep').lower()
1836 except ManifestParseError:
1837 keep = "true"
1838 if keep != "true" and keep != "false":
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301839 raise ManifestParseError('optional "keep" attribute must be '
David Pursehouseabdf7502020-02-12 14:58:39 +09001840 '"true" or "false"')
Jack Neus6ea0cae2021-07-20 20:52:33 +00001841 element.AddAnnotation(name, value, keep)
James W. Mills24c13082012-04-12 15:04:13 -05001842
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001843 def _get_remote(self, node):
1844 name = node.getAttribute('remote')
1845 if not name:
1846 return None
1847
1848 v = self._remotes.get(name)
1849 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301850 raise ManifestParseError("remote %s not defined in %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001851 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001852 return v
1853
1854 def _reqatt(self, node, attname):
1855 """
1856 reads a required attribute from the node.
1857 """
1858 v = node.getAttribute(attname)
1859 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301860 raise ManifestParseError("no %s in <%s> within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001861 (attname, node.nodeName, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001862 return v
Julien Camperguedd654222014-01-09 16:21:37 +01001863
1864 def projectsDiff(self, manifest):
1865 """return the projects differences between two manifests.
1866
1867 The diff will be from self to given manifest.
1868
1869 """
1870 fromProjects = self.paths
1871 toProjects = manifest.paths
1872
Anthony King7446c592014-05-06 09:19:39 +01001873 fromKeys = sorted(fromProjects.keys())
1874 toKeys = sorted(toProjects.keys())
Julien Camperguedd654222014-01-09 16:21:37 +01001875
1876 diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
1877
1878 for proj in fromKeys:
David Pursehouseeeff3532020-02-12 11:24:10 +09001879 if proj not in toKeys:
Julien Camperguedd654222014-01-09 16:21:37 +01001880 diff['removed'].append(fromProjects[proj])
1881 else:
1882 fromProj = fromProjects[proj]
1883 toProj = toProjects[proj]
1884 try:
1885 fromRevId = fromProj.GetCommitRevisionId()
1886 toRevId = toProj.GetCommitRevisionId()
1887 except ManifestInvalidRevisionError:
1888 diff['unreachable'].append((fromProj, toProj))
1889 else:
1890 if fromRevId != toRevId:
1891 diff['changed'].append((fromProj, toProj))
1892 toKeys.remove(proj)
1893
1894 for proj in toKeys:
1895 diff['added'].append(toProjects[proj])
1896
1897 return diff
Simran Basib9a1b732015-08-20 12:19:28 -07001898
1899
1900class GitcManifest(XmlManifest):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001901 """Parser for GitC (git-in-the-cloud) manifests."""
Simran Basib9a1b732015-08-20 12:19:28 -07001902
David Pursehousee5913ae2020-02-12 13:56:59 +09001903 def _ParseProject(self, node, parent=None):
Simran Basib9a1b732015-08-20 12:19:28 -07001904 """Override _ParseProject and add support for GITC specific attributes."""
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001905 return super()._ParseProject(
Simran Basib9a1b732015-08-20 12:19:28 -07001906 node, parent=parent, old_revision=node.getAttribute('old-revision'))
1907
1908 def _output_manifest_project_extras(self, p, e):
1909 """Output GITC Specific Project attributes"""
1910 if p.old_revision:
Stefan Beller66851062016-06-17 16:40:08 -07001911 e.setAttribute('old-revision', str(p.old_revision))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001912
1913
1914class RepoClient(XmlManifest):
1915 """Manages a repo client checkout."""
1916
LaMont Jonescc879a92021-11-18 22:40:18 +00001917 def __init__(self, repodir, manifest_file=None, submanifest_path='', **kwargs):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001918 self.isGitcClient = False
LaMont Jonescc879a92021-11-18 22:40:18 +00001919 submanifest_path = submanifest_path or ''
1920 if submanifest_path:
1921 self._CheckLocalPath(submanifest_path)
1922 prefix = os.path.join(repodir, SUBMANIFEST_DIR, submanifest_path)
1923 else:
1924 prefix = repodir
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001925
LaMont Jonescc879a92021-11-18 22:40:18 +00001926 if os.path.exists(os.path.join(prefix, LOCAL_MANIFEST_NAME)):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001927 print('error: %s is not supported; put local manifests in `%s` instead' %
LaMont Jonescc879a92021-11-18 22:40:18 +00001928 (LOCAL_MANIFEST_NAME, os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME)),
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001929 file=sys.stderr)
1930 sys.exit(1)
1931
1932 if manifest_file is None:
LaMont Jonescc879a92021-11-18 22:40:18 +00001933 manifest_file = os.path.join(prefix, MANIFEST_FILE_NAME)
1934 local_manifests = os.path.abspath(os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME))
1935 super().__init__(repodir, manifest_file, local_manifests,
1936 submanifest_path=submanifest_path, **kwargs)
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001937
1938 # TODO: Completely separate manifest logic out of the client.
1939 self.manifest = self
1940
1941
1942class GitcClient(RepoClient, GitcManifest):
1943 """Manages a GitC client checkout."""
1944
1945 def __init__(self, repodir, gitc_client_name):
1946 """Initialize the GitcManifest object."""
1947 self.gitc_client_name = gitc_client_name
1948 self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
1949 gitc_client_name)
1950
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001951 super().__init__(repodir, os.path.join(self.gitc_client_dir, '.manifest'))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001952 self.isGitcClient = True