blob: fa3e1034108f51938ca8f95e4a59417372a9bb47 [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
Jack Neus6ea0cae2021-07-20 20:52:33 +000028from project import Annotation, RemoteSpec, Project, MetaProject
Mike Frysinger04122b72019-07-31 23:32:58 -040029from error import (ManifestParseError, ManifestInvalidPathError,
30 ManifestInvalidRevisionError)
Raman Tenneti993af5e2021-05-12 12:00:31 -070031from wrapper import Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070032
33MANIFEST_FILE_NAME = 'manifest.xml'
Shawn O. Pearce5cc66792008-10-23 16:19:27 -070034LOCAL_MANIFEST_NAME = 'local_manifest.xml'
David Pursehouse2d5a0df2012-11-13 02:50:36 +090035LOCAL_MANIFESTS_DIR_NAME = 'local_manifests'
LaMont Jonescc879a92021-11-18 22:40:18 +000036SUBMANIFEST_DIR = 'submanifests'
37# Limit submanifests to an arbitrary depth for loop detection.
38MAX_SUBMANIFEST_DEPTH = 8
LaMont Jonesb308db12022-02-25 17:05:21 +000039# Add all projects from sub manifest into a group.
40SUBMANIFEST_GROUP_PREFIX = 'submanifest:'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070041
Raman Tenneti78f4dd32021-06-07 13:27:37 -070042# Add all projects from local manifest into a group.
43LOCAL_MANIFEST_GROUP_PREFIX = 'local:'
44
Raman Tenneti993af5e2021-05-12 12:00:31 -070045# ContactInfo has the self-registered bug url, supplied by the manifest authors.
46ContactInfo = collections.namedtuple('ContactInfo', 'bugurl')
47
Anthony Kingcb07ba72015-03-28 23:26:04 +000048# urljoin gets confused if the scheme is not known.
Joe Kilner6e310792016-10-27 15:53:53 -070049urllib.parse.uses_relative.extend([
50 'ssh',
51 'git',
52 'persistent-https',
53 'sso',
54 'rpc'])
55urllib.parse.uses_netloc.extend([
56 'ssh',
57 'git',
58 'persistent-https',
59 'sso',
60 'rpc'])
Conley Owensdb728cd2011-09-26 16:34:01 -070061
David Pursehouse819827a2020-02-12 15:20:19 +090062
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050063def XmlBool(node, attr, default=None):
64 """Determine boolean value of |node|'s |attr|.
65
66 Invalid values will issue a non-fatal warning.
67
68 Args:
69 node: XML node whose attributes we access.
70 attr: The attribute to access.
71 default: If the attribute is not set (value is empty), then use this.
72
73 Returns:
74 True if the attribute is a valid string representing true.
75 False if the attribute is a valid string representing false.
76 |default| otherwise.
77 """
78 value = node.getAttribute(attr)
79 s = value.lower()
80 if s == '':
81 return default
82 elif s in {'yes', 'true', '1'}:
83 return True
84 elif s in {'no', 'false', '0'}:
85 return False
86 else:
87 print('warning: manifest: %s="%s": ignoring invalid XML boolean' %
88 (attr, value), file=sys.stderr)
89 return default
90
91
92def XmlInt(node, attr, default=None):
93 """Determine integer value of |node|'s |attr|.
94
95 Args:
96 node: XML node whose attributes we access.
97 attr: The attribute to access.
98 default: If the attribute is not set (value is empty), then use this.
99
100 Returns:
101 The number if the attribute is a valid number.
102
103 Raises:
104 ManifestParseError: The number is invalid.
105 """
106 value = node.getAttribute(attr)
107 if not value:
108 return default
109
110 try:
111 return int(value)
112 except ValueError:
113 raise ManifestParseError('manifest: invalid %s="%s" integer' %
114 (attr, value))
115
116
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700117class _Default(object):
118 """Project defaults within the manifest."""
119
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700120 revisionExpr = None
Conley Owensb6a16e62013-09-25 15:06:09 -0700121 destBranchExpr = None
Nasser Grainawida403412018-05-04 12:53:29 -0600122 upstreamExpr = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700123 remote = None
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700124 sync_j = 1
Anatol Pomazau79770d22012-04-20 14:41:59 -0700125 sync_c = False
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800126 sync_s = False
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900127 sync_tags = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700128
Julien Campergue74879922013-10-09 14:38:46 +0200129 def __eq__(self, other):
Jack Neus5ba21202021-06-09 15:21:25 +0000130 if not isinstance(other, _Default):
131 return False
Julien Campergue74879922013-10-09 14:38:46 +0200132 return self.__dict__ == other.__dict__
133
134 def __ne__(self, other):
Jack Neus5ba21202021-06-09 15:21:25 +0000135 if not isinstance(other, _Default):
136 return True
Julien Campergue74879922013-10-09 14:38:46 +0200137 return self.__dict__ != other.__dict__
138
David Pursehouse819827a2020-02-12 15:20:19 +0900139
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700140class _XmlRemote(object):
141 def __init__(self,
142 name,
Yestin Sunb292b982012-07-02 07:32:50 -0700143 alias=None,
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700144 fetch=None,
Steve Raed6480452016-08-10 15:00:00 -0700145 pushUrl=None,
Conley Owensdb728cd2011-09-26 16:34:01 -0700146 manifestUrl=None,
Anthony King36ea2fb2014-05-06 11:54:01 +0100147 review=None,
Jonathan Nieder93719792015-03-17 11:29:58 -0700148 revision=None):
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700149 self.name = name
150 self.fetchUrl = fetch
Steve Raed6480452016-08-10 15:00:00 -0700151 self.pushUrl = pushUrl
Conley Owensdb728cd2011-09-26 16:34:01 -0700152 self.manifestUrl = manifestUrl
Yestin Sunb292b982012-07-02 07:32:50 -0700153 self.remoteAlias = alias
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700154 self.reviewUrl = review
Anthony King36ea2fb2014-05-06 11:54:01 +0100155 self.revision = revision
Conley Owensceea3682011-10-20 10:45:47 -0700156 self.resolvedFetchUrl = self._resolveFetchUrl()
Jack Neus6ea0cae2021-07-20 20:52:33 +0000157 self.annotations = []
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700158
David Pursehouse717ece92012-11-13 08:49:16 +0900159 def __eq__(self, other):
Jack Neus5ba21202021-06-09 15:21:25 +0000160 if not isinstance(other, _XmlRemote):
161 return False
Jack Neus6ea0cae2021-07-20 20:52:33 +0000162 return (sorted(self.annotations) == sorted(other.annotations) and
163 self.name == other.name and self.fetchUrl == other.fetchUrl and
164 self.pushUrl == other.pushUrl and self.remoteAlias == other.remoteAlias
165 and self.reviewUrl == other.reviewUrl and self.revision == other.revision)
David Pursehouse717ece92012-11-13 08:49:16 +0900166
167 def __ne__(self, other):
Jack Neus6ea0cae2021-07-20 20:52:33 +0000168 return not self.__eq__(other)
David Pursehouse717ece92012-11-13 08:49:16 +0900169
Conley Owensceea3682011-10-20 10:45:47 -0700170 def _resolveFetchUrl(self):
Jack Neus5ba21202021-06-09 15:21:25 +0000171 if self.fetchUrl is None:
172 return ''
Conley Owensceea3682011-10-20 10:45:47 -0700173 url = self.fetchUrl.rstrip('/')
Conley Owensdb728cd2011-09-26 16:34:01 -0700174 manifestUrl = self.manifestUrl.rstrip('/')
Conley Owens2d0f5082014-01-31 15:03:51 -0800175 # urljoin will gets confused over quite a few things. The ones we care
176 # about here are:
177 # * no scheme in the base url, like <hostname:port>
Anthony Kingcb07ba72015-03-28 23:26:04 +0000178 # We handle no scheme by replacing it with an obscure protocol, gopher
179 # and then replacing it with the original when we are done.
180
Conley Owensdb728cd2011-09-26 16:34:01 -0700181 if manifestUrl.find(':') != manifestUrl.find('/') - 1:
Conley Owens4ccad752015-04-29 10:45:37 -0700182 url = urllib.parse.urljoin('gopher://' + manifestUrl, url)
183 url = re.sub(r'^gopher://', '', url)
Anthony Kingcb07ba72015-03-28 23:26:04 +0000184 else:
185 url = urllib.parse.urljoin(manifestUrl, url)
Shawn Pearcea9f11b32013-01-02 15:40:48 -0800186 return url
Conley Owensceea3682011-10-20 10:45:47 -0700187
188 def ToRemoteSpec(self, projectName):
David Rileye0684ad2017-04-05 00:02:59 -0700189 fetchUrl = self.resolvedFetchUrl.rstrip('/')
190 url = fetchUrl + '/' + projectName
Yestin Sunb292b982012-07-02 07:32:50 -0700191 remoteName = self.name
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700192 if self.remoteAlias:
David Pursehouse37128b62013-10-15 10:48:40 +0900193 remoteName = self.remoteAlias
Dan Willemsen96c2d652016-04-06 16:03:54 -0700194 return RemoteSpec(remoteName,
195 url=url,
Steve Raed6480452016-08-10 15:00:00 -0700196 pushUrl=self.pushUrl,
Dan Willemsen96c2d652016-04-06 16:03:54 -0700197 review=self.reviewUrl,
David Rileye0684ad2017-04-05 00:02:59 -0700198 orig_name=self.name,
199 fetchUrl=self.fetchUrl)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700200
Jack Neus6ea0cae2021-07-20 20:52:33 +0000201 def AddAnnotation(self, name, value, keep):
202 self.annotations.append(Annotation(name, value, keep))
203
David Pursehouse819827a2020-02-12 15:20:19 +0900204
LaMont Jonescc879a92021-11-18 22:40:18 +0000205class _XmlSubmanifest:
206 """Manage the <submanifest> element specified in the manifest.
207
208 Attributes:
209 name: a string, the name for this submanifest.
210 remote: a string, the remote.name for this submanifest.
211 project: a string, the name of the manifest project.
212 revision: a string, the commitish.
213 manifestName: a string, the submanifest file name.
214 groups: a list of strings, the groups to add to all projects in the submanifest.
215 path: a string, the relative path for the submanifest checkout.
216 annotations: (derived) a list of annotations.
217 present: (derived) a boolean, whether the submanifest's manifest file is present.
218 """
219 def __init__(self,
220 name,
221 remote=None,
222 project=None,
223 revision=None,
224 manifestName=None,
225 groups=None,
226 path=None,
227 parent=None):
228 self.name = name
229 self.remote = remote
230 self.project = project
231 self.revision = revision
232 self.manifestName = manifestName
233 self.groups = groups
234 self.path = path
235 self.annotations = []
236 outer_client = parent._outer_client or parent
237 if self.remote and not self.project:
238 raise ManifestParseError(
239 f'Submanifest {name}: must specify project when remote is given.')
240 rc = self.repo_client = RepoClient(
241 parent.repodir, manifestName, parent_groups=','.join(groups) or '',
242 submanifest_path=self.relpath, outer_client=outer_client)
243
244 self.present = os.path.exists(os.path.join(self.repo_client.subdir,
245 MANIFEST_FILE_NAME))
246
247 def __eq__(self, other):
248 if not isinstance(other, _XmlSubmanifest):
249 return False
250 return (
251 self.name == other.name and
252 self.remote == other.remote and
253 self.project == other.project and
254 self.revision == other.revision and
255 self.manifestName == other.manifestName and
256 self.groups == other.groups and
257 self.path == other.path and
258 sorted(self.annotations) == sorted(other.annotations))
259
260 def __ne__(self, other):
261 return not self.__eq__(other)
262
263 def ToSubmanifestSpec(self, root):
264 """Return a SubmanifestSpec object, populating attributes"""
265 mp = root.manifestProject
266 remote = root.remotes[self.remote or root.default.remote.name]
267 # If a project was given, generate the url from the remote and project.
268 # If not, use this manifestProject's url.
269 if self.project:
270 manifestUrl = remote.ToRemoteSpec(self.project).url
271 else:
272 manifestUrl = mp.GetRemote(mp.remote.name).url
273 manifestName = self.manifestName or 'default.xml'
274 revision = self.revision or self.name
275 path = self.path or revision.split('/')[-1]
276 groups = self.groups or []
277
278 return SubmanifestSpec(self.name, manifestUrl, manifestName, revision, path,
279 groups)
280
281 @property
282 def relpath(self):
283 """The path of this submanifest relative to the parent manifest."""
284 revision = self.revision or self.name
285 return self.path or revision.split('/')[-1]
286
287 def GetGroupsStr(self):
288 """Returns the `groups` given for this submanifest."""
289 if self.groups:
290 return ','.join(self.groups)
291 return ''
292
293 def AddAnnotation(self, name, value, keep):
294 """Add annotations to the submanifest."""
295 self.annotations.append(Annotation(name, value, keep))
296
297
298class SubmanifestSpec:
299 """The submanifest element, with all fields expanded."""
300
301 def __init__(self,
302 name,
303 manifestUrl,
304 manifestName,
305 revision,
306 path,
307 groups):
308 self.name = name
309 self.manifestUrl = manifestUrl
310 self.manifestName = manifestName
311 self.revision = revision
312 self.path = path
313 self.groups = groups or []
314
315
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700316class XmlManifest(object):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700317 """manages the repo configuration file"""
318
LaMont Jonescc879a92021-11-18 22:40:18 +0000319 def __init__(self, repodir, manifest_file, local_manifests=None,
320 outer_client=None, parent_groups='', submanifest_path=''):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400321 """Initialize.
322
323 Args:
324 repodir: Path to the .repo/ dir for holding all internal checkout state.
325 It must be in the top directory of the repo client checkout.
326 manifest_file: Full path to the manifest file to parse. This will usually
327 be |repodir|/|MANIFEST_FILE_NAME|.
328 local_manifests: Full path to the directory of local override manifests.
329 This will usually be |repodir|/|LOCAL_MANIFESTS_DIR_NAME|.
LaMont Jonescc879a92021-11-18 22:40:18 +0000330 outer_client: RepoClient of the outertree.
331 parent_groups: a string, the groups to apply to this projects.
332 submanifest_path: The submanifest root relative to the repo root.
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400333 """
334 # TODO(vapier): Move this out of this class.
335 self.globalConfig = GitConfig.ForUser()
336
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700337 self.repodir = os.path.abspath(repodir)
LaMont Jonescc879a92021-11-18 22:40:18 +0000338 self._CheckLocalPath(submanifest_path)
339 self.topdir = os.path.join(os.path.dirname(self.repodir), submanifest_path)
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400340 self.manifestFile = manifest_file
341 self.local_manifests = local_manifests
Basil Gelloc7453502018-05-25 20:23:52 +0300342 self._load_local_manifests = True
LaMont Jonescc879a92021-11-18 22:40:18 +0000343 self.parent_groups = parent_groups
344
345 if outer_client and self.isGitcClient:
346 raise ManifestParseError('Multi-manifest is incompatible with `gitc-init`')
347
348 if submanifest_path and not outer_client:
349 # If passing a submanifest_path, there must be an outer_client.
350 raise ManifestParseError(f'Bad call to {self.__class__.__name__}')
351
352 # If self._outer_client is None, this is not a checkout that supports
353 # multi-tree.
354 self._outer_client = outer_client or self
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700355
356 self.repoProject = MetaProject(self, 'repo',
David Pursehouseabdf7502020-02-12 14:58:39 +0900357 gitdir=os.path.join(repodir, 'repo/.git'),
358 worktree=os.path.join(repodir, 'repo'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700359
LaMont Jonescc879a92021-11-18 22:40:18 +0000360 mp = self.SubmanifestProject(self.path_prefix)
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500361 self.manifestProject = mp
362
363 # This is a bit hacky, but we're in a chicken & egg situation: all the
364 # normal repo settings live in the manifestProject which we just setup
365 # above, so we couldn't easily query before that. We assume Project()
366 # init doesn't care if this changes afterwards.
Mike Frysingerd957ec62020-02-24 14:40:25 -0500367 if os.path.exists(mp.gitdir) and mp.config.GetBoolean('repo.worktree'):
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500368 mp.use_git_worktrees = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700369
370 self._Unload()
371
Basil Gelloc7453502018-05-25 20:23:52 +0300372 def Override(self, name, load_local_manifests=True):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700373 """Use a different manifest, just for the current instantiation.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700374 """
Basil Gelloc7453502018-05-25 20:23:52 +0300375 path = None
376
377 # Look for a manifest by path in the filesystem (including the cwd).
378 if not load_local_manifests:
379 local_path = os.path.abspath(name)
380 if os.path.isfile(local_path):
381 path = local_path
382
383 # Look for manifests by name from the manifests repo.
384 if path is None:
385 path = os.path.join(self.manifestProject.worktree, name)
386 if not os.path.isfile(path):
387 raise ManifestParseError('manifest %s not found' % name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700388
389 old = self.manifestFile
390 try:
Basil Gelloc7453502018-05-25 20:23:52 +0300391 self._load_local_manifests = load_local_manifests
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700392 self.manifestFile = path
393 self._Unload()
394 self._Load()
395 finally:
396 self.manifestFile = old
397
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700398 def Link(self, name):
399 """Update the repo metadata to use a different manifest.
400 """
401 self.Override(name)
402
Mike Frysingera269b1c2020-02-21 00:49:41 -0500403 # Old versions of repo would generate symlinks we need to clean up.
Mike Frysinger9d96f582021-09-28 11:27:24 -0400404 platform_utils.remove(self.manifestFile, missing_ok=True)
Mike Frysingera269b1c2020-02-21 00:49:41 -0500405 # This file is interpreted as if it existed inside the manifest repo.
406 # That allows us to use <include> with the relative file name.
407 with open(self.manifestFile, 'w') as fp:
408 fp.write("""<?xml version="1.0" encoding="UTF-8"?>
409<!--
410DO NOT EDIT THIS FILE! It is generated by repo and changes will be discarded.
411If you want to use a different manifest, use `repo init -m <file>` instead.
412
413If you want to customize your checkout by overriding manifest settings, use
414the local_manifests/ directory instead.
415
416For more information on repo manifests, check out:
417https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
418-->
419<manifest>
420 <include name="%s" />
421</manifest>
422""" % (name,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700423
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800424 def _RemoteToXml(self, r, doc, root):
425 e = doc.createElement('remote')
426 root.appendChild(e)
427 e.setAttribute('name', r.name)
428 e.setAttribute('fetch', r.fetchUrl)
Steve Raed6480452016-08-10 15:00:00 -0700429 if r.pushUrl is not None:
430 e.setAttribute('pushurl', r.pushUrl)
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700431 if r.remoteAlias is not None:
432 e.setAttribute('alias', r.remoteAlias)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800433 if r.reviewUrl is not None:
434 e.setAttribute('review', r.reviewUrl)
Anthony King36ea2fb2014-05-06 11:54:01 +0100435 if r.revision is not None:
436 e.setAttribute('revision', r.revision)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800437
Jack Neus6ea0cae2021-07-20 20:52:33 +0000438 for a in r.annotations:
439 if a.keep == 'true':
440 ae = doc.createElement('annotation')
441 ae.setAttribute('name', a.name)
442 ae.setAttribute('value', a.value)
443 e.appendChild(ae)
444
LaMont Jonescc879a92021-11-18 22:40:18 +0000445 def _SubmanifestToXml(self, r, doc, root):
446 """Generate XML <submanifest/> node."""
447 e = doc.createElement('submanifest')
448 root.appendChild(e)
449 e.setAttribute('name', r.name)
450 if r.remote is not None:
451 e.setAttribute('remote', r.remote)
452 if r.project is not None:
453 e.setAttribute('project', r.project)
454 if r.manifestName is not None:
455 e.setAttribute('manifest-name', r.manifestName)
456 if r.revision is not None:
457 e.setAttribute('revision', r.revision)
458 if r.path is not None:
459 e.setAttribute('path', r.path)
460 if r.groups:
461 e.setAttribute('groups', r.GetGroupsStr())
462
463 for a in r.annotations:
464 if a.keep == 'true':
465 ae = doc.createElement('annotation')
466 ae.setAttribute('name', a.name)
467 ae.setAttribute('value', a.value)
468 e.appendChild(ae)
469
Mike Frysinger51e39d52020-12-04 05:32:06 -0500470 def _ParseList(self, field):
471 """Parse fields that contain flattened lists.
472
473 These are whitespace & comma separated. Empty elements will be discarded.
474 """
475 return [x for x in re.split(r'[,\s]+', field) if x]
Josh Triplett884a3872014-06-12 14:57:29 -0700476
Mike Frysinger23411d32020-09-02 04:31:10 -0400477 def ToXml(self, peg_rev=False, peg_rev_upstream=True, peg_rev_dest_branch=True, groups=None):
478 """Return the current manifest XML."""
Colin Cross5acde752012-03-28 20:15:45 -0700479 mp = self.manifestProject
480
Dan Willemsen5ea32d12015-09-08 13:27:20 -0700481 if groups is None:
482 groups = mp.config.GetString('manifest.groups')
Matt Gumbel0c635bb2012-12-21 10:14:53 -0800483 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -0500484 groups = self._ParseList(groups)
Colin Cross5acde752012-03-28 20:15:45 -0700485
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800486 doc = xml.dom.minidom.Document()
487 root = doc.createElement('manifest')
LaMont Jonescc879a92021-11-18 22:40:18 +0000488 if self.is_submanifest:
489 root.setAttribute('path', self.path_prefix)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800490 doc.appendChild(root)
491
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700492 # Save out the notice. There's a little bit of work here to give it the
493 # right whitespace, which assumes that the notice is automatically indented
494 # by 4 by minidom.
495 if self.notice:
496 notice_element = root.appendChild(doc.createElement('notice'))
497 notice_lines = self.notice.splitlines()
David Pursehouse54a4e602020-02-12 14:31:05 +0900498 indented_notice = ('\n'.join(" " * 4 + line for line in notice_lines))[4:]
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700499 notice_element.appendChild(doc.createTextNode(indented_notice))
500
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800501 d = self.default
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800502
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530503 for r in sorted(self.remotes):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800504 self._RemoteToXml(self.remotes[r], doc, root)
505 if self.remotes:
506 root.appendChild(doc.createTextNode(''))
507
508 have_default = False
509 e = doc.createElement('default')
510 if d.remote:
511 have_default = True
512 e.setAttribute('remote', d.remote.name)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700513 if d.revisionExpr:
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800514 have_default = True
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700515 e.setAttribute('revision', d.revisionExpr)
Simon Ruggier7e59de22015-07-24 12:50:06 +0200516 if d.destBranchExpr:
517 have_default = True
518 e.setAttribute('dest-branch', d.destBranchExpr)
Nasser Grainawida403412018-05-04 12:53:29 -0600519 if d.upstreamExpr:
520 have_default = True
521 e.setAttribute('upstream', d.upstreamExpr)
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700522 if d.sync_j > 1:
523 have_default = True
524 e.setAttribute('sync-j', '%d' % d.sync_j)
Anatol Pomazau79770d22012-04-20 14:41:59 -0700525 if d.sync_c:
526 have_default = True
527 e.setAttribute('sync-c', 'true')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800528 if d.sync_s:
529 have_default = True
530 e.setAttribute('sync-s', 'true')
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900531 if not d.sync_tags:
532 have_default = True
533 e.setAttribute('sync-tags', 'false')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800534 if have_default:
535 root.appendChild(e)
536 root.appendChild(doc.createTextNode(''))
537
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700538 if self._manifest_server:
539 e = doc.createElement('manifest-server')
540 e.setAttribute('url', self._manifest_server)
541 root.appendChild(e)
542 root.appendChild(doc.createTextNode(''))
543
LaMont Jonescc879a92021-11-18 22:40:18 +0000544 for r in sorted(self.submanifests):
545 self._SubmanifestToXml(self.submanifests[r], doc, root)
546 if self.submanifests:
547 root.appendChild(doc.createTextNode(''))
548
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800549 def output_projects(parent, parent_node, projects):
David James8d201162013-10-11 17:03:19 -0700550 for project_name in projects:
551 for project in self._projects[project_name]:
552 output_project(parent, parent_node, project)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800553
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800554 def output_project(parent, parent_node, p):
Colin Cross5acde752012-03-28 20:15:45 -0700555 if not p.MatchesGroups(groups):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800556 return
557
558 name = p.name
559 relpath = p.relpath
560 if parent:
561 name = self._UnjoinName(parent.name, name)
562 relpath = self._UnjoinRelpath(parent.relpath, relpath)
Colin Cross5acde752012-03-28 20:15:45 -0700563
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800564 e = doc.createElement('project')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800565 parent_node.appendChild(e)
566 e.setAttribute('name', name)
567 if relpath != name:
568 e.setAttribute('path', relpath)
Conley Owensa17d7af2013-10-16 14:38:09 -0700569 remoteName = None
570 if d.remote:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700571 remoteName = d.remote.name
572 if not d.remote or p.remote.orig_name != remoteName:
573 remoteName = p.remote.orig_name
Anthony King36ea2fb2014-05-06 11:54:01 +0100574 e.setAttribute('remote', remoteName)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800575 if peg_rev:
576 if self.IsMirror:
Brian Harring14a66742012-09-28 20:21:57 -0700577 value = p.bare_git.rev_parse(p.revisionExpr + '^0')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800578 else:
Brian Harring14a66742012-09-28 20:21:57 -0700579 value = p.work_git.rev_parse(HEAD + '^0')
580 e.setAttribute('revision', value)
Conley Owens551dfec2015-07-10 14:54:54 -0700581 if peg_rev_upstream:
582 if p.upstream:
583 e.setAttribute('upstream', p.upstream)
584 elif value != p.revisionExpr:
585 # Only save the origin if the origin is not a sha1, and the default
586 # isn't our value
587 e.setAttribute('upstream', p.revisionExpr)
Sean McAllisteraf908cb2020-04-20 08:41:58 -0600588
589 if peg_rev_dest_branch:
590 if p.dest_branch:
591 e.setAttribute('dest-branch', p.dest_branch)
592 elif value != p.revisionExpr:
593 e.setAttribute('dest-branch', p.revisionExpr)
594
Anthony King36ea2fb2014-05-06 11:54:01 +0100595 else:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700596 revision = self.remotes[p.remote.orig_name].revision or d.revisionExpr
Anthony King36ea2fb2014-05-06 11:54:01 +0100597 if not revision or revision != p.revisionExpr:
598 e.setAttribute('revision', p.revisionExpr)
Raman Tennetib5c5a5e2021-02-06 09:44:15 -0800599 elif p.revisionId:
600 e.setAttribute('revision', p.revisionId)
Nasser Grainawida403412018-05-04 12:53:29 -0600601 if (p.upstream and (p.upstream != p.revisionExpr or
602 p.upstream != d.upstreamExpr)):
Mani Chandel7a91d512014-07-24 16:27:08 +0530603 e.setAttribute('upstream', p.upstream)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800604
Simon Ruggier7e59de22015-07-24 12:50:06 +0200605 if p.dest_branch and p.dest_branch != d.destBranchExpr:
606 e.setAttribute('dest-branch', p.dest_branch)
607
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800608 for c in p.copyfiles:
609 ce = doc.createElement('copyfile')
610 ce.setAttribute('src', c.src)
611 ce.setAttribute('dest', c.dest)
612 e.appendChild(ce)
613
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500614 for l in p.linkfiles:
615 le = doc.createElement('linkfile')
616 le.setAttribute('src', l.src)
617 le.setAttribute('dest', l.dest)
618 e.appendChild(le)
619
Conley Owensbb1b5f52012-08-13 13:11:18 -0700620 default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
Dmitry Fink17f85ea2012-08-06 14:52:29 -0700621 egroups = [g for g in p.groups if g not in default_groups]
Conley Owens971de8e2012-04-16 10:36:08 -0700622 if egroups:
623 e.setAttribute('groups', ','.join(egroups))
Colin Cross5acde752012-03-28 20:15:45 -0700624
James W. Mills24c13082012-04-12 15:04:13 -0500625 for a in p.annotations:
626 if a.keep == "true":
627 ae = doc.createElement('annotation')
628 ae.setAttribute('name', a.name)
629 ae.setAttribute('value', a.value)
630 e.appendChild(ae)
631
Anatol Pomazau79770d22012-04-20 14:41:59 -0700632 if p.sync_c:
633 e.setAttribute('sync-c', 'true')
634
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800635 if p.sync_s:
636 e.setAttribute('sync-s', 'true')
637
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900638 if not p.sync_tags:
639 e.setAttribute('sync-tags', 'false')
640
Dan Willemsen88409222015-08-17 15:29:10 -0700641 if p.clone_depth:
642 e.setAttribute('clone-depth', str(p.clone_depth))
643
Simran Basib9a1b732015-08-20 12:19:28 -0700644 self._output_manifest_project_extras(p, e)
645
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800646 if p.subprojects:
David James8d201162013-10-11 17:03:19 -0700647 subprojects = set(subp.name for subp in p.subprojects)
648 output_projects(p, e, list(sorted(subprojects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800649
David James8d201162013-10-11 17:03:19 -0700650 projects = set(p.name for p in self._paths.values() if not p.parent)
651 output_projects(None, root, list(sorted(projects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800652
Doug Anderson37282b42011-03-04 11:54:18 -0800653 if self._repo_hooks_project:
654 root.appendChild(doc.createTextNode(''))
655 e = doc.createElement('repo-hooks')
656 e.setAttribute('in-project', self._repo_hooks_project.name)
657 e.setAttribute('enabled-list',
658 ' '.join(self._repo_hooks_project.enabled_repo_hooks))
659 root.appendChild(e)
660
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800661 if self._superproject:
662 root.appendChild(doc.createTextNode(''))
663 e = doc.createElement('superproject')
664 e.setAttribute('name', self._superproject['name'])
665 remoteName = None
666 if d.remote:
667 remoteName = d.remote.name
668 remote = self._superproject.get('remote')
669 if not d.remote or remote.orig_name != remoteName:
670 remoteName = remote.orig_name
671 e.setAttribute('remote', remoteName)
Xin Lie0b16a22021-09-26 23:20:32 -0700672 revision = remote.revision or d.revisionExpr
673 if not revision or revision != self._superproject['revision']:
674 e.setAttribute('revision', self._superproject['revision'])
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800675 root.appendChild(e)
676
Raman Tenneti993af5e2021-05-12 12:00:31 -0700677 if self._contactinfo.bugurl != Wrapper().BUG_URL:
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700678 root.appendChild(doc.createTextNode(''))
679 e = doc.createElement('contactinfo')
Raman Tenneti993af5e2021-05-12 12:00:31 -0700680 e.setAttribute('bugurl', self._contactinfo.bugurl)
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700681 root.appendChild(e)
682
Mike Frysinger23411d32020-09-02 04:31:10 -0400683 return doc
684
685 def ToDict(self, **kwargs):
686 """Return the current manifest as a dictionary."""
687 # Elements that may only appear once.
688 SINGLE_ELEMENTS = {
689 'notice',
690 'default',
691 'manifest-server',
692 'repo-hooks',
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800693 'superproject',
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700694 'contactinfo',
Mike Frysinger23411d32020-09-02 04:31:10 -0400695 }
696 # Elements that may be repeated.
697 MULTI_ELEMENTS = {
698 'remote',
699 'remove-project',
700 'project',
701 'extend-project',
702 'include',
LaMont Jonescc879a92021-11-18 22:40:18 +0000703 'submanifest',
Mike Frysinger23411d32020-09-02 04:31:10 -0400704 # These are children of 'project' nodes.
705 'annotation',
706 'project',
707 'copyfile',
708 'linkfile',
709 }
710
711 doc = self.ToXml(**kwargs)
712 ret = {}
713
714 def append_children(ret, node):
715 for child in node.childNodes:
716 if child.nodeType == xml.dom.Node.ELEMENT_NODE:
717 attrs = child.attributes
718 element = dict((attrs.item(i).localName, attrs.item(i).value)
719 for i in range(attrs.length))
720 if child.nodeName in SINGLE_ELEMENTS:
721 ret[child.nodeName] = element
722 elif child.nodeName in MULTI_ELEMENTS:
723 ret.setdefault(child.nodeName, []).append(element)
724 else:
725 raise ManifestParseError('Unhandled element "%s"' % (child.nodeName,))
726
727 append_children(element, child)
728
729 append_children(ret, doc.firstChild)
730
731 return ret
732
733 def Save(self, fd, **kwargs):
734 """Write the current manifest out to the given file descriptor."""
735 doc = self.ToXml(**kwargs)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800736 doc.writexml(fd, '', ' ', '\n', 'UTF-8')
737
Simran Basib9a1b732015-08-20 12:19:28 -0700738 def _output_manifest_project_extras(self, p, e):
739 """Manifests can modify e if they support extra project attributes."""
Simran Basib9a1b732015-08-20 12:19:28 -0700740
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700741 @property
LaMont Jonescc879a92021-11-18 22:40:18 +0000742 def is_multimanifest(self):
743 """Whether this is a multimanifest checkout"""
744 return bool(self.outer_client.submanifests)
745
746 @property
747 def is_submanifest(self):
748 """Whether this manifest is a submanifest"""
749 return self._outer_client and self._outer_client != self
750
751 @property
752 def outer_client(self):
753 """The instance of the outermost manifest client"""
754 self._Load()
755 return self._outer_client
756
757 @property
758 def all_manifests(self):
759 """Generator yielding all (sub)manifests."""
760 self._Load()
761 outer = self._outer_client
762 yield outer
763 for tree in outer.all_children:
764 yield tree
765
766 @property
767 def all_children(self):
768 """Generator yielding all child submanifests."""
769 self._Load()
770 for child in self._submanifests.values():
771 if child.repo_client:
772 yield child.repo_client
773 for tree in child.repo_client.all_children:
774 yield tree
775
776 @property
777 def path_prefix(self):
778 """The path of this submanifest, relative to the outermost manifest."""
779 if not self._outer_client or self == self._outer_client:
780 return ''
781 return os.path.relpath(self.topdir, self._outer_client.topdir)
782
783 @property
784 def all_paths(self):
785 """All project paths for all (sub)manifests. See `paths`."""
786 ret = {}
787 for tree in self.all_manifests:
788 prefix = tree.path_prefix
789 ret.update({os.path.join(prefix, k): v for k, v in tree.paths.items()})
790 return ret
791
792 @property
793 def all_projects(self):
794 """All projects for all (sub)manifests. See `projects`."""
795 return list(itertools.chain.from_iterable(x._paths.values() for x in self.all_manifests))
796
797 @property
David James8d201162013-10-11 17:03:19 -0700798 def paths(self):
LaMont Jonescc879a92021-11-18 22:40:18 +0000799 """Return all paths for this manifest.
800
801 Return:
802 A dictionary of {path: Project()}. `path` is relative to this manifest.
803 """
David James8d201162013-10-11 17:03:19 -0700804 self._Load()
805 return self._paths
806
807 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700808 def projects(self):
LaMont Jonescc879a92021-11-18 22:40:18 +0000809 """Return a list of all Projects in this manifest."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700810 self._Load()
Anthony Kingd58bfe52014-05-05 23:30:49 +0100811 return list(self._paths.values())
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700812
813 @property
814 def remotes(self):
815 self._Load()
816 return self._remotes
817
818 @property
819 def default(self):
820 self._Load()
821 return self._default
822
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800823 @property
LaMont Jonescc879a92021-11-18 22:40:18 +0000824 def submanifests(self):
825 """All submanifests in this manifest."""
826 self._Load()
827 return self._submanifests
828
829 @property
Doug Anderson37282b42011-03-04 11:54:18 -0800830 def repo_hooks_project(self):
831 self._Load()
832 return self._repo_hooks_project
833
834 @property
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800835 def superproject(self):
836 self._Load()
837 return self._superproject
838
839 @property
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700840 def contactinfo(self):
841 self._Load()
842 return self._contactinfo
843
844 @property
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700845 def notice(self):
846 self._Load()
847 return self._notice
848
849 @property
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700850 def manifest_server(self):
851 self._Load()
Shawn O. Pearce34fb20f2011-11-30 13:41:02 -0800852 return self._manifest_server
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700853
854 @property
Xin Lid79a4bc2020-05-20 16:03:45 -0700855 def CloneBundle(self):
856 clone_bundle = self.manifestProject.config.GetBoolean('repo.clonebundle')
857 if clone_bundle is None:
858 return False if self.manifestProject.config.GetBoolean('repo.partialclone') else True
859 else:
860 return clone_bundle
861
862 @property
Xin Li745be2e2019-06-03 11:24:30 -0700863 def CloneFilter(self):
864 if self.manifestProject.config.GetBoolean('repo.partialclone'):
865 return self.manifestProject.config.GetString('repo.clonefilter')
866 return None
867
868 @property
Raman Tennetif32f2432021-04-12 20:57:25 -0700869 def PartialCloneExclude(self):
870 exclude = self.manifest.manifestProject.config.GetString(
871 'repo.partialcloneexclude') or ''
872 return set(x.strip() for x in exclude.split(','))
873
874 @property
Michael Kellyc34b91c2021-07-02 09:25:48 -0700875 def UseLocalManifests(self):
876 return self._load_local_manifests
877
878 def SetUseLocalManifests(self, value):
879 self._load_local_manifests = value
880
881 @property
Raman Tennetifeb28912021-05-02 19:47:29 -0700882 def HasLocalManifests(self):
883 return self._load_local_manifests and self.local_manifests
884
LaMont Jones87cce682022-02-14 17:48:31 +0000885 def IsFromLocalManifest(self, project):
LaMont Jonescc879a92021-11-18 22:40:18 +0000886 """Is the project from a local manifest?"""
LaMont Jones87cce682022-02-14 17:48:31 +0000887 return any(x.startswith(LOCAL_MANIFEST_GROUP_PREFIX)
888 for x in project.groups)
889
Raman Tennetifeb28912021-05-02 19:47:29 -0700890 @property
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800891 def IsMirror(self):
892 return self.manifestProject.config.GetBoolean('repo.mirror')
893
Julien Campergue335f5ef2013-10-16 11:02:35 +0200894 @property
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500895 def UseGitWorktrees(self):
896 return self.manifestProject.config.GetBoolean('repo.worktree')
897
898 @property
Julien Campergue335f5ef2013-10-16 11:02:35 +0200899 def IsArchive(self):
900 return self.manifestProject.config.GetBoolean('repo.archive')
901
Martin Kellye4e94d22017-03-21 16:05:12 -0700902 @property
903 def HasSubmodules(self):
904 return self.manifestProject.config.GetBoolean('repo.submodules')
905
XD Trol630876f2022-01-17 23:29:04 +0800906 @property
907 def EnableGitLfs(self):
908 return self.manifestProject.config.GetBoolean('repo.git-lfs')
909
LaMont Jonescc879a92021-11-18 22:40:18 +0000910 def FindManifestByPath(self, path):
911 """Returns the manifest containing path."""
912 path = os.path.abspath(path)
913 manifest = self._outer_client or self
914 old = None
915 while manifest._submanifests and manifest != old:
916 old = manifest
917 for name in manifest._submanifests:
918 tree = manifest._submanifests[name]
919 if path.startswith(tree.repo_client.manifest.topdir):
920 manifest = tree.repo_client
921 break
922 return manifest
923
924 @property
925 def subdir(self):
926 """Returns the path for per-submanifest objects for this manifest."""
927 return self.SubmanifestInfoDir(self.path_prefix)
928
929 def SubmanifestInfoDir(self, submanifest_path, object_path=''):
930 """Return the path to submanifest-specific info for a submanifest.
931
932 Return the full path of the directory in which to put per-manifest objects.
933
934 Args:
935 submanifest_path: a string, the path of the submanifest, relative to the
936 outermost topdir. If empty, then repodir is returned.
937 object_path: a string, relative path to append to the submanifest info
938 directory path.
939 """
940 if submanifest_path:
941 return os.path.join(self.repodir, SUBMANIFEST_DIR, submanifest_path,
942 object_path)
943 else:
944 return os.path.join(self.repodir, object_path)
945
946 def SubmanifestProject(self, submanifest_path):
947 """Return a manifestProject for a submanifest."""
948 subdir = self.SubmanifestInfoDir(submanifest_path)
949 mp = MetaProject(self, 'manifests',
950 gitdir=os.path.join(subdir, 'manifests.git'),
951 worktree=os.path.join(subdir, 'manifests'))
952 return mp
953
Raman Tenneti080877e2021-03-09 15:19:06 -0800954 def GetDefaultGroupsStr(self):
955 """Returns the default group string for the platform."""
956 return 'default,platform-' + platform.system().lower()
957
958 def GetGroupsStr(self):
959 """Returns the manifest group string that should be synced."""
960 groups = self.manifestProject.config.GetString('manifest.groups')
961 if not groups:
962 groups = self.GetDefaultGroupsStr()
963 return groups
964
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700965 def _Unload(self):
966 self._loaded = False
967 self._projects = {}
David James8d201162013-10-11 17:03:19 -0700968 self._paths = {}
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700969 self._remotes = {}
970 self._default = None
LaMont Jonescc879a92021-11-18 22:40:18 +0000971 self._submanifests = {}
Doug Anderson37282b42011-03-04 11:54:18 -0800972 self._repo_hooks_project = None
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800973 self._superproject = {}
Raman Tenneti993af5e2021-05-12 12:00:31 -0700974 self._contactinfo = ContactInfo(Wrapper().BUG_URL)
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700975 self._notice = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700976 self.branch = None
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700977 self._manifest_server = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700978
LaMont Jonescc879a92021-11-18 22:40:18 +0000979 def _Load(self, initial_client=None, submanifest_depth=0):
980 if submanifest_depth > MAX_SUBMANIFEST_DEPTH:
981 raise ManifestParseError('maximum submanifest depth %d exceeded.' %
982 MAX_SUBMANIFEST_DEPTH)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700983 if not self._loaded:
LaMont Jonescc879a92021-11-18 22:40:18 +0000984 if self._outer_client and self._outer_client != self:
985 # This will load all clients.
986 self._outer_client._Load(initial_client=self)
987
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800988 m = self.manifestProject
989 b = m.GetBranch(m.CurrentBranch).merge
Shawn O. Pearce21c5c342009-06-25 16:47:30 -0700990 if b is not None and b.startswith(R_HEADS):
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800991 b = b[len(R_HEADS):]
992 self.branch = b
993
LaMont Jonescc879a92021-11-18 22:40:18 +0000994 parent_groups = self.parent_groups
LaMont Jonesb308db12022-02-25 17:05:21 +0000995 if self.path_prefix:
996 parent_groups = f'{SUBMANIFEST_GROUP_PREFIX}:path:{self.path_prefix},{parent_groups}'
LaMont Jonescc879a92021-11-18 22:40:18 +0000997
Mike Frysinger54133972021-03-01 21:38:08 -0500998 # The manifestFile was specified by the user which is why we allow include
999 # paths to point anywhere.
Colin Cross23acdd32012-04-21 00:33:54 -07001000 nodes = []
Mike Frysinger54133972021-03-01 21:38:08 -05001001 nodes.append(self._ParseManifestXml(
1002 self.manifestFile, self.manifestProject.worktree,
LaMont Jonescc879a92021-11-18 22:40:18 +00001003 parent_groups=parent_groups, restrict_includes=False))
Shawn O. Pearce5cc66792008-10-23 16:19:27 -07001004
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001005 if self._load_local_manifests and self.local_manifests:
Basil Gelloc7453502018-05-25 20:23:52 +03001006 try:
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001007 for local_file in sorted(platform_utils.listdir(self.local_manifests)):
Basil Gelloc7453502018-05-25 20:23:52 +03001008 if local_file.endswith('.xml'):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001009 local = os.path.join(self.local_manifests, local_file)
Mike Frysinger54133972021-03-01 21:38:08 -05001010 # Since local manifests are entirely managed by the user, allow
1011 # them to point anywhere the user wants.
LaMont Jonescc879a92021-11-18 22:40:18 +00001012 local_group = f'{LOCAL_MANIFEST_GROUP_PREFIX}:{local_file[:-4]}'
Mike Frysinger54133972021-03-01 21:38:08 -05001013 nodes.append(self._ParseManifestXml(
LaMont Jonescc879a92021-11-18 22:40:18 +00001014 local, self.subdir,
1015 parent_groups=f'{local_group},{parent_groups}',
Raman Tenneti78f4dd32021-06-07 13:27:37 -07001016 restrict_includes=False))
Basil Gelloc7453502018-05-25 20:23:52 +03001017 except OSError:
1018 pass
David Pursehouse2d5a0df2012-11-13 02:50:36 +09001019
Joe Onorato26e24752013-01-11 12:35:53 -08001020 try:
1021 self._ParseManifest(nodes)
1022 except ManifestParseError as e:
1023 # There was a problem parsing, unload ourselves in case they catch
1024 # this error and try again later, we will show the correct error
1025 self._Unload()
1026 raise e
Shawn O. Pearce5cc66792008-10-23 16:19:27 -07001027
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001028 if self.IsMirror:
1029 self._AddMetaProjectMirror(self.repoProject)
1030 self._AddMetaProjectMirror(self.manifestProject)
1031
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001032 self._loaded = True
1033
LaMont Jonescc879a92021-11-18 22:40:18 +00001034 # Now that we have loaded this manifest, load any submanifest manifests
1035 # as well. We need to do this after self._loaded is set to avoid looping.
1036 if self._outer_client:
1037 for name in self._submanifests:
1038 tree = self._submanifests[name]
1039 spec = tree.ToSubmanifestSpec(self)
1040 present = os.path.exists(os.path.join(self.subdir, MANIFEST_FILE_NAME))
1041 if present and tree.present and not tree.repo_client:
1042 if initial_client and initial_client.topdir == self.topdir:
1043 tree.repo_client = self
1044 tree.present = present
1045 elif not os.path.exists(self.subdir):
1046 tree.present = False
1047 if tree.present:
1048 tree.repo_client._Load(initial_client=initial_client,
1049 submanifest_depth=submanifest_depth + 1)
1050
Mike Frysinger54133972021-03-01 21:38:08 -05001051 def _ParseManifestXml(self, path, include_root, parent_groups='',
1052 restrict_includes=True):
1053 """Parse a manifest XML and return the computed nodes.
1054
1055 Args:
1056 path: The XML file to read & parse.
1057 include_root: The path to interpret include "name"s relative to.
1058 parent_groups: The groups to apply to this projects.
1059 restrict_includes: Whether to constrain the "name" attribute of includes.
1060
1061 Returns:
1062 List of XML nodes.
1063 """
David Pursehousef7fc8a92012-11-13 04:00:28 +09001064 try:
1065 root = xml.dom.minidom.parse(path)
David Pursehouse2d5a0df2012-11-13 02:50:36 +09001066 except (OSError, xml.parsers.expat.ExpatError) as e:
David Pursehousef7fc8a92012-11-13 04:00:28 +09001067 raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
1068
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001069 if not root or not root.childNodes:
Brian Harring26448742011-04-28 05:04:41 -07001070 raise ManifestParseError("no root node in %s" % (path,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001071
Jooncheol Park34acdd22012-08-27 02:25:59 +09001072 for manifest in root.childNodes:
1073 if manifest.nodeName == 'manifest':
1074 break
1075 else:
Brian Harring26448742011-04-28 05:04:41 -07001076 raise ManifestParseError("no <manifest> in %s" % (path,))
1077
Colin Cross23acdd32012-04-21 00:33:54 -07001078 nodes = []
David Pursehouse65b0ba52018-06-24 16:21:51 +09001079 for node in manifest.childNodes:
David Pursehousec1b86a22012-11-14 11:36:51 +09001080 if node.nodeName == 'include':
1081 name = self._reqatt(node, 'name')
Mike Frysinger54133972021-03-01 21:38:08 -05001082 if restrict_includes:
1083 msg = self._CheckLocalPath(name)
1084 if msg:
1085 raise ManifestInvalidPathError(
1086 '<include> invalid "name": %s: %s' % (name, msg))
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001087 include_groups = ''
1088 if parent_groups:
1089 include_groups = parent_groups
1090 if node.hasAttribute('groups'):
1091 include_groups = node.getAttribute('groups') + ',' + include_groups
David Pursehousec1b86a22012-11-14 11:36:51 +09001092 fp = os.path.join(include_root, name)
1093 if not os.path.isfile(fp):
Mike Frysinger54133972021-03-01 21:38:08 -05001094 raise ManifestParseError("include [%s/]%s doesn't exist or isn't a file"
1095 % (include_root, name))
David Pursehousec1b86a22012-11-14 11:36:51 +09001096 try:
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001097 nodes.extend(self._ParseManifestXml(fp, include_root, include_groups))
David Pursehousec1b86a22012-11-14 11:36:51 +09001098 # should isolate this to the exact exception, but that's
1099 # tricky. actual parsing implementation may vary.
Mike Frysinger54133972021-03-01 21:38:08 -05001100 except (KeyboardInterrupt, RuntimeError, SystemExit, ManifestParseError):
David Pursehousec1b86a22012-11-14 11:36:51 +09001101 raise
1102 except Exception as e:
1103 raise ManifestParseError(
Mike Frysingerec558df2019-07-05 01:38:05 -04001104 "failed parsing included manifest %s: %s" % (name, e))
David Pursehousec1b86a22012-11-14 11:36:51 +09001105 else:
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001106 if parent_groups and node.nodeName == 'project':
1107 nodeGroups = parent_groups
1108 if node.hasAttribute('groups'):
1109 nodeGroups = node.getAttribute('groups') + ',' + nodeGroups
1110 node.setAttribute('groups', nodeGroups)
David Pursehousec1b86a22012-11-14 11:36:51 +09001111 nodes.append(node)
Colin Cross23acdd32012-04-21 00:33:54 -07001112 return nodes
Brian Harring26448742011-04-28 05:04:41 -07001113
Colin Cross23acdd32012-04-21 00:33:54 -07001114 def _ParseManifest(self, node_list):
1115 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001116 if node.nodeName == 'remote':
1117 remote = self._ParseRemote(node)
David Pursehouse717ece92012-11-13 08:49:16 +09001118 if remote:
1119 if remote.name in self._remotes:
1120 if remote != self._remotes[remote.name]:
1121 raise ManifestParseError(
1122 'remote %s already exists with different attributes' %
1123 (remote.name))
1124 else:
1125 self._remotes[remote.name] = remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001126
Colin Cross23acdd32012-04-21 00:33:54 -07001127 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001128 if node.nodeName == 'default':
Julien Campergue74879922013-10-09 14:38:46 +02001129 new_default = self._ParseDefault(node)
Jack Neusb8c84482021-06-15 14:28:30 +00001130 emptyDefault = not node.hasAttributes() and not node.hasChildNodes()
Julien Campergue74879922013-10-09 14:38:46 +02001131 if self._default is None:
1132 self._default = new_default
Jack Neusb8c84482021-06-15 14:28:30 +00001133 elif not emptyDefault and new_default != self._default:
David Pursehouse37128b62013-10-15 10:48:40 +09001134 raise ManifestParseError('duplicate default in %s' %
1135 (self.manifestFile))
Julien Campergue74879922013-10-09 14:38:46 +02001136
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001137 if self._default is None:
1138 self._default = _Default()
1139
LaMont Jonescc879a92021-11-18 22:40:18 +00001140 submanifest_paths = set()
1141 for node in itertools.chain(*node_list):
1142 if node.nodeName == 'submanifest':
1143 submanifest = self._ParseSubmanifest(node)
1144 if submanifest:
1145 if submanifest.name in self._submanifests:
1146 if submanifest != self._submanifests[submanifest.name]:
1147 raise ManifestParseError(
1148 'submanifest %s already exists with different attributes' %
1149 (submanifest.name))
1150 else:
1151 self._submanifests[submanifest.name] = submanifest
1152 submanifest_paths.add(submanifest.relpath)
1153
Colin Cross23acdd32012-04-21 00:33:54 -07001154 for node in itertools.chain(*node_list):
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001155 if node.nodeName == 'notice':
1156 if self._notice is not None:
Doug Anderson37282b42011-03-04 11:54:18 -08001157 raise ManifestParseError(
1158 'duplicate notice in %s' %
1159 (self.manifestFile))
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001160 self._notice = self._ParseNotice(node)
1161
Colin Cross23acdd32012-04-21 00:33:54 -07001162 for node in itertools.chain(*node_list):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001163 if node.nodeName == 'manifest-server':
1164 url = self._reqatt(node, 'url')
1165 if self._manifest_server is not None:
David Pursehousec1b86a22012-11-14 11:36:51 +09001166 raise ManifestParseError(
1167 'duplicate manifest-server in %s' %
1168 (self.manifestFile))
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001169 self._manifest_server = url
1170
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001171 def recursively_add_projects(project):
David James8d201162013-10-11 17:03:19 -07001172 projects = self._projects.setdefault(project.name, [])
1173 if project.relpath is None:
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001174 raise ManifestParseError(
David James8d201162013-10-11 17:03:19 -07001175 'missing path for %s in %s' %
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001176 (project.name, self.manifestFile))
David James8d201162013-10-11 17:03:19 -07001177 if project.relpath in self._paths:
1178 raise ManifestParseError(
1179 'duplicate path %s in %s' %
1180 (project.relpath, self.manifestFile))
LaMont Jonescc879a92021-11-18 22:40:18 +00001181 for tree in submanifest_paths:
1182 if project.relpath.startswith(tree):
1183 raise ManifestParseError(
1184 'project %s conflicts with submanifest path %s' %
1185 (project.relpath, tree))
David James8d201162013-10-11 17:03:19 -07001186 self._paths[project.relpath] = project
1187 projects.append(project)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001188 for subproject in project.subprojects:
1189 recursively_add_projects(subproject)
1190
Jack Neusa84f43a2021-09-21 22:23:55 +00001191 repo_hooks_project = None
1192 enabled_repo_hooks = None
Colin Cross23acdd32012-04-21 00:33:54 -07001193 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001194 if node.nodeName == 'project':
1195 project = self._ParseProject(node)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001196 recursively_add_projects(project)
Josh Triplett884a3872014-06-12 14:57:29 -07001197 if node.nodeName == 'extend-project':
1198 name = self._reqatt(node, 'name')
1199
1200 if name not in self._projects:
1201 raise ManifestParseError('extend-project element specifies non-existent '
1202 'project: %s' % name)
1203
1204 path = node.getAttribute('path')
Michael Kelly37c21c22020-06-13 02:10:40 -07001205 dest_path = node.getAttribute('dest-path')
Josh Triplett884a3872014-06-12 14:57:29 -07001206 groups = node.getAttribute('groups')
1207 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -05001208 groups = self._ParseList(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -07001209 revision = node.getAttribute('revision')
LaMont Jonescc879a92021-11-18 22:40:18 +00001210 remote_name = node.getAttribute('remote')
1211 if not remote_name:
1212 remote = self._default.remote
1213 else:
Kyunam Jobd0aae92020-02-04 11:38:53 +09001214 remote = self._get_remote(node)
Josh Triplett884a3872014-06-12 14:57:29 -07001215
Michael Kelly37c21c22020-06-13 02:10:40 -07001216 named_projects = self._projects[name]
1217 if dest_path and not path and len(named_projects) > 1:
1218 raise ManifestParseError('extend-project cannot use dest-path when '
1219 'matching multiple projects: %s' % name)
Josh Triplett884a3872014-06-12 14:57:29 -07001220 for p in self._projects[name]:
1221 if path and p.relpath != path:
1222 continue
1223 if groups:
1224 p.groups.extend(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -07001225 if revision:
Michael Kelly2f3c3312020-07-21 19:40:38 -07001226 p.SetRevision(revision)
1227
LaMont Jonescc879a92021-11-18 22:40:18 +00001228 if remote_name:
Kyunam Jobd0aae92020-02-04 11:38:53 +09001229 p.remote = remote.ToRemoteSpec(name)
Michael Kelly2f3c3312020-07-21 19:40:38 -07001230
Michael Kelly37c21c22020-06-13 02:10:40 -07001231 if dest_path:
1232 del self._paths[p.relpath]
LaMont Jonescc879a92021-11-18 22:40:18 +00001233 relpath, worktree, gitdir, objdir, _ = self.GetProjectPaths(
1234 name, dest_path, remote.name)
Michael Kelly37c21c22020-06-13 02:10:40 -07001235 p.UpdatePaths(relpath, worktree, gitdir, objdir)
1236 self._paths[p.relpath] = p
1237
Doug Anderson37282b42011-03-04 11:54:18 -08001238 if node.nodeName == 'repo-hooks':
Doug Anderson37282b42011-03-04 11:54:18 -08001239 # Only one project can be the hooks project
Jack Neusa84f43a2021-09-21 22:23:55 +00001240 if repo_hooks_project is not None:
Doug Anderson37282b42011-03-04 11:54:18 -08001241 raise ManifestParseError(
1242 'duplicate repo-hooks in %s' %
1243 (self.manifestFile))
1244
Jack Neusa84f43a2021-09-21 22:23:55 +00001245 # Get the name of the project and the (space-separated) list of enabled.
1246 repo_hooks_project = self._reqatt(node, 'in-project')
1247 enabled_repo_hooks = self._ParseList(self._reqatt(node, 'enabled-list'))
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001248 if node.nodeName == 'superproject':
1249 name = self._reqatt(node, 'name')
1250 # There can only be one superproject.
1251 if self._superproject.get('name'):
1252 raise ManifestParseError(
1253 'duplicate superproject in %s' %
1254 (self.manifestFile))
1255 self._superproject['name'] = name
1256 remote_name = node.getAttribute('remote')
1257 if not remote_name:
1258 remote = self._default.remote
1259 else:
1260 remote = self._get_remote(node)
1261 if remote is None:
1262 raise ManifestParseError("no remote for superproject %s within %s" %
1263 (name, self.manifestFile))
1264 self._superproject['remote'] = remote.ToRemoteSpec(name)
Xin Lie0b16a22021-09-26 23:20:32 -07001265 revision = node.getAttribute('revision') or remote.revision
1266 if not revision:
1267 revision = self._default.revisionExpr
1268 if not revision:
1269 raise ManifestParseError('no revision for superproject %s within %s' %
1270 (name, self.manifestFile))
1271 self._superproject['revision'] = revision
Raman Tenneti1c3f57e2021-05-04 12:32:13 -07001272 if node.nodeName == 'contactinfo':
1273 bugurl = self._reqatt(node, 'bugurl')
1274 # This element can be repeated, later entries will clobber earlier ones.
Raman Tenneti993af5e2021-05-12 12:00:31 -07001275 self._contactinfo = ContactInfo(bugurl)
1276
Colin Cross23acdd32012-04-21 00:33:54 -07001277 if node.nodeName == 'remove-project':
1278 name = self._reqatt(node, 'name')
David Jamesb8433df2014-01-30 10:11:17 -08001279
Michael Kelly06da9982021-06-30 01:58:28 -07001280 if name in self._projects:
1281 for p in self._projects[name]:
1282 del self._paths[p.relpath]
1283 del self._projects[name]
1284
1285 # If the manifest removes the hooks project, treat it as if it deleted
1286 # the repo-hooks element too.
Jack Neusa84f43a2021-09-21 22:23:55 +00001287 if repo_hooks_project == name:
1288 repo_hooks_project = None
Michael Kelly06da9982021-06-30 01:58:28 -07001289 elif not XmlBool(node, 'optional', False):
David Pursehousef9107482012-11-16 19:12:32 +09001290 raise ManifestParseError('remove-project element specifies non-existent '
1291 'project: %s' % name)
Colin Cross23acdd32012-04-21 00:33:54 -07001292
Jack Neusa84f43a2021-09-21 22:23:55 +00001293 # Store repo hooks project information.
1294 if repo_hooks_project:
1295 # Store a reference to the Project.
1296 try:
1297 repo_hooks_projects = self._projects[repo_hooks_project]
1298 except KeyError:
1299 raise ManifestParseError(
1300 'project %s not found for repo-hooks' %
1301 (repo_hooks_project))
1302
1303 if len(repo_hooks_projects) != 1:
1304 raise ManifestParseError(
1305 'internal error parsing repo-hooks in %s' %
1306 (self.manifestFile))
1307 self._repo_hooks_project = repo_hooks_projects[0]
1308 # Store the enabled hooks in the Project object.
1309 self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
1310
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001311 def _AddMetaProjectMirror(self, m):
1312 name = None
1313 m_url = m.GetRemote(m.remote.name).url
1314 if m_url.endswith('/.git'):
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301315 raise ManifestParseError('refusing to mirror %s' % m_url)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001316
1317 if self._default and self._default.remote:
Conley Owensceea3682011-10-20 10:45:47 -07001318 url = self._default.remote.resolvedFetchUrl
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001319 if not url.endswith('/'):
1320 url += '/'
1321 if m_url.startswith(url):
1322 remote = self._default.remote
1323 name = m_url[len(url):]
1324
1325 if name is None:
1326 s = m_url.rindex('/') + 1
Conley Owensdb728cd2011-09-26 16:34:01 -07001327 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Shawn O. Pearcef35b2d92012-08-02 11:46:22 -07001328 remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001329 name = m_url[s:]
1330
1331 if name.endswith('.git'):
1332 name = name[:-4]
1333
1334 if name not in self._projects:
1335 m.PreSync()
1336 gitdir = os.path.join(self.topdir, '%s.git' % name)
David Pursehousee5913ae2020-02-12 13:56:59 +09001337 project = Project(manifest=self,
1338 name=name,
1339 remote=remote.ToRemoteSpec(name),
1340 gitdir=gitdir,
1341 objdir=gitdir,
1342 worktree=None,
1343 relpath=name or None,
1344 revisionExpr=m.revisionExpr,
1345 revisionId=None)
David James8d201162013-10-11 17:03:19 -07001346 self._projects[project.name] = [project]
Kwanhong Leeccd218c2014-02-17 13:07:32 +09001347 self._paths[project.relpath] = project
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001348
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001349 def _ParseRemote(self, node):
1350 """
1351 reads a <remote> element from the manifest file
1352 """
1353 name = self._reqatt(node, 'name')
Yestin Sunb292b982012-07-02 07:32:50 -07001354 alias = node.getAttribute('alias')
1355 if alias == '':
1356 alias = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001357 fetch = self._reqatt(node, 'fetch')
Steve Raed6480452016-08-10 15:00:00 -07001358 pushUrl = node.getAttribute('pushurl')
1359 if pushUrl == '':
1360 pushUrl = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001361 review = node.getAttribute('review')
Shawn O. Pearceae6e0942008-11-06 10:25:35 -08001362 if review == '':
1363 review = None
Anthony King36ea2fb2014-05-06 11:54:01 +01001364 revision = node.getAttribute('revision')
1365 if revision == '':
1366 revision = None
Conley Owensdb728cd2011-09-26 16:34:01 -07001367 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Jack Neus6ea0cae2021-07-20 20:52:33 +00001368
1369 remote = _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
1370
1371 for n in node.childNodes:
1372 if n.nodeName == 'annotation':
1373 self._ParseAnnotation(remote, n)
1374
1375 return remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001376
1377 def _ParseDefault(self, node):
1378 """
1379 reads a <default> element from the manifest file
1380 """
1381 d = _Default()
1382 d.remote = self._get_remote(node)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001383 d.revisionExpr = node.getAttribute('revision')
1384 if d.revisionExpr == '':
1385 d.revisionExpr = None
Anatol Pomazau79770d22012-04-20 14:41:59 -07001386
Bryan Jacobsf609f912013-05-06 13:36:24 -04001387 d.destBranchExpr = node.getAttribute('dest-branch') or None
Nasser Grainawida403412018-05-04 12:53:29 -06001388 d.upstreamExpr = node.getAttribute('upstream') or None
Bryan Jacobsf609f912013-05-06 13:36:24 -04001389
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001390 d.sync_j = XmlInt(node, 'sync-j', 1)
1391 if d.sync_j <= 0:
1392 raise ManifestParseError('%s: sync-j must be greater than 0, not "%s"' %
1393 (self.manifestFile, d.sync_j))
Anatol Pomazau79770d22012-04-20 14:41:59 -07001394
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001395 d.sync_c = XmlBool(node, 'sync-c', False)
1396 d.sync_s = XmlBool(node, 'sync-s', False)
1397 d.sync_tags = XmlBool(node, 'sync-tags', True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001398 return d
1399
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001400 def _ParseNotice(self, node):
1401 """
1402 reads a <notice> element from the manifest file
1403
1404 The <notice> element is distinct from other tags in the XML in that the
1405 data is conveyed between the start and end tag (it's not an empty-element
1406 tag).
1407
1408 The white space (carriage returns, indentation) for the notice element is
1409 relevant and is parsed in a way that is based on how python docstrings work.
1410 In fact, the code is remarkably similar to here:
1411 http://www.python.org/dev/peps/pep-0257/
1412 """
1413 # Get the data out of the node...
1414 notice = node.childNodes[0].data
1415
1416 # Figure out minimum indentation, skipping the first line (the same line
1417 # as the <notice> tag)...
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301418 minIndent = sys.maxsize
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001419 lines = notice.splitlines()
1420 for line in lines[1:]:
1421 lstrippedLine = line.lstrip()
1422 if lstrippedLine:
1423 indent = len(line) - len(lstrippedLine)
1424 minIndent = min(indent, minIndent)
1425
1426 # Strip leading / trailing blank lines and also indentation.
1427 cleanLines = [lines[0].strip()]
1428 for line in lines[1:]:
1429 cleanLines.append(line[minIndent:].rstrip())
1430
1431 # Clear completely blank lines from front and back...
1432 while cleanLines and not cleanLines[0]:
1433 del cleanLines[0]
1434 while cleanLines and not cleanLines[-1]:
1435 del cleanLines[-1]
1436
1437 return '\n'.join(cleanLines)
1438
LaMont Jonescc879a92021-11-18 22:40:18 +00001439 def _ParseSubmanifest(self, node):
1440 """Reads a <submanifest> element from the manifest file."""
1441 name = self._reqatt(node, 'name')
1442 remote = node.getAttribute('remote')
1443 if remote == '':
1444 remote = None
1445 project = node.getAttribute('project')
1446 if project == '':
1447 project = None
1448 revision = node.getAttribute('revision')
1449 if revision == '':
1450 revision = None
1451 manifestName = node.getAttribute('manifest-name')
1452 if manifestName == '':
1453 manifestName = None
1454 groups = ''
1455 if node.hasAttribute('groups'):
1456 groups = node.getAttribute('groups')
1457 groups = self._ParseList(groups)
1458 path = node.getAttribute('path')
1459 if path == '':
1460 path = None
1461 if revision:
1462 msg = self._CheckLocalPath(revision.split('/')[-1])
1463 if msg:
1464 raise ManifestInvalidPathError(
1465 '<submanifest> invalid "revision": %s: %s' % (revision, msg))
1466 else:
1467 msg = self._CheckLocalPath(name)
1468 if msg:
1469 raise ManifestInvalidPathError(
1470 '<submanifest> invalid "name": %s: %s' % (name, msg))
1471 else:
1472 msg = self._CheckLocalPath(path)
1473 if msg:
1474 raise ManifestInvalidPathError(
1475 '<submanifest> invalid "path": %s: %s' % (path, msg))
1476
1477 submanifest = _XmlSubmanifest(name, remote, project, revision, manifestName,
1478 groups, path, self)
1479
1480 for n in node.childNodes:
1481 if n.nodeName == 'annotation':
1482 self._ParseAnnotation(submanifest, n)
1483
1484 return submanifest
1485
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001486 def _JoinName(self, parent_name, name):
1487 return os.path.join(parent_name, name)
1488
1489 def _UnjoinName(self, parent_name, name):
1490 return os.path.relpath(name, parent_name)
1491
David Pursehousee5913ae2020-02-12 13:56:59 +09001492 def _ParseProject(self, node, parent=None, **extra_proj_attrs):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001493 """
1494 reads a <project> element from the manifest file
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001495 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001496 name = self._reqatt(node, 'name')
Mike Frysingera29424e2021-02-25 21:53:49 -05001497 msg = self._CheckLocalPath(name, dir_ok=True)
1498 if msg:
1499 raise ManifestInvalidPathError(
1500 '<project> invalid "name": %s: %s' % (name, msg))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001501 if parent:
1502 name = self._JoinName(parent.name, name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001503
1504 remote = self._get_remote(node)
1505 if remote is None:
1506 remote = self._default.remote
1507 if remote is None:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301508 raise ManifestParseError("no remote for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001509 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001510
Anthony King36ea2fb2014-05-06 11:54:01 +01001511 revisionExpr = node.getAttribute('revision') or remote.revision
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001512 if not revisionExpr:
1513 revisionExpr = self._default.revisionExpr
1514 if not revisionExpr:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301515 raise ManifestParseError("no revision for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001516 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001517
1518 path = node.getAttribute('path')
1519 if not path:
1520 path = name
Mike Frysingera29424e2021-02-25 21:53:49 -05001521 else:
Mike Frysinger0458faa2021-03-10 23:35:44 -05001522 # NB: The "." project is handled specially in Project.Sync_LocalHalf.
1523 msg = self._CheckLocalPath(path, dir_ok=True, cwd_dot_ok=True)
Mike Frysingera29424e2021-02-25 21:53:49 -05001524 if msg:
1525 raise ManifestInvalidPathError(
1526 '<project> invalid "path": %s: %s' % (path, msg))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001527
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001528 rebase = XmlBool(node, 'rebase', True)
1529 sync_c = XmlBool(node, 'sync-c', False)
1530 sync_s = XmlBool(node, 'sync-s', self._default.sync_s)
1531 sync_tags = XmlBool(node, 'sync-tags', self._default.sync_tags)
Mike Pontillod3153822012-02-28 11:53:24 -08001532
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001533 clone_depth = XmlInt(node, 'clone-depth')
1534 if clone_depth is not None and clone_depth <= 0:
1535 raise ManifestParseError('%s: clone-depth must be greater than 0, not "%s"' %
1536 (self.manifestFile, clone_depth))
David Pursehouseede7f122012-11-27 22:25:30 +09001537
Bryan Jacobsf609f912013-05-06 13:36:24 -04001538 dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
1539
Nasser Grainawida403412018-05-04 12:53:29 -06001540 upstream = node.getAttribute('upstream') or self._default.upstreamExpr
Brian Harring14a66742012-09-28 20:21:57 -07001541
Conley Owens971de8e2012-04-16 10:36:08 -07001542 groups = ''
1543 if node.hasAttribute('groups'):
1544 groups = node.getAttribute('groups')
Mike Frysinger51e39d52020-12-04 05:32:06 -05001545 groups = self._ParseList(groups)
Brian Harring7da13142012-06-15 02:24:20 -07001546
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001547 if parent is None:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001548 relpath, worktree, gitdir, objdir, use_git_worktrees = \
LaMont Jonescc879a92021-11-18 22:40:18 +00001549 self.GetProjectPaths(name, path, remote.name)
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001550 else:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001551 use_git_worktrees = False
David James8d201162013-10-11 17:03:19 -07001552 relpath, worktree, gitdir, objdir = \
1553 self.GetSubprojectPaths(parent, name, path)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001554
1555 default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
1556 groups.extend(set(default_groups).difference(groups))
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001557
Scott Fandb83b1b2013-02-28 09:34:14 +08001558 if self.IsMirror and node.hasAttribute('force-path'):
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001559 if XmlBool(node, 'force-path', False):
Scott Fandb83b1b2013-02-28 09:34:14 +08001560 gitdir = os.path.join(self.topdir, '%s.git' % path)
1561
David Pursehousee5913ae2020-02-12 13:56:59 +09001562 project = Project(manifest=self,
1563 name=name,
1564 remote=remote.ToRemoteSpec(name),
1565 gitdir=gitdir,
1566 objdir=objdir,
1567 worktree=worktree,
1568 relpath=relpath,
1569 revisionExpr=revisionExpr,
1570 revisionId=None,
1571 rebase=rebase,
1572 groups=groups,
1573 sync_c=sync_c,
1574 sync_s=sync_s,
1575 sync_tags=sync_tags,
1576 clone_depth=clone_depth,
1577 upstream=upstream,
1578 parent=parent,
1579 dest_branch=dest_branch,
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001580 use_git_worktrees=use_git_worktrees,
Simran Basib9a1b732015-08-20 12:19:28 -07001581 **extra_proj_attrs)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001582
1583 for n in node.childNodes:
Shawn O. Pearce242b5262009-05-19 13:00:29 -07001584 if n.nodeName == 'copyfile':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001585 self._ParseCopyFile(project, n)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001586 if n.nodeName == 'linkfile':
1587 self._ParseLinkFile(project, n)
James W. Mills24c13082012-04-12 15:04:13 -05001588 if n.nodeName == 'annotation':
1589 self._ParseAnnotation(project, n)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001590 if n.nodeName == 'project':
David Pursehousee5913ae2020-02-12 13:56:59 +09001591 project.subprojects.append(self._ParseProject(n, parent=project))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001592
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001593 return project
1594
LaMont Jonescc879a92021-11-18 22:40:18 +00001595 def GetProjectPaths(self, name, path, remote):
1596 """Return the paths for a project.
1597
1598 Args:
1599 name: a string, the name of the project.
1600 path: a string, the path of the project.
1601 remote: a string, the remote.name of the project.
1602 """
Mike Frysingercebf2272020-05-26 01:02:29 -04001603 # The manifest entries might have trailing slashes. Normalize them to avoid
1604 # unexpected filesystem behavior since we do string concatenation below.
1605 path = path.rstrip('/')
1606 name = name.rstrip('/')
LaMont Jonescc879a92021-11-18 22:40:18 +00001607 remote = remote.rstrip('/')
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001608 use_git_worktrees = False
LaMont Jonescc879a92021-11-18 22:40:18 +00001609 use_remote_name = bool(self._outer_client._submanifests)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001610 relpath = path
1611 if self.IsMirror:
1612 worktree = None
1613 gitdir = os.path.join(self.topdir, '%s.git' % name)
David James8d201162013-10-11 17:03:19 -07001614 objdir = gitdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001615 else:
LaMont Jonescc879a92021-11-18 22:40:18 +00001616 if use_remote_name:
1617 namepath = os.path.join(remote, f'{name}.git')
1618 else:
1619 namepath = f'{name}.git'
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001620 worktree = os.path.join(self.topdir, path).replace('\\', '/')
LaMont Jonescc879a92021-11-18 22:40:18 +00001621 gitdir = os.path.join(self.subdir, 'projects', '%s.git' % path)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001622 # We allow people to mix git worktrees & non-git worktrees for now.
1623 # This allows for in situ migration of repo clients.
1624 if os.path.exists(gitdir) or not self.UseGitWorktrees:
LaMont Jonescc879a92021-11-18 22:40:18 +00001625 objdir = os.path.join(self.subdir, 'project-objects', namepath)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001626 else:
1627 use_git_worktrees = True
LaMont Jonescc879a92021-11-18 22:40:18 +00001628 gitdir = os.path.join(self.repodir, 'worktrees', namepath)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001629 objdir = gitdir
1630 return relpath, worktree, gitdir, objdir, use_git_worktrees
David James8d201162013-10-11 17:03:19 -07001631
LaMont Jonescc879a92021-11-18 22:40:18 +00001632 def GetProjectsWithName(self, name, all_manifests=False):
1633 """All projects with |name|.
1634
1635 Args:
1636 name: a string, the name of the project.
1637 all_manifests: a boolean, if True, then all manifests are searched. If
1638 False, then only this manifest is searched.
1639 """
1640 if all_manifests:
1641 return list(itertools.chain.from_iterable(
1642 x._projects.get(name, []) for x in self.all_manifests))
David James8d201162013-10-11 17:03:19 -07001643 return self._projects.get(name, [])
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001644
1645 def GetSubprojectName(self, parent, submodule_path):
1646 return os.path.join(parent.name, submodule_path)
1647
1648 def _JoinRelpath(self, parent_relpath, relpath):
1649 return os.path.join(parent_relpath, relpath)
1650
1651 def _UnjoinRelpath(self, parent_relpath, relpath):
1652 return os.path.relpath(relpath, parent_relpath)
1653
David James8d201162013-10-11 17:03:19 -07001654 def GetSubprojectPaths(self, parent, name, path):
Mike Frysingercebf2272020-05-26 01:02:29 -04001655 # The manifest entries might have trailing slashes. Normalize them to avoid
1656 # unexpected filesystem behavior since we do string concatenation below.
1657 path = path.rstrip('/')
1658 name = name.rstrip('/')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001659 relpath = self._JoinRelpath(parent.relpath, path)
1660 gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
David James8d201162013-10-11 17:03:19 -07001661 objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001662 if self.IsMirror:
1663 worktree = None
1664 else:
1665 worktree = os.path.join(parent.worktree, path).replace('\\', '/')
David James8d201162013-10-11 17:03:19 -07001666 return relpath, worktree, gitdir, objdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001667
Mike Frysinger04122b72019-07-31 23:32:58 -04001668 @staticmethod
Mike Frysingera00c5f42021-02-25 18:26:31 -05001669 def _CheckLocalPath(path, dir_ok=False, cwd_dot_ok=False):
1670 """Verify |path| is reasonable for use in filesystem paths.
1671
Mike Frysingera29424e2021-02-25 21:53:49 -05001672 Used with <copyfile> & <linkfile> & <project> elements.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001673
1674 This only validates the |path| in isolation: it does not check against the
1675 current filesystem state. Thus it is suitable as a first-past in a parser.
1676
1677 It enforces a number of constraints:
1678 * No empty paths.
1679 * No "~" in paths.
1680 * No Unicode codepoints that filesystems might elide when normalizing.
1681 * No relative path components like "." or "..".
1682 * No absolute paths.
1683 * No ".git" or ".repo*" path components.
1684
1685 Args:
1686 path: The path name to validate.
1687 dir_ok: Whether |path| may force a directory (e.g. end in a /).
1688 cwd_dot_ok: Whether |path| may be just ".".
1689
1690 Returns:
1691 None if |path| is OK, a failure message otherwise.
1692 """
1693 if not path:
1694 return 'empty paths not allowed'
1695
Mike Frysinger04122b72019-07-31 23:32:58 -04001696 if '~' in path:
1697 return '~ not allowed (due to 8.3 filenames on Windows filesystems)'
1698
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001699 path_codepoints = set(path)
1700
Mike Frysinger04122b72019-07-31 23:32:58 -04001701 # Some filesystems (like Apple's HFS+) try to normalize Unicode codepoints
1702 # which means there are alternative names for ".git". Reject paths with
1703 # these in it as there shouldn't be any reasonable need for them here.
1704 # The set of codepoints here was cribbed from jgit's implementation:
1705 # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
1706 BAD_CODEPOINTS = {
1707 u'\u200C', # ZERO WIDTH NON-JOINER
1708 u'\u200D', # ZERO WIDTH JOINER
1709 u'\u200E', # LEFT-TO-RIGHT MARK
1710 u'\u200F', # RIGHT-TO-LEFT MARK
1711 u'\u202A', # LEFT-TO-RIGHT EMBEDDING
1712 u'\u202B', # RIGHT-TO-LEFT EMBEDDING
1713 u'\u202C', # POP DIRECTIONAL FORMATTING
1714 u'\u202D', # LEFT-TO-RIGHT OVERRIDE
1715 u'\u202E', # RIGHT-TO-LEFT OVERRIDE
1716 u'\u206A', # INHIBIT SYMMETRIC SWAPPING
1717 u'\u206B', # ACTIVATE SYMMETRIC SWAPPING
1718 u'\u206C', # INHIBIT ARABIC FORM SHAPING
1719 u'\u206D', # ACTIVATE ARABIC FORM SHAPING
1720 u'\u206E', # NATIONAL DIGIT SHAPES
1721 u'\u206F', # NOMINAL DIGIT SHAPES
1722 u'\uFEFF', # ZERO WIDTH NO-BREAK SPACE
1723 }
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001724 if BAD_CODEPOINTS & path_codepoints:
Mike Frysinger04122b72019-07-31 23:32:58 -04001725 # This message is more expansive than reality, but should be fine.
1726 return 'Unicode combining characters not allowed'
1727
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001728 # Reject newlines as there shouldn't be any legitmate use for them, they'll
1729 # be confusing to users, and they can easily break tools that expect to be
1730 # able to iterate over newline delimited lists. This even applies to our
1731 # own code like .repo/project.list.
1732 if {'\r', '\n'} & path_codepoints:
1733 return 'Newlines not allowed'
1734
Mike Frysinger04122b72019-07-31 23:32:58 -04001735 # Assume paths might be used on case-insensitive filesystems.
1736 path = path.lower()
1737
Mike Frysingerd9254592020-02-19 22:36:26 -05001738 # Split up the path by its components. We can't use os.path.sep exclusively
1739 # as some platforms (like Windows) will convert / to \ and that bypasses all
1740 # our constructed logic here. Especially since manifest authors only use
1741 # / in their paths.
1742 resep = re.compile(r'[/%s]' % re.escape(os.path.sep))
Mike Frysinger0458faa2021-03-10 23:35:44 -05001743 # Strip off trailing slashes as those only produce '' elements, and we use
1744 # parts to look for individual bad components.
1745 parts = resep.split(path.rstrip('/'))
Mike Frysingerd9254592020-02-19 22:36:26 -05001746
Mike Frysingerae625412020-02-10 17:10:03 -05001747 # Some people use src="." to create stable links to projects. Lets allow
1748 # that but reject all other uses of "." to keep things simple.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001749 if not cwd_dot_ok or parts != ['.']:
Mike Frysingerae625412020-02-10 17:10:03 -05001750 for part in set(parts):
1751 if part in {'.', '..', '.git'} or part.startswith('.repo'):
1752 return 'bad component: %s' % (part,)
Mike Frysinger04122b72019-07-31 23:32:58 -04001753
Mike Frysingera00c5f42021-02-25 18:26:31 -05001754 if not dir_ok and resep.match(path[-1]):
Mike Frysinger04122b72019-07-31 23:32:58 -04001755 return 'dirs not allowed'
1756
Mike Frysingerd9254592020-02-19 22:36:26 -05001757 # NB: The two abspath checks here are to handle platforms with multiple
1758 # filesystem path styles (e.g. Windows).
Mike Frysinger04122b72019-07-31 23:32:58 -04001759 norm = os.path.normpath(path)
Mike Frysingerd9254592020-02-19 22:36:26 -05001760 if (norm == '..' or
1761 (len(norm) >= 3 and norm.startswith('..') and resep.match(norm[0])) or
1762 os.path.isabs(norm) or
1763 norm.startswith('/')):
Mike Frysinger04122b72019-07-31 23:32:58 -04001764 return 'path cannot be outside'
1765
1766 @classmethod
1767 def _ValidateFilePaths(cls, element, src, dest):
1768 """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
1769
1770 We verify the path independent of any filesystem state as we won't have a
1771 checkout available to compare to. i.e. This is for parsing validation
1772 purposes only.
1773
1774 We'll do full/live sanity checking before we do the actual filesystem
1775 modifications in _CopyFile/_LinkFile/etc...
1776 """
1777 # |dest| is the file we write to or symlink we create.
1778 # It is relative to the top of the repo client checkout.
1779 msg = cls._CheckLocalPath(dest)
1780 if msg:
1781 raise ManifestInvalidPathError(
1782 '<%s> invalid "dest": %s: %s' % (element, dest, msg))
1783
1784 # |src| is the file we read from or path we point to for symlinks.
1785 # It is relative to the top of the git project checkout.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001786 is_linkfile = element == 'linkfile'
1787 msg = cls._CheckLocalPath(src, dir_ok=is_linkfile, cwd_dot_ok=is_linkfile)
Mike Frysinger04122b72019-07-31 23:32:58 -04001788 if msg:
1789 raise ManifestInvalidPathError(
1790 '<%s> invalid "src": %s: %s' % (element, src, msg))
1791
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001792 def _ParseCopyFile(self, project, node):
1793 src = self._reqatt(node, 'src')
1794 dest = self._reqatt(node, 'dest')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001795 if not self.IsMirror:
1796 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001797 # dest is relative to the top of the tree.
1798 # We only validate paths if we actually plan to process them.
1799 self._ValidateFilePaths('copyfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001800 project.AddCopyFile(src, dest, self.topdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001801
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001802 def _ParseLinkFile(self, project, node):
1803 src = self._reqatt(node, 'src')
1804 dest = self._reqatt(node, 'dest')
1805 if not self.IsMirror:
1806 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001807 # dest is relative to the top of the tree.
1808 # We only validate paths if we actually plan to process them.
1809 self._ValidateFilePaths('linkfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001810 project.AddLinkFile(src, dest, self.topdir)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001811
Jack Neus6ea0cae2021-07-20 20:52:33 +00001812 def _ParseAnnotation(self, element, node):
James W. Mills24c13082012-04-12 15:04:13 -05001813 name = self._reqatt(node, 'name')
1814 value = self._reqatt(node, 'value')
1815 try:
1816 keep = self._reqatt(node, 'keep').lower()
1817 except ManifestParseError:
1818 keep = "true"
1819 if keep != "true" and keep != "false":
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301820 raise ManifestParseError('optional "keep" attribute must be '
David Pursehouseabdf7502020-02-12 14:58:39 +09001821 '"true" or "false"')
Jack Neus6ea0cae2021-07-20 20:52:33 +00001822 element.AddAnnotation(name, value, keep)
James W. Mills24c13082012-04-12 15:04:13 -05001823
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001824 def _get_remote(self, node):
1825 name = node.getAttribute('remote')
1826 if not name:
1827 return None
1828
1829 v = self._remotes.get(name)
1830 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301831 raise ManifestParseError("remote %s not defined in %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001832 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001833 return v
1834
1835 def _reqatt(self, node, attname):
1836 """
1837 reads a required attribute from the node.
1838 """
1839 v = node.getAttribute(attname)
1840 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301841 raise ManifestParseError("no %s in <%s> within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001842 (attname, node.nodeName, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001843 return v
Julien Camperguedd654222014-01-09 16:21:37 +01001844
1845 def projectsDiff(self, manifest):
1846 """return the projects differences between two manifests.
1847
1848 The diff will be from self to given manifest.
1849
1850 """
1851 fromProjects = self.paths
1852 toProjects = manifest.paths
1853
Anthony King7446c592014-05-06 09:19:39 +01001854 fromKeys = sorted(fromProjects.keys())
1855 toKeys = sorted(toProjects.keys())
Julien Camperguedd654222014-01-09 16:21:37 +01001856
1857 diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
1858
1859 for proj in fromKeys:
David Pursehouseeeff3532020-02-12 11:24:10 +09001860 if proj not in toKeys:
Julien Camperguedd654222014-01-09 16:21:37 +01001861 diff['removed'].append(fromProjects[proj])
1862 else:
1863 fromProj = fromProjects[proj]
1864 toProj = toProjects[proj]
1865 try:
1866 fromRevId = fromProj.GetCommitRevisionId()
1867 toRevId = toProj.GetCommitRevisionId()
1868 except ManifestInvalidRevisionError:
1869 diff['unreachable'].append((fromProj, toProj))
1870 else:
1871 if fromRevId != toRevId:
1872 diff['changed'].append((fromProj, toProj))
1873 toKeys.remove(proj)
1874
1875 for proj in toKeys:
1876 diff['added'].append(toProjects[proj])
1877
1878 return diff
Simran Basib9a1b732015-08-20 12:19:28 -07001879
1880
1881class GitcManifest(XmlManifest):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001882 """Parser for GitC (git-in-the-cloud) manifests."""
Simran Basib9a1b732015-08-20 12:19:28 -07001883
David Pursehousee5913ae2020-02-12 13:56:59 +09001884 def _ParseProject(self, node, parent=None):
Simran Basib9a1b732015-08-20 12:19:28 -07001885 """Override _ParseProject and add support for GITC specific attributes."""
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001886 return super()._ParseProject(
Simran Basib9a1b732015-08-20 12:19:28 -07001887 node, parent=parent, old_revision=node.getAttribute('old-revision'))
1888
1889 def _output_manifest_project_extras(self, p, e):
1890 """Output GITC Specific Project attributes"""
1891 if p.old_revision:
Stefan Beller66851062016-06-17 16:40:08 -07001892 e.setAttribute('old-revision', str(p.old_revision))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001893
1894
1895class RepoClient(XmlManifest):
1896 """Manages a repo client checkout."""
1897
LaMont Jonescc879a92021-11-18 22:40:18 +00001898 def __init__(self, repodir, manifest_file=None, submanifest_path='', **kwargs):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001899 self.isGitcClient = False
LaMont Jonescc879a92021-11-18 22:40:18 +00001900 submanifest_path = submanifest_path or ''
1901 if submanifest_path:
1902 self._CheckLocalPath(submanifest_path)
1903 prefix = os.path.join(repodir, SUBMANIFEST_DIR, submanifest_path)
1904 else:
1905 prefix = repodir
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001906
LaMont Jonescc879a92021-11-18 22:40:18 +00001907 if os.path.exists(os.path.join(prefix, LOCAL_MANIFEST_NAME)):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001908 print('error: %s is not supported; put local manifests in `%s` instead' %
LaMont Jonescc879a92021-11-18 22:40:18 +00001909 (LOCAL_MANIFEST_NAME, os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME)),
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001910 file=sys.stderr)
1911 sys.exit(1)
1912
1913 if manifest_file is None:
LaMont Jonescc879a92021-11-18 22:40:18 +00001914 manifest_file = os.path.join(prefix, MANIFEST_FILE_NAME)
1915 local_manifests = os.path.abspath(os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME))
1916 super().__init__(repodir, manifest_file, local_manifests,
1917 submanifest_path=submanifest_path, **kwargs)
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001918
1919 # TODO: Completely separate manifest logic out of the client.
1920 self.manifest = self
1921
1922
1923class GitcClient(RepoClient, GitcManifest):
1924 """Manages a GitC client checkout."""
1925
1926 def __init__(self, repodir, gitc_client_name):
1927 """Initialize the GitcManifest object."""
1928 self.gitc_client_name = gitc_client_name
1929 self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
1930 gitc_client_name)
1931
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001932 super().__init__(repodir, os.path.join(self.gitc_client_dir, '.manifest'))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001933 self.isGitcClient = True