blob: 7a4eb1e86af11f5b4ec33d46cc50445c39056e90 [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
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070039
Raman Tenneti78f4dd32021-06-07 13:27:37 -070040# Add all projects from local manifest into a group.
41LOCAL_MANIFEST_GROUP_PREFIX = 'local:'
42
Raman Tenneti993af5e2021-05-12 12:00:31 -070043# ContactInfo has the self-registered bug url, supplied by the manifest authors.
44ContactInfo = collections.namedtuple('ContactInfo', 'bugurl')
45
Anthony Kingcb07ba72015-03-28 23:26:04 +000046# urljoin gets confused if the scheme is not known.
Joe Kilner6e310792016-10-27 15:53:53 -070047urllib.parse.uses_relative.extend([
48 'ssh',
49 'git',
50 'persistent-https',
51 'sso',
52 'rpc'])
53urllib.parse.uses_netloc.extend([
54 'ssh',
55 'git',
56 'persistent-https',
57 'sso',
58 'rpc'])
Conley Owensdb728cd2011-09-26 16:34:01 -070059
David Pursehouse819827a2020-02-12 15:20:19 +090060
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050061def XmlBool(node, attr, default=None):
62 """Determine boolean value of |node|'s |attr|.
63
64 Invalid values will issue a non-fatal warning.
65
66 Args:
67 node: XML node whose attributes we access.
68 attr: The attribute to access.
69 default: If the attribute is not set (value is empty), then use this.
70
71 Returns:
72 True if the attribute is a valid string representing true.
73 False if the attribute is a valid string representing false.
74 |default| otherwise.
75 """
76 value = node.getAttribute(attr)
77 s = value.lower()
78 if s == '':
79 return default
80 elif s in {'yes', 'true', '1'}:
81 return True
82 elif s in {'no', 'false', '0'}:
83 return False
84 else:
85 print('warning: manifest: %s="%s": ignoring invalid XML boolean' %
86 (attr, value), file=sys.stderr)
87 return default
88
89
90def XmlInt(node, attr, default=None):
91 """Determine integer value of |node|'s |attr|.
92
93 Args:
94 node: XML node whose attributes we access.
95 attr: The attribute to access.
96 default: If the attribute is not set (value is empty), then use this.
97
98 Returns:
99 The number if the attribute is a valid number.
100
101 Raises:
102 ManifestParseError: The number is invalid.
103 """
104 value = node.getAttribute(attr)
105 if not value:
106 return default
107
108 try:
109 return int(value)
110 except ValueError:
111 raise ManifestParseError('manifest: invalid %s="%s" integer' %
112 (attr, value))
113
114
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700115class _Default(object):
116 """Project defaults within the manifest."""
117
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700118 revisionExpr = None
Conley Owensb6a16e62013-09-25 15:06:09 -0700119 destBranchExpr = None
Nasser Grainawida403412018-05-04 12:53:29 -0600120 upstreamExpr = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700121 remote = None
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700122 sync_j = 1
Anatol Pomazau79770d22012-04-20 14:41:59 -0700123 sync_c = False
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800124 sync_s = False
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900125 sync_tags = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700126
Julien Campergue74879922013-10-09 14:38:46 +0200127 def __eq__(self, other):
Jack Neus5ba21202021-06-09 15:21:25 +0000128 if not isinstance(other, _Default):
129 return False
Julien Campergue74879922013-10-09 14:38:46 +0200130 return self.__dict__ == other.__dict__
131
132 def __ne__(self, other):
Jack Neus5ba21202021-06-09 15:21:25 +0000133 if not isinstance(other, _Default):
134 return True
Julien Campergue74879922013-10-09 14:38:46 +0200135 return self.__dict__ != other.__dict__
136
David Pursehouse819827a2020-02-12 15:20:19 +0900137
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700138class _XmlRemote(object):
139 def __init__(self,
140 name,
Yestin Sunb292b982012-07-02 07:32:50 -0700141 alias=None,
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700142 fetch=None,
Steve Raed6480452016-08-10 15:00:00 -0700143 pushUrl=None,
Conley Owensdb728cd2011-09-26 16:34:01 -0700144 manifestUrl=None,
Anthony King36ea2fb2014-05-06 11:54:01 +0100145 review=None,
Jonathan Nieder93719792015-03-17 11:29:58 -0700146 revision=None):
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700147 self.name = name
148 self.fetchUrl = fetch
Steve Raed6480452016-08-10 15:00:00 -0700149 self.pushUrl = pushUrl
Conley Owensdb728cd2011-09-26 16:34:01 -0700150 self.manifestUrl = manifestUrl
Yestin Sunb292b982012-07-02 07:32:50 -0700151 self.remoteAlias = alias
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700152 self.reviewUrl = review
Anthony King36ea2fb2014-05-06 11:54:01 +0100153 self.revision = revision
Conley Owensceea3682011-10-20 10:45:47 -0700154 self.resolvedFetchUrl = self._resolveFetchUrl()
Jack Neus6ea0cae2021-07-20 20:52:33 +0000155 self.annotations = []
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700156
David Pursehouse717ece92012-11-13 08:49:16 +0900157 def __eq__(self, other):
Jack Neus5ba21202021-06-09 15:21:25 +0000158 if not isinstance(other, _XmlRemote):
159 return False
Jack Neus6ea0cae2021-07-20 20:52:33 +0000160 return (sorted(self.annotations) == sorted(other.annotations) and
161 self.name == other.name and self.fetchUrl == other.fetchUrl and
162 self.pushUrl == other.pushUrl and self.remoteAlias == other.remoteAlias
163 and self.reviewUrl == other.reviewUrl and self.revision == other.revision)
David Pursehouse717ece92012-11-13 08:49:16 +0900164
165 def __ne__(self, other):
Jack Neus6ea0cae2021-07-20 20:52:33 +0000166 return not self.__eq__(other)
David Pursehouse717ece92012-11-13 08:49:16 +0900167
Conley Owensceea3682011-10-20 10:45:47 -0700168 def _resolveFetchUrl(self):
Jack Neus5ba21202021-06-09 15:21:25 +0000169 if self.fetchUrl is None:
170 return ''
Conley Owensceea3682011-10-20 10:45:47 -0700171 url = self.fetchUrl.rstrip('/')
Conley Owensdb728cd2011-09-26 16:34:01 -0700172 manifestUrl = self.manifestUrl.rstrip('/')
Conley Owens2d0f5082014-01-31 15:03:51 -0800173 # urljoin will gets confused over quite a few things. The ones we care
174 # about here are:
175 # * no scheme in the base url, like <hostname:port>
Anthony Kingcb07ba72015-03-28 23:26:04 +0000176 # We handle no scheme by replacing it with an obscure protocol, gopher
177 # and then replacing it with the original when we are done.
178
Conley Owensdb728cd2011-09-26 16:34:01 -0700179 if manifestUrl.find(':') != manifestUrl.find('/') - 1:
Conley Owens4ccad752015-04-29 10:45:37 -0700180 url = urllib.parse.urljoin('gopher://' + manifestUrl, url)
181 url = re.sub(r'^gopher://', '', url)
Anthony Kingcb07ba72015-03-28 23:26:04 +0000182 else:
183 url = urllib.parse.urljoin(manifestUrl, url)
Shawn Pearcea9f11b32013-01-02 15:40:48 -0800184 return url
Conley Owensceea3682011-10-20 10:45:47 -0700185
186 def ToRemoteSpec(self, projectName):
David Rileye0684ad2017-04-05 00:02:59 -0700187 fetchUrl = self.resolvedFetchUrl.rstrip('/')
188 url = fetchUrl + '/' + projectName
Yestin Sunb292b982012-07-02 07:32:50 -0700189 remoteName = self.name
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700190 if self.remoteAlias:
David Pursehouse37128b62013-10-15 10:48:40 +0900191 remoteName = self.remoteAlias
Dan Willemsen96c2d652016-04-06 16:03:54 -0700192 return RemoteSpec(remoteName,
193 url=url,
Steve Raed6480452016-08-10 15:00:00 -0700194 pushUrl=self.pushUrl,
Dan Willemsen96c2d652016-04-06 16:03:54 -0700195 review=self.reviewUrl,
David Rileye0684ad2017-04-05 00:02:59 -0700196 orig_name=self.name,
197 fetchUrl=self.fetchUrl)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700198
Jack Neus6ea0cae2021-07-20 20:52:33 +0000199 def AddAnnotation(self, name, value, keep):
200 self.annotations.append(Annotation(name, value, keep))
201
David Pursehouse819827a2020-02-12 15:20:19 +0900202
LaMont Jonescc879a92021-11-18 22:40:18 +0000203class _XmlSubmanifest:
204 """Manage the <submanifest> element specified in the manifest.
205
206 Attributes:
207 name: a string, the name for this submanifest.
208 remote: a string, the remote.name for this submanifest.
209 project: a string, the name of the manifest project.
210 revision: a string, the commitish.
211 manifestName: a string, the submanifest file name.
212 groups: a list of strings, the groups to add to all projects in the submanifest.
213 path: a string, the relative path for the submanifest checkout.
214 annotations: (derived) a list of annotations.
215 present: (derived) a boolean, whether the submanifest's manifest file is present.
216 """
217 def __init__(self,
218 name,
219 remote=None,
220 project=None,
221 revision=None,
222 manifestName=None,
223 groups=None,
224 path=None,
225 parent=None):
226 self.name = name
227 self.remote = remote
228 self.project = project
229 self.revision = revision
230 self.manifestName = manifestName
231 self.groups = groups
232 self.path = path
233 self.annotations = []
234 outer_client = parent._outer_client or parent
235 if self.remote and not self.project:
236 raise ManifestParseError(
237 f'Submanifest {name}: must specify project when remote is given.')
238 rc = self.repo_client = RepoClient(
239 parent.repodir, manifestName, parent_groups=','.join(groups) or '',
240 submanifest_path=self.relpath, outer_client=outer_client)
241
242 self.present = os.path.exists(os.path.join(self.repo_client.subdir,
243 MANIFEST_FILE_NAME))
244
245 def __eq__(self, other):
246 if not isinstance(other, _XmlSubmanifest):
247 return False
248 return (
249 self.name == other.name and
250 self.remote == other.remote and
251 self.project == other.project and
252 self.revision == other.revision and
253 self.manifestName == other.manifestName and
254 self.groups == other.groups and
255 self.path == other.path and
256 sorted(self.annotations) == sorted(other.annotations))
257
258 def __ne__(self, other):
259 return not self.__eq__(other)
260
261 def ToSubmanifestSpec(self, root):
262 """Return a SubmanifestSpec object, populating attributes"""
263 mp = root.manifestProject
264 remote = root.remotes[self.remote or root.default.remote.name]
265 # If a project was given, generate the url from the remote and project.
266 # If not, use this manifestProject's url.
267 if self.project:
268 manifestUrl = remote.ToRemoteSpec(self.project).url
269 else:
270 manifestUrl = mp.GetRemote(mp.remote.name).url
271 manifestName = self.manifestName or 'default.xml'
272 revision = self.revision or self.name
273 path = self.path or revision.split('/')[-1]
274 groups = self.groups or []
275
276 return SubmanifestSpec(self.name, manifestUrl, manifestName, revision, path,
277 groups)
278
279 @property
280 def relpath(self):
281 """The path of this submanifest relative to the parent manifest."""
282 revision = self.revision or self.name
283 return self.path or revision.split('/')[-1]
284
285 def GetGroupsStr(self):
286 """Returns the `groups` given for this submanifest."""
287 if self.groups:
288 return ','.join(self.groups)
289 return ''
290
291 def AddAnnotation(self, name, value, keep):
292 """Add annotations to the submanifest."""
293 self.annotations.append(Annotation(name, value, keep))
294
295
296class SubmanifestSpec:
297 """The submanifest element, with all fields expanded."""
298
299 def __init__(self,
300 name,
301 manifestUrl,
302 manifestName,
303 revision,
304 path,
305 groups):
306 self.name = name
307 self.manifestUrl = manifestUrl
308 self.manifestName = manifestName
309 self.revision = revision
310 self.path = path
311 self.groups = groups or []
312
313
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700314class XmlManifest(object):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700315 """manages the repo configuration file"""
316
LaMont Jonescc879a92021-11-18 22:40:18 +0000317 def __init__(self, repodir, manifest_file, local_manifests=None,
318 outer_client=None, parent_groups='', submanifest_path=''):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400319 """Initialize.
320
321 Args:
322 repodir: Path to the .repo/ dir for holding all internal checkout state.
323 It must be in the top directory of the repo client checkout.
324 manifest_file: Full path to the manifest file to parse. This will usually
325 be |repodir|/|MANIFEST_FILE_NAME|.
326 local_manifests: Full path to the directory of local override manifests.
327 This will usually be |repodir|/|LOCAL_MANIFESTS_DIR_NAME|.
LaMont Jonescc879a92021-11-18 22:40:18 +0000328 outer_client: RepoClient of the outertree.
329 parent_groups: a string, the groups to apply to this projects.
330 submanifest_path: The submanifest root relative to the repo root.
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400331 """
332 # TODO(vapier): Move this out of this class.
333 self.globalConfig = GitConfig.ForUser()
334
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700335 self.repodir = os.path.abspath(repodir)
LaMont Jonescc879a92021-11-18 22:40:18 +0000336 self._CheckLocalPath(submanifest_path)
337 self.topdir = os.path.join(os.path.dirname(self.repodir), submanifest_path)
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400338 self.manifestFile = manifest_file
339 self.local_manifests = local_manifests
Basil Gelloc7453502018-05-25 20:23:52 +0300340 self._load_local_manifests = True
LaMont Jonescc879a92021-11-18 22:40:18 +0000341 self.parent_groups = parent_groups
342
343 if outer_client and self.isGitcClient:
344 raise ManifestParseError('Multi-manifest is incompatible with `gitc-init`')
345
346 if submanifest_path and not outer_client:
347 # If passing a submanifest_path, there must be an outer_client.
348 raise ManifestParseError(f'Bad call to {self.__class__.__name__}')
349
350 # If self._outer_client is None, this is not a checkout that supports
351 # multi-tree.
352 self._outer_client = outer_client or self
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700353
354 self.repoProject = MetaProject(self, 'repo',
David Pursehouseabdf7502020-02-12 14:58:39 +0900355 gitdir=os.path.join(repodir, 'repo/.git'),
356 worktree=os.path.join(repodir, 'repo'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700357
LaMont Jonescc879a92021-11-18 22:40:18 +0000358 mp = self.SubmanifestProject(self.path_prefix)
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500359 self.manifestProject = mp
360
361 # This is a bit hacky, but we're in a chicken & egg situation: all the
362 # normal repo settings live in the manifestProject which we just setup
363 # above, so we couldn't easily query before that. We assume Project()
364 # init doesn't care if this changes afterwards.
Mike Frysingerd957ec62020-02-24 14:40:25 -0500365 if os.path.exists(mp.gitdir) and mp.config.GetBoolean('repo.worktree'):
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500366 mp.use_git_worktrees = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700367
368 self._Unload()
369
Basil Gelloc7453502018-05-25 20:23:52 +0300370 def Override(self, name, load_local_manifests=True):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700371 """Use a different manifest, just for the current instantiation.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700372 """
Basil Gelloc7453502018-05-25 20:23:52 +0300373 path = None
374
375 # Look for a manifest by path in the filesystem (including the cwd).
376 if not load_local_manifests:
377 local_path = os.path.abspath(name)
378 if os.path.isfile(local_path):
379 path = local_path
380
381 # Look for manifests by name from the manifests repo.
382 if path is None:
383 path = os.path.join(self.manifestProject.worktree, name)
384 if not os.path.isfile(path):
385 raise ManifestParseError('manifest %s not found' % name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700386
387 old = self.manifestFile
388 try:
Basil Gelloc7453502018-05-25 20:23:52 +0300389 self._load_local_manifests = load_local_manifests
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700390 self.manifestFile = path
391 self._Unload()
392 self._Load()
393 finally:
394 self.manifestFile = old
395
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700396 def Link(self, name):
397 """Update the repo metadata to use a different manifest.
398 """
399 self.Override(name)
400
Mike Frysingera269b1c2020-02-21 00:49:41 -0500401 # Old versions of repo would generate symlinks we need to clean up.
Mike Frysinger9d96f582021-09-28 11:27:24 -0400402 platform_utils.remove(self.manifestFile, missing_ok=True)
Mike Frysingera269b1c2020-02-21 00:49:41 -0500403 # This file is interpreted as if it existed inside the manifest repo.
404 # That allows us to use <include> with the relative file name.
405 with open(self.manifestFile, 'w') as fp:
406 fp.write("""<?xml version="1.0" encoding="UTF-8"?>
407<!--
408DO NOT EDIT THIS FILE! It is generated by repo and changes will be discarded.
409If you want to use a different manifest, use `repo init -m <file>` instead.
410
411If you want to customize your checkout by overriding manifest settings, use
412the local_manifests/ directory instead.
413
414For more information on repo manifests, check out:
415https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
416-->
417<manifest>
418 <include name="%s" />
419</manifest>
420""" % (name,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700421
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800422 def _RemoteToXml(self, r, doc, root):
423 e = doc.createElement('remote')
424 root.appendChild(e)
425 e.setAttribute('name', r.name)
426 e.setAttribute('fetch', r.fetchUrl)
Steve Raed6480452016-08-10 15:00:00 -0700427 if r.pushUrl is not None:
428 e.setAttribute('pushurl', r.pushUrl)
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700429 if r.remoteAlias is not None:
430 e.setAttribute('alias', r.remoteAlias)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800431 if r.reviewUrl is not None:
432 e.setAttribute('review', r.reviewUrl)
Anthony King36ea2fb2014-05-06 11:54:01 +0100433 if r.revision is not None:
434 e.setAttribute('revision', r.revision)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800435
Jack Neus6ea0cae2021-07-20 20:52:33 +0000436 for a in r.annotations:
437 if a.keep == 'true':
438 ae = doc.createElement('annotation')
439 ae.setAttribute('name', a.name)
440 ae.setAttribute('value', a.value)
441 e.appendChild(ae)
442
LaMont Jonescc879a92021-11-18 22:40:18 +0000443 def _SubmanifestToXml(self, r, doc, root):
444 """Generate XML <submanifest/> node."""
445 e = doc.createElement('submanifest')
446 root.appendChild(e)
447 e.setAttribute('name', r.name)
448 if r.remote is not None:
449 e.setAttribute('remote', r.remote)
450 if r.project is not None:
451 e.setAttribute('project', r.project)
452 if r.manifestName is not None:
453 e.setAttribute('manifest-name', r.manifestName)
454 if r.revision is not None:
455 e.setAttribute('revision', r.revision)
456 if r.path is not None:
457 e.setAttribute('path', r.path)
458 if r.groups:
459 e.setAttribute('groups', r.GetGroupsStr())
460
461 for a in r.annotations:
462 if a.keep == 'true':
463 ae = doc.createElement('annotation')
464 ae.setAttribute('name', a.name)
465 ae.setAttribute('value', a.value)
466 e.appendChild(ae)
467
Mike Frysinger51e39d52020-12-04 05:32:06 -0500468 def _ParseList(self, field):
469 """Parse fields that contain flattened lists.
470
471 These are whitespace & comma separated. Empty elements will be discarded.
472 """
473 return [x for x in re.split(r'[,\s]+', field) if x]
Josh Triplett884a3872014-06-12 14:57:29 -0700474
Mike Frysinger23411d32020-09-02 04:31:10 -0400475 def ToXml(self, peg_rev=False, peg_rev_upstream=True, peg_rev_dest_branch=True, groups=None):
476 """Return the current manifest XML."""
Colin Cross5acde752012-03-28 20:15:45 -0700477 mp = self.manifestProject
478
Dan Willemsen5ea32d12015-09-08 13:27:20 -0700479 if groups is None:
480 groups = mp.config.GetString('manifest.groups')
Matt Gumbel0c635bb2012-12-21 10:14:53 -0800481 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -0500482 groups = self._ParseList(groups)
Colin Cross5acde752012-03-28 20:15:45 -0700483
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800484 doc = xml.dom.minidom.Document()
485 root = doc.createElement('manifest')
LaMont Jonescc879a92021-11-18 22:40:18 +0000486 if self.is_submanifest:
487 root.setAttribute('path', self.path_prefix)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800488 doc.appendChild(root)
489
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700490 # Save out the notice. There's a little bit of work here to give it the
491 # right whitespace, which assumes that the notice is automatically indented
492 # by 4 by minidom.
493 if self.notice:
494 notice_element = root.appendChild(doc.createElement('notice'))
495 notice_lines = self.notice.splitlines()
David Pursehouse54a4e602020-02-12 14:31:05 +0900496 indented_notice = ('\n'.join(" " * 4 + line for line in notice_lines))[4:]
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700497 notice_element.appendChild(doc.createTextNode(indented_notice))
498
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800499 d = self.default
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800500
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530501 for r in sorted(self.remotes):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800502 self._RemoteToXml(self.remotes[r], doc, root)
503 if self.remotes:
504 root.appendChild(doc.createTextNode(''))
505
506 have_default = False
507 e = doc.createElement('default')
508 if d.remote:
509 have_default = True
510 e.setAttribute('remote', d.remote.name)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700511 if d.revisionExpr:
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800512 have_default = True
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700513 e.setAttribute('revision', d.revisionExpr)
Simon Ruggier7e59de22015-07-24 12:50:06 +0200514 if d.destBranchExpr:
515 have_default = True
516 e.setAttribute('dest-branch', d.destBranchExpr)
Nasser Grainawida403412018-05-04 12:53:29 -0600517 if d.upstreamExpr:
518 have_default = True
519 e.setAttribute('upstream', d.upstreamExpr)
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700520 if d.sync_j > 1:
521 have_default = True
522 e.setAttribute('sync-j', '%d' % d.sync_j)
Anatol Pomazau79770d22012-04-20 14:41:59 -0700523 if d.sync_c:
524 have_default = True
525 e.setAttribute('sync-c', 'true')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800526 if d.sync_s:
527 have_default = True
528 e.setAttribute('sync-s', 'true')
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900529 if not d.sync_tags:
530 have_default = True
531 e.setAttribute('sync-tags', 'false')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800532 if have_default:
533 root.appendChild(e)
534 root.appendChild(doc.createTextNode(''))
535
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700536 if self._manifest_server:
537 e = doc.createElement('manifest-server')
538 e.setAttribute('url', self._manifest_server)
539 root.appendChild(e)
540 root.appendChild(doc.createTextNode(''))
541
LaMont Jonescc879a92021-11-18 22:40:18 +0000542 for r in sorted(self.submanifests):
543 self._SubmanifestToXml(self.submanifests[r], doc, root)
544 if self.submanifests:
545 root.appendChild(doc.createTextNode(''))
546
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800547 def output_projects(parent, parent_node, projects):
David James8d201162013-10-11 17:03:19 -0700548 for project_name in projects:
549 for project in self._projects[project_name]:
550 output_project(parent, parent_node, project)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800551
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800552 def output_project(parent, parent_node, p):
Colin Cross5acde752012-03-28 20:15:45 -0700553 if not p.MatchesGroups(groups):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800554 return
555
556 name = p.name
557 relpath = p.relpath
558 if parent:
559 name = self._UnjoinName(parent.name, name)
560 relpath = self._UnjoinRelpath(parent.relpath, relpath)
Colin Cross5acde752012-03-28 20:15:45 -0700561
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800562 e = doc.createElement('project')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800563 parent_node.appendChild(e)
564 e.setAttribute('name', name)
565 if relpath != name:
566 e.setAttribute('path', relpath)
Conley Owensa17d7af2013-10-16 14:38:09 -0700567 remoteName = None
568 if d.remote:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700569 remoteName = d.remote.name
570 if not d.remote or p.remote.orig_name != remoteName:
571 remoteName = p.remote.orig_name
Anthony King36ea2fb2014-05-06 11:54:01 +0100572 e.setAttribute('remote', remoteName)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800573 if peg_rev:
574 if self.IsMirror:
Brian Harring14a66742012-09-28 20:21:57 -0700575 value = p.bare_git.rev_parse(p.revisionExpr + '^0')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800576 else:
Brian Harring14a66742012-09-28 20:21:57 -0700577 value = p.work_git.rev_parse(HEAD + '^0')
578 e.setAttribute('revision', value)
Conley Owens551dfec2015-07-10 14:54:54 -0700579 if peg_rev_upstream:
580 if p.upstream:
581 e.setAttribute('upstream', p.upstream)
582 elif value != p.revisionExpr:
583 # Only save the origin if the origin is not a sha1, and the default
584 # isn't our value
585 e.setAttribute('upstream', p.revisionExpr)
Sean McAllisteraf908cb2020-04-20 08:41:58 -0600586
587 if peg_rev_dest_branch:
588 if p.dest_branch:
589 e.setAttribute('dest-branch', p.dest_branch)
590 elif value != p.revisionExpr:
591 e.setAttribute('dest-branch', p.revisionExpr)
592
Anthony King36ea2fb2014-05-06 11:54:01 +0100593 else:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700594 revision = self.remotes[p.remote.orig_name].revision or d.revisionExpr
Anthony King36ea2fb2014-05-06 11:54:01 +0100595 if not revision or revision != p.revisionExpr:
596 e.setAttribute('revision', p.revisionExpr)
Raman Tennetib5c5a5e2021-02-06 09:44:15 -0800597 elif p.revisionId:
598 e.setAttribute('revision', p.revisionId)
Nasser Grainawida403412018-05-04 12:53:29 -0600599 if (p.upstream and (p.upstream != p.revisionExpr or
600 p.upstream != d.upstreamExpr)):
Mani Chandel7a91d512014-07-24 16:27:08 +0530601 e.setAttribute('upstream', p.upstream)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800602
Simon Ruggier7e59de22015-07-24 12:50:06 +0200603 if p.dest_branch and p.dest_branch != d.destBranchExpr:
604 e.setAttribute('dest-branch', p.dest_branch)
605
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800606 for c in p.copyfiles:
607 ce = doc.createElement('copyfile')
608 ce.setAttribute('src', c.src)
609 ce.setAttribute('dest', c.dest)
610 e.appendChild(ce)
611
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500612 for l in p.linkfiles:
613 le = doc.createElement('linkfile')
614 le.setAttribute('src', l.src)
615 le.setAttribute('dest', l.dest)
616 e.appendChild(le)
617
Conley Owensbb1b5f52012-08-13 13:11:18 -0700618 default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
Dmitry Fink17f85ea2012-08-06 14:52:29 -0700619 egroups = [g for g in p.groups if g not in default_groups]
Conley Owens971de8e2012-04-16 10:36:08 -0700620 if egroups:
621 e.setAttribute('groups', ','.join(egroups))
Colin Cross5acde752012-03-28 20:15:45 -0700622
James W. Mills24c13082012-04-12 15:04:13 -0500623 for a in p.annotations:
624 if a.keep == "true":
625 ae = doc.createElement('annotation')
626 ae.setAttribute('name', a.name)
627 ae.setAttribute('value', a.value)
628 e.appendChild(ae)
629
Anatol Pomazau79770d22012-04-20 14:41:59 -0700630 if p.sync_c:
631 e.setAttribute('sync-c', 'true')
632
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800633 if p.sync_s:
634 e.setAttribute('sync-s', 'true')
635
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900636 if not p.sync_tags:
637 e.setAttribute('sync-tags', 'false')
638
Dan Willemsen88409222015-08-17 15:29:10 -0700639 if p.clone_depth:
640 e.setAttribute('clone-depth', str(p.clone_depth))
641
Simran Basib9a1b732015-08-20 12:19:28 -0700642 self._output_manifest_project_extras(p, e)
643
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800644 if p.subprojects:
David James8d201162013-10-11 17:03:19 -0700645 subprojects = set(subp.name for subp in p.subprojects)
646 output_projects(p, e, list(sorted(subprojects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800647
David James8d201162013-10-11 17:03:19 -0700648 projects = set(p.name for p in self._paths.values() if not p.parent)
649 output_projects(None, root, list(sorted(projects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800650
Doug Anderson37282b42011-03-04 11:54:18 -0800651 if self._repo_hooks_project:
652 root.appendChild(doc.createTextNode(''))
653 e = doc.createElement('repo-hooks')
654 e.setAttribute('in-project', self._repo_hooks_project.name)
655 e.setAttribute('enabled-list',
656 ' '.join(self._repo_hooks_project.enabled_repo_hooks))
657 root.appendChild(e)
658
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800659 if self._superproject:
660 root.appendChild(doc.createTextNode(''))
661 e = doc.createElement('superproject')
662 e.setAttribute('name', self._superproject['name'])
663 remoteName = None
664 if d.remote:
665 remoteName = d.remote.name
666 remote = self._superproject.get('remote')
667 if not d.remote or remote.orig_name != remoteName:
668 remoteName = remote.orig_name
669 e.setAttribute('remote', remoteName)
Xin Lie0b16a22021-09-26 23:20:32 -0700670 revision = remote.revision or d.revisionExpr
671 if not revision or revision != self._superproject['revision']:
672 e.setAttribute('revision', self._superproject['revision'])
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800673 root.appendChild(e)
674
Raman Tenneti993af5e2021-05-12 12:00:31 -0700675 if self._contactinfo.bugurl != Wrapper().BUG_URL:
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700676 root.appendChild(doc.createTextNode(''))
677 e = doc.createElement('contactinfo')
Raman Tenneti993af5e2021-05-12 12:00:31 -0700678 e.setAttribute('bugurl', self._contactinfo.bugurl)
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700679 root.appendChild(e)
680
Mike Frysinger23411d32020-09-02 04:31:10 -0400681 return doc
682
683 def ToDict(self, **kwargs):
684 """Return the current manifest as a dictionary."""
685 # Elements that may only appear once.
686 SINGLE_ELEMENTS = {
687 'notice',
688 'default',
689 'manifest-server',
690 'repo-hooks',
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800691 'superproject',
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700692 'contactinfo',
Mike Frysinger23411d32020-09-02 04:31:10 -0400693 }
694 # Elements that may be repeated.
695 MULTI_ELEMENTS = {
696 'remote',
697 'remove-project',
698 'project',
699 'extend-project',
700 'include',
LaMont Jonescc879a92021-11-18 22:40:18 +0000701 'submanifest',
Mike Frysinger23411d32020-09-02 04:31:10 -0400702 # These are children of 'project' nodes.
703 'annotation',
704 'project',
705 'copyfile',
706 'linkfile',
707 }
708
709 doc = self.ToXml(**kwargs)
710 ret = {}
711
712 def append_children(ret, node):
713 for child in node.childNodes:
714 if child.nodeType == xml.dom.Node.ELEMENT_NODE:
715 attrs = child.attributes
716 element = dict((attrs.item(i).localName, attrs.item(i).value)
717 for i in range(attrs.length))
718 if child.nodeName in SINGLE_ELEMENTS:
719 ret[child.nodeName] = element
720 elif child.nodeName in MULTI_ELEMENTS:
721 ret.setdefault(child.nodeName, []).append(element)
722 else:
723 raise ManifestParseError('Unhandled element "%s"' % (child.nodeName,))
724
725 append_children(element, child)
726
727 append_children(ret, doc.firstChild)
728
729 return ret
730
731 def Save(self, fd, **kwargs):
732 """Write the current manifest out to the given file descriptor."""
733 doc = self.ToXml(**kwargs)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800734 doc.writexml(fd, '', ' ', '\n', 'UTF-8')
735
Simran Basib9a1b732015-08-20 12:19:28 -0700736 def _output_manifest_project_extras(self, p, e):
737 """Manifests can modify e if they support extra project attributes."""
Simran Basib9a1b732015-08-20 12:19:28 -0700738
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700739 @property
LaMont Jonescc879a92021-11-18 22:40:18 +0000740 def is_multimanifest(self):
741 """Whether this is a multimanifest checkout"""
742 return bool(self.outer_client.submanifests)
743
744 @property
745 def is_submanifest(self):
746 """Whether this manifest is a submanifest"""
747 return self._outer_client and self._outer_client != self
748
749 @property
750 def outer_client(self):
751 """The instance of the outermost manifest client"""
752 self._Load()
753 return self._outer_client
754
755 @property
756 def all_manifests(self):
757 """Generator yielding all (sub)manifests."""
758 self._Load()
759 outer = self._outer_client
760 yield outer
761 for tree in outer.all_children:
762 yield tree
763
764 @property
765 def all_children(self):
766 """Generator yielding all child submanifests."""
767 self._Load()
768 for child in self._submanifests.values():
769 if child.repo_client:
770 yield child.repo_client
771 for tree in child.repo_client.all_children:
772 yield tree
773
774 @property
775 def path_prefix(self):
776 """The path of this submanifest, relative to the outermost manifest."""
777 if not self._outer_client or self == self._outer_client:
778 return ''
779 return os.path.relpath(self.topdir, self._outer_client.topdir)
780
781 @property
782 def all_paths(self):
783 """All project paths for all (sub)manifests. See `paths`."""
784 ret = {}
785 for tree in self.all_manifests:
786 prefix = tree.path_prefix
787 ret.update({os.path.join(prefix, k): v for k, v in tree.paths.items()})
788 return ret
789
790 @property
791 def all_projects(self):
792 """All projects for all (sub)manifests. See `projects`."""
793 return list(itertools.chain.from_iterable(x._paths.values() for x in self.all_manifests))
794
795 @property
David James8d201162013-10-11 17:03:19 -0700796 def paths(self):
LaMont Jonescc879a92021-11-18 22:40:18 +0000797 """Return all paths for this manifest.
798
799 Return:
800 A dictionary of {path: Project()}. `path` is relative to this manifest.
801 """
David James8d201162013-10-11 17:03:19 -0700802 self._Load()
803 return self._paths
804
805 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700806 def projects(self):
LaMont Jonescc879a92021-11-18 22:40:18 +0000807 """Return a list of all Projects in this manifest."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700808 self._Load()
Anthony Kingd58bfe52014-05-05 23:30:49 +0100809 return list(self._paths.values())
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700810
811 @property
812 def remotes(self):
813 self._Load()
814 return self._remotes
815
816 @property
817 def default(self):
818 self._Load()
819 return self._default
820
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800821 @property
LaMont Jonescc879a92021-11-18 22:40:18 +0000822 def submanifests(self):
823 """All submanifests in this manifest."""
824 self._Load()
825 return self._submanifests
826
827 @property
Doug Anderson37282b42011-03-04 11:54:18 -0800828 def repo_hooks_project(self):
829 self._Load()
830 return self._repo_hooks_project
831
832 @property
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800833 def superproject(self):
834 self._Load()
835 return self._superproject
836
837 @property
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700838 def contactinfo(self):
839 self._Load()
840 return self._contactinfo
841
842 @property
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700843 def notice(self):
844 self._Load()
845 return self._notice
846
847 @property
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700848 def manifest_server(self):
849 self._Load()
Shawn O. Pearce34fb20f2011-11-30 13:41:02 -0800850 return self._manifest_server
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700851
852 @property
Xin Lid79a4bc2020-05-20 16:03:45 -0700853 def CloneBundle(self):
854 clone_bundle = self.manifestProject.config.GetBoolean('repo.clonebundle')
855 if clone_bundle is None:
856 return False if self.manifestProject.config.GetBoolean('repo.partialclone') else True
857 else:
858 return clone_bundle
859
860 @property
Xin Li745be2e2019-06-03 11:24:30 -0700861 def CloneFilter(self):
862 if self.manifestProject.config.GetBoolean('repo.partialclone'):
863 return self.manifestProject.config.GetString('repo.clonefilter')
864 return None
865
866 @property
Raman Tennetif32f2432021-04-12 20:57:25 -0700867 def PartialCloneExclude(self):
868 exclude = self.manifest.manifestProject.config.GetString(
869 'repo.partialcloneexclude') or ''
870 return set(x.strip() for x in exclude.split(','))
871
872 @property
Michael Kellyc34b91c2021-07-02 09:25:48 -0700873 def UseLocalManifests(self):
874 return self._load_local_manifests
875
876 def SetUseLocalManifests(self, value):
877 self._load_local_manifests = value
878
879 @property
Raman Tennetifeb28912021-05-02 19:47:29 -0700880 def HasLocalManifests(self):
881 return self._load_local_manifests and self.local_manifests
882
LaMont Jones87cce682022-02-14 17:48:31 +0000883 def IsFromLocalManifest(self, project):
LaMont Jonescc879a92021-11-18 22:40:18 +0000884 """Is the project from a local manifest?"""
LaMont Jones87cce682022-02-14 17:48:31 +0000885 return any(x.startswith(LOCAL_MANIFEST_GROUP_PREFIX)
886 for x in project.groups)
887
Raman Tennetifeb28912021-05-02 19:47:29 -0700888 @property
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800889 def IsMirror(self):
890 return self.manifestProject.config.GetBoolean('repo.mirror')
891
Julien Campergue335f5ef2013-10-16 11:02:35 +0200892 @property
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500893 def UseGitWorktrees(self):
894 return self.manifestProject.config.GetBoolean('repo.worktree')
895
896 @property
Julien Campergue335f5ef2013-10-16 11:02:35 +0200897 def IsArchive(self):
898 return self.manifestProject.config.GetBoolean('repo.archive')
899
Martin Kellye4e94d22017-03-21 16:05:12 -0700900 @property
901 def HasSubmodules(self):
902 return self.manifestProject.config.GetBoolean('repo.submodules')
903
XD Trol630876f2022-01-17 23:29:04 +0800904 @property
905 def EnableGitLfs(self):
906 return self.manifestProject.config.GetBoolean('repo.git-lfs')
907
LaMont Jonescc879a92021-11-18 22:40:18 +0000908 def FindManifestByPath(self, path):
909 """Returns the manifest containing path."""
910 path = os.path.abspath(path)
911 manifest = self._outer_client or self
912 old = None
913 while manifest._submanifests and manifest != old:
914 old = manifest
915 for name in manifest._submanifests:
916 tree = manifest._submanifests[name]
917 if path.startswith(tree.repo_client.manifest.topdir):
918 manifest = tree.repo_client
919 break
920 return manifest
921
922 @property
923 def subdir(self):
924 """Returns the path for per-submanifest objects for this manifest."""
925 return self.SubmanifestInfoDir(self.path_prefix)
926
927 def SubmanifestInfoDir(self, submanifest_path, object_path=''):
928 """Return the path to submanifest-specific info for a submanifest.
929
930 Return the full path of the directory in which to put per-manifest objects.
931
932 Args:
933 submanifest_path: a string, the path of the submanifest, relative to the
934 outermost topdir. If empty, then repodir is returned.
935 object_path: a string, relative path to append to the submanifest info
936 directory path.
937 """
938 if submanifest_path:
939 return os.path.join(self.repodir, SUBMANIFEST_DIR, submanifest_path,
940 object_path)
941 else:
942 return os.path.join(self.repodir, object_path)
943
944 def SubmanifestProject(self, submanifest_path):
945 """Return a manifestProject for a submanifest."""
946 subdir = self.SubmanifestInfoDir(submanifest_path)
947 mp = MetaProject(self, 'manifests',
948 gitdir=os.path.join(subdir, 'manifests.git'),
949 worktree=os.path.join(subdir, 'manifests'))
950 return mp
951
Raman Tenneti080877e2021-03-09 15:19:06 -0800952 def GetDefaultGroupsStr(self):
953 """Returns the default group string for the platform."""
954 return 'default,platform-' + platform.system().lower()
955
956 def GetGroupsStr(self):
957 """Returns the manifest group string that should be synced."""
958 groups = self.manifestProject.config.GetString('manifest.groups')
959 if not groups:
960 groups = self.GetDefaultGroupsStr()
961 return groups
962
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700963 def _Unload(self):
964 self._loaded = False
965 self._projects = {}
David James8d201162013-10-11 17:03:19 -0700966 self._paths = {}
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700967 self._remotes = {}
968 self._default = None
LaMont Jonescc879a92021-11-18 22:40:18 +0000969 self._submanifests = {}
Doug Anderson37282b42011-03-04 11:54:18 -0800970 self._repo_hooks_project = None
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800971 self._superproject = {}
Raman Tenneti993af5e2021-05-12 12:00:31 -0700972 self._contactinfo = ContactInfo(Wrapper().BUG_URL)
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700973 self._notice = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700974 self.branch = None
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700975 self._manifest_server = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700976
LaMont Jonescc879a92021-11-18 22:40:18 +0000977 def _Load(self, initial_client=None, submanifest_depth=0):
978 if submanifest_depth > MAX_SUBMANIFEST_DEPTH:
979 raise ManifestParseError('maximum submanifest depth %d exceeded.' %
980 MAX_SUBMANIFEST_DEPTH)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700981 if not self._loaded:
LaMont Jonescc879a92021-11-18 22:40:18 +0000982 if self._outer_client and self._outer_client != self:
983 # This will load all clients.
984 self._outer_client._Load(initial_client=self)
985
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800986 m = self.manifestProject
987 b = m.GetBranch(m.CurrentBranch).merge
Shawn O. Pearce21c5c342009-06-25 16:47:30 -0700988 if b is not None and b.startswith(R_HEADS):
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800989 b = b[len(R_HEADS):]
990 self.branch = b
991
LaMont Jonescc879a92021-11-18 22:40:18 +0000992 parent_groups = self.parent_groups
993
Mike Frysinger54133972021-03-01 21:38:08 -0500994 # The manifestFile was specified by the user which is why we allow include
995 # paths to point anywhere.
Colin Cross23acdd32012-04-21 00:33:54 -0700996 nodes = []
Mike Frysinger54133972021-03-01 21:38:08 -0500997 nodes.append(self._ParseManifestXml(
998 self.manifestFile, self.manifestProject.worktree,
LaMont Jonescc879a92021-11-18 22:40:18 +0000999 parent_groups=parent_groups, restrict_includes=False))
Shawn O. Pearce5cc66792008-10-23 16:19:27 -07001000
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001001 if self._load_local_manifests and self.local_manifests:
Basil Gelloc7453502018-05-25 20:23:52 +03001002 try:
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001003 for local_file in sorted(platform_utils.listdir(self.local_manifests)):
Basil Gelloc7453502018-05-25 20:23:52 +03001004 if local_file.endswith('.xml'):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001005 local = os.path.join(self.local_manifests, local_file)
Mike Frysinger54133972021-03-01 21:38:08 -05001006 # Since local manifests are entirely managed by the user, allow
1007 # them to point anywhere the user wants.
LaMont Jonescc879a92021-11-18 22:40:18 +00001008 local_group = f'{LOCAL_MANIFEST_GROUP_PREFIX}:{local_file[:-4]}'
Mike Frysinger54133972021-03-01 21:38:08 -05001009 nodes.append(self._ParseManifestXml(
LaMont Jonescc879a92021-11-18 22:40:18 +00001010 local, self.subdir,
1011 parent_groups=f'{local_group},{parent_groups}',
Raman Tenneti78f4dd32021-06-07 13:27:37 -07001012 restrict_includes=False))
Basil Gelloc7453502018-05-25 20:23:52 +03001013 except OSError:
1014 pass
David Pursehouse2d5a0df2012-11-13 02:50:36 +09001015
Joe Onorato26e24752013-01-11 12:35:53 -08001016 try:
1017 self._ParseManifest(nodes)
1018 except ManifestParseError as e:
1019 # There was a problem parsing, unload ourselves in case they catch
1020 # this error and try again later, we will show the correct error
1021 self._Unload()
1022 raise e
Shawn O. Pearce5cc66792008-10-23 16:19:27 -07001023
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001024 if self.IsMirror:
1025 self._AddMetaProjectMirror(self.repoProject)
1026 self._AddMetaProjectMirror(self.manifestProject)
1027
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001028 self._loaded = True
1029
LaMont Jonescc879a92021-11-18 22:40:18 +00001030 # Now that we have loaded this manifest, load any submanifest manifests
1031 # as well. We need to do this after self._loaded is set to avoid looping.
1032 if self._outer_client:
1033 for name in self._submanifests:
1034 tree = self._submanifests[name]
1035 spec = tree.ToSubmanifestSpec(self)
1036 present = os.path.exists(os.path.join(self.subdir, MANIFEST_FILE_NAME))
1037 if present and tree.present and not tree.repo_client:
1038 if initial_client and initial_client.topdir == self.topdir:
1039 tree.repo_client = self
1040 tree.present = present
1041 elif not os.path.exists(self.subdir):
1042 tree.present = False
1043 if tree.present:
1044 tree.repo_client._Load(initial_client=initial_client,
1045 submanifest_depth=submanifest_depth + 1)
1046
Mike Frysinger54133972021-03-01 21:38:08 -05001047 def _ParseManifestXml(self, path, include_root, parent_groups='',
1048 restrict_includes=True):
1049 """Parse a manifest XML and return the computed nodes.
1050
1051 Args:
1052 path: The XML file to read & parse.
1053 include_root: The path to interpret include "name"s relative to.
1054 parent_groups: The groups to apply to this projects.
1055 restrict_includes: Whether to constrain the "name" attribute of includes.
1056
1057 Returns:
1058 List of XML nodes.
1059 """
David Pursehousef7fc8a92012-11-13 04:00:28 +09001060 try:
1061 root = xml.dom.minidom.parse(path)
David Pursehouse2d5a0df2012-11-13 02:50:36 +09001062 except (OSError, xml.parsers.expat.ExpatError) as e:
David Pursehousef7fc8a92012-11-13 04:00:28 +09001063 raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
1064
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001065 if not root or not root.childNodes:
Brian Harring26448742011-04-28 05:04:41 -07001066 raise ManifestParseError("no root node in %s" % (path,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001067
Jooncheol Park34acdd22012-08-27 02:25:59 +09001068 for manifest in root.childNodes:
1069 if manifest.nodeName == 'manifest':
1070 break
1071 else:
Brian Harring26448742011-04-28 05:04:41 -07001072 raise ManifestParseError("no <manifest> in %s" % (path,))
1073
Colin Cross23acdd32012-04-21 00:33:54 -07001074 nodes = []
David Pursehouse65b0ba52018-06-24 16:21:51 +09001075 for node in manifest.childNodes:
David Pursehousec1b86a22012-11-14 11:36:51 +09001076 if node.nodeName == 'include':
1077 name = self._reqatt(node, 'name')
Mike Frysinger54133972021-03-01 21:38:08 -05001078 if restrict_includes:
1079 msg = self._CheckLocalPath(name)
1080 if msg:
1081 raise ManifestInvalidPathError(
1082 '<include> invalid "name": %s: %s' % (name, msg))
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001083 include_groups = ''
1084 if parent_groups:
1085 include_groups = parent_groups
1086 if node.hasAttribute('groups'):
1087 include_groups = node.getAttribute('groups') + ',' + include_groups
David Pursehousec1b86a22012-11-14 11:36:51 +09001088 fp = os.path.join(include_root, name)
1089 if not os.path.isfile(fp):
Mike Frysinger54133972021-03-01 21:38:08 -05001090 raise ManifestParseError("include [%s/]%s doesn't exist or isn't a file"
1091 % (include_root, name))
David Pursehousec1b86a22012-11-14 11:36:51 +09001092 try:
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001093 nodes.extend(self._ParseManifestXml(fp, include_root, include_groups))
David Pursehousec1b86a22012-11-14 11:36:51 +09001094 # should isolate this to the exact exception, but that's
1095 # tricky. actual parsing implementation may vary.
Mike Frysinger54133972021-03-01 21:38:08 -05001096 except (KeyboardInterrupt, RuntimeError, SystemExit, ManifestParseError):
David Pursehousec1b86a22012-11-14 11:36:51 +09001097 raise
1098 except Exception as e:
1099 raise ManifestParseError(
Mike Frysingerec558df2019-07-05 01:38:05 -04001100 "failed parsing included manifest %s: %s" % (name, e))
David Pursehousec1b86a22012-11-14 11:36:51 +09001101 else:
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001102 if parent_groups and node.nodeName == 'project':
1103 nodeGroups = parent_groups
1104 if node.hasAttribute('groups'):
1105 nodeGroups = node.getAttribute('groups') + ',' + nodeGroups
1106 node.setAttribute('groups', nodeGroups)
David Pursehousec1b86a22012-11-14 11:36:51 +09001107 nodes.append(node)
Colin Cross23acdd32012-04-21 00:33:54 -07001108 return nodes
Brian Harring26448742011-04-28 05:04:41 -07001109
Colin Cross23acdd32012-04-21 00:33:54 -07001110 def _ParseManifest(self, node_list):
1111 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001112 if node.nodeName == 'remote':
1113 remote = self._ParseRemote(node)
David Pursehouse717ece92012-11-13 08:49:16 +09001114 if remote:
1115 if remote.name in self._remotes:
1116 if remote != self._remotes[remote.name]:
1117 raise ManifestParseError(
1118 'remote %s already exists with different attributes' %
1119 (remote.name))
1120 else:
1121 self._remotes[remote.name] = remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001122
Colin Cross23acdd32012-04-21 00:33:54 -07001123 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001124 if node.nodeName == 'default':
Julien Campergue74879922013-10-09 14:38:46 +02001125 new_default = self._ParseDefault(node)
Jack Neusb8c84482021-06-15 14:28:30 +00001126 emptyDefault = not node.hasAttributes() and not node.hasChildNodes()
Julien Campergue74879922013-10-09 14:38:46 +02001127 if self._default is None:
1128 self._default = new_default
Jack Neusb8c84482021-06-15 14:28:30 +00001129 elif not emptyDefault and new_default != self._default:
David Pursehouse37128b62013-10-15 10:48:40 +09001130 raise ManifestParseError('duplicate default in %s' %
1131 (self.manifestFile))
Julien Campergue74879922013-10-09 14:38:46 +02001132
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001133 if self._default is None:
1134 self._default = _Default()
1135
LaMont Jonescc879a92021-11-18 22:40:18 +00001136 submanifest_paths = set()
1137 for node in itertools.chain(*node_list):
1138 if node.nodeName == 'submanifest':
1139 submanifest = self._ParseSubmanifest(node)
1140 if submanifest:
1141 if submanifest.name in self._submanifests:
1142 if submanifest != self._submanifests[submanifest.name]:
1143 raise ManifestParseError(
1144 'submanifest %s already exists with different attributes' %
1145 (submanifest.name))
1146 else:
1147 self._submanifests[submanifest.name] = submanifest
1148 submanifest_paths.add(submanifest.relpath)
1149
Colin Cross23acdd32012-04-21 00:33:54 -07001150 for node in itertools.chain(*node_list):
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001151 if node.nodeName == 'notice':
1152 if self._notice is not None:
Doug Anderson37282b42011-03-04 11:54:18 -08001153 raise ManifestParseError(
1154 'duplicate notice in %s' %
1155 (self.manifestFile))
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001156 self._notice = self._ParseNotice(node)
1157
Colin Cross23acdd32012-04-21 00:33:54 -07001158 for node in itertools.chain(*node_list):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001159 if node.nodeName == 'manifest-server':
1160 url = self._reqatt(node, 'url')
1161 if self._manifest_server is not None:
David Pursehousec1b86a22012-11-14 11:36:51 +09001162 raise ManifestParseError(
1163 'duplicate manifest-server in %s' %
1164 (self.manifestFile))
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001165 self._manifest_server = url
1166
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001167 def recursively_add_projects(project):
David James8d201162013-10-11 17:03:19 -07001168 projects = self._projects.setdefault(project.name, [])
1169 if project.relpath is None:
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001170 raise ManifestParseError(
David James8d201162013-10-11 17:03:19 -07001171 'missing path for %s in %s' %
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001172 (project.name, self.manifestFile))
David James8d201162013-10-11 17:03:19 -07001173 if project.relpath in self._paths:
1174 raise ManifestParseError(
1175 'duplicate path %s in %s' %
1176 (project.relpath, self.manifestFile))
LaMont Jonescc879a92021-11-18 22:40:18 +00001177 for tree in submanifest_paths:
1178 if project.relpath.startswith(tree):
1179 raise ManifestParseError(
1180 'project %s conflicts with submanifest path %s' %
1181 (project.relpath, tree))
David James8d201162013-10-11 17:03:19 -07001182 self._paths[project.relpath] = project
1183 projects.append(project)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001184 for subproject in project.subprojects:
1185 recursively_add_projects(subproject)
1186
Jack Neusa84f43a2021-09-21 22:23:55 +00001187 repo_hooks_project = None
1188 enabled_repo_hooks = None
Colin Cross23acdd32012-04-21 00:33:54 -07001189 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001190 if node.nodeName == 'project':
1191 project = self._ParseProject(node)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001192 recursively_add_projects(project)
Josh Triplett884a3872014-06-12 14:57:29 -07001193 if node.nodeName == 'extend-project':
1194 name = self._reqatt(node, 'name')
1195
1196 if name not in self._projects:
1197 raise ManifestParseError('extend-project element specifies non-existent '
1198 'project: %s' % name)
1199
1200 path = node.getAttribute('path')
Michael Kelly37c21c22020-06-13 02:10:40 -07001201 dest_path = node.getAttribute('dest-path')
Josh Triplett884a3872014-06-12 14:57:29 -07001202 groups = node.getAttribute('groups')
1203 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -05001204 groups = self._ParseList(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -07001205 revision = node.getAttribute('revision')
LaMont Jonescc879a92021-11-18 22:40:18 +00001206 remote_name = node.getAttribute('remote')
1207 if not remote_name:
1208 remote = self._default.remote
1209 else:
Kyunam Jobd0aae92020-02-04 11:38:53 +09001210 remote = self._get_remote(node)
Josh Triplett884a3872014-06-12 14:57:29 -07001211
Michael Kelly37c21c22020-06-13 02:10:40 -07001212 named_projects = self._projects[name]
1213 if dest_path and not path and len(named_projects) > 1:
1214 raise ManifestParseError('extend-project cannot use dest-path when '
1215 'matching multiple projects: %s' % name)
Josh Triplett884a3872014-06-12 14:57:29 -07001216 for p in self._projects[name]:
1217 if path and p.relpath != path:
1218 continue
1219 if groups:
1220 p.groups.extend(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -07001221 if revision:
Michael Kelly2f3c3312020-07-21 19:40:38 -07001222 p.SetRevision(revision)
1223
LaMont Jonescc879a92021-11-18 22:40:18 +00001224 if remote_name:
Kyunam Jobd0aae92020-02-04 11:38:53 +09001225 p.remote = remote.ToRemoteSpec(name)
Michael Kelly2f3c3312020-07-21 19:40:38 -07001226
Michael Kelly37c21c22020-06-13 02:10:40 -07001227 if dest_path:
1228 del self._paths[p.relpath]
LaMont Jonescc879a92021-11-18 22:40:18 +00001229 relpath, worktree, gitdir, objdir, _ = self.GetProjectPaths(
1230 name, dest_path, remote.name)
Michael Kelly37c21c22020-06-13 02:10:40 -07001231 p.UpdatePaths(relpath, worktree, gitdir, objdir)
1232 self._paths[p.relpath] = p
1233
Doug Anderson37282b42011-03-04 11:54:18 -08001234 if node.nodeName == 'repo-hooks':
Doug Anderson37282b42011-03-04 11:54:18 -08001235 # Only one project can be the hooks project
Jack Neusa84f43a2021-09-21 22:23:55 +00001236 if repo_hooks_project is not None:
Doug Anderson37282b42011-03-04 11:54:18 -08001237 raise ManifestParseError(
1238 'duplicate repo-hooks in %s' %
1239 (self.manifestFile))
1240
Jack Neusa84f43a2021-09-21 22:23:55 +00001241 # Get the name of the project and the (space-separated) list of enabled.
1242 repo_hooks_project = self._reqatt(node, 'in-project')
1243 enabled_repo_hooks = self._ParseList(self._reqatt(node, 'enabled-list'))
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001244 if node.nodeName == 'superproject':
1245 name = self._reqatt(node, 'name')
1246 # There can only be one superproject.
1247 if self._superproject.get('name'):
1248 raise ManifestParseError(
1249 'duplicate superproject in %s' %
1250 (self.manifestFile))
1251 self._superproject['name'] = name
1252 remote_name = node.getAttribute('remote')
1253 if not remote_name:
1254 remote = self._default.remote
1255 else:
1256 remote = self._get_remote(node)
1257 if remote is None:
1258 raise ManifestParseError("no remote for superproject %s within %s" %
1259 (name, self.manifestFile))
1260 self._superproject['remote'] = remote.ToRemoteSpec(name)
Xin Lie0b16a22021-09-26 23:20:32 -07001261 revision = node.getAttribute('revision') or remote.revision
1262 if not revision:
1263 revision = self._default.revisionExpr
1264 if not revision:
1265 raise ManifestParseError('no revision for superproject %s within %s' %
1266 (name, self.manifestFile))
1267 self._superproject['revision'] = revision
Raman Tenneti1c3f57e2021-05-04 12:32:13 -07001268 if node.nodeName == 'contactinfo':
1269 bugurl = self._reqatt(node, 'bugurl')
1270 # This element can be repeated, later entries will clobber earlier ones.
Raman Tenneti993af5e2021-05-12 12:00:31 -07001271 self._contactinfo = ContactInfo(bugurl)
1272
Colin Cross23acdd32012-04-21 00:33:54 -07001273 if node.nodeName == 'remove-project':
1274 name = self._reqatt(node, 'name')
David Jamesb8433df2014-01-30 10:11:17 -08001275
Michael Kelly06da9982021-06-30 01:58:28 -07001276 if name in self._projects:
1277 for p in self._projects[name]:
1278 del self._paths[p.relpath]
1279 del self._projects[name]
1280
1281 # If the manifest removes the hooks project, treat it as if it deleted
1282 # the repo-hooks element too.
Jack Neusa84f43a2021-09-21 22:23:55 +00001283 if repo_hooks_project == name:
1284 repo_hooks_project = None
Michael Kelly06da9982021-06-30 01:58:28 -07001285 elif not XmlBool(node, 'optional', False):
David Pursehousef9107482012-11-16 19:12:32 +09001286 raise ManifestParseError('remove-project element specifies non-existent '
1287 'project: %s' % name)
Colin Cross23acdd32012-04-21 00:33:54 -07001288
Jack Neusa84f43a2021-09-21 22:23:55 +00001289 # Store repo hooks project information.
1290 if repo_hooks_project:
1291 # Store a reference to the Project.
1292 try:
1293 repo_hooks_projects = self._projects[repo_hooks_project]
1294 except KeyError:
1295 raise ManifestParseError(
1296 'project %s not found for repo-hooks' %
1297 (repo_hooks_project))
1298
1299 if len(repo_hooks_projects) != 1:
1300 raise ManifestParseError(
1301 'internal error parsing repo-hooks in %s' %
1302 (self.manifestFile))
1303 self._repo_hooks_project = repo_hooks_projects[0]
1304 # Store the enabled hooks in the Project object.
1305 self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
1306
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001307 def _AddMetaProjectMirror(self, m):
1308 name = None
1309 m_url = m.GetRemote(m.remote.name).url
1310 if m_url.endswith('/.git'):
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301311 raise ManifestParseError('refusing to mirror %s' % m_url)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001312
1313 if self._default and self._default.remote:
Conley Owensceea3682011-10-20 10:45:47 -07001314 url = self._default.remote.resolvedFetchUrl
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001315 if not url.endswith('/'):
1316 url += '/'
1317 if m_url.startswith(url):
1318 remote = self._default.remote
1319 name = m_url[len(url):]
1320
1321 if name is None:
1322 s = m_url.rindex('/') + 1
Conley Owensdb728cd2011-09-26 16:34:01 -07001323 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Shawn O. Pearcef35b2d92012-08-02 11:46:22 -07001324 remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001325 name = m_url[s:]
1326
1327 if name.endswith('.git'):
1328 name = name[:-4]
1329
1330 if name not in self._projects:
1331 m.PreSync()
1332 gitdir = os.path.join(self.topdir, '%s.git' % name)
David Pursehousee5913ae2020-02-12 13:56:59 +09001333 project = Project(manifest=self,
1334 name=name,
1335 remote=remote.ToRemoteSpec(name),
1336 gitdir=gitdir,
1337 objdir=gitdir,
1338 worktree=None,
1339 relpath=name or None,
1340 revisionExpr=m.revisionExpr,
1341 revisionId=None)
David James8d201162013-10-11 17:03:19 -07001342 self._projects[project.name] = [project]
Kwanhong Leeccd218c2014-02-17 13:07:32 +09001343 self._paths[project.relpath] = project
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001344
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001345 def _ParseRemote(self, node):
1346 """
1347 reads a <remote> element from the manifest file
1348 """
1349 name = self._reqatt(node, 'name')
Yestin Sunb292b982012-07-02 07:32:50 -07001350 alias = node.getAttribute('alias')
1351 if alias == '':
1352 alias = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001353 fetch = self._reqatt(node, 'fetch')
Steve Raed6480452016-08-10 15:00:00 -07001354 pushUrl = node.getAttribute('pushurl')
1355 if pushUrl == '':
1356 pushUrl = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001357 review = node.getAttribute('review')
Shawn O. Pearceae6e0942008-11-06 10:25:35 -08001358 if review == '':
1359 review = None
Anthony King36ea2fb2014-05-06 11:54:01 +01001360 revision = node.getAttribute('revision')
1361 if revision == '':
1362 revision = None
Conley Owensdb728cd2011-09-26 16:34:01 -07001363 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Jack Neus6ea0cae2021-07-20 20:52:33 +00001364
1365 remote = _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
1366
1367 for n in node.childNodes:
1368 if n.nodeName == 'annotation':
1369 self._ParseAnnotation(remote, n)
1370
1371 return remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001372
1373 def _ParseDefault(self, node):
1374 """
1375 reads a <default> element from the manifest file
1376 """
1377 d = _Default()
1378 d.remote = self._get_remote(node)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001379 d.revisionExpr = node.getAttribute('revision')
1380 if d.revisionExpr == '':
1381 d.revisionExpr = None
Anatol Pomazau79770d22012-04-20 14:41:59 -07001382
Bryan Jacobsf609f912013-05-06 13:36:24 -04001383 d.destBranchExpr = node.getAttribute('dest-branch') or None
Nasser Grainawida403412018-05-04 12:53:29 -06001384 d.upstreamExpr = node.getAttribute('upstream') or None
Bryan Jacobsf609f912013-05-06 13:36:24 -04001385
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001386 d.sync_j = XmlInt(node, 'sync-j', 1)
1387 if d.sync_j <= 0:
1388 raise ManifestParseError('%s: sync-j must be greater than 0, not "%s"' %
1389 (self.manifestFile, d.sync_j))
Anatol Pomazau79770d22012-04-20 14:41:59 -07001390
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001391 d.sync_c = XmlBool(node, 'sync-c', False)
1392 d.sync_s = XmlBool(node, 'sync-s', False)
1393 d.sync_tags = XmlBool(node, 'sync-tags', True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001394 return d
1395
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001396 def _ParseNotice(self, node):
1397 """
1398 reads a <notice> element from the manifest file
1399
1400 The <notice> element is distinct from other tags in the XML in that the
1401 data is conveyed between the start and end tag (it's not an empty-element
1402 tag).
1403
1404 The white space (carriage returns, indentation) for the notice element is
1405 relevant and is parsed in a way that is based on how python docstrings work.
1406 In fact, the code is remarkably similar to here:
1407 http://www.python.org/dev/peps/pep-0257/
1408 """
1409 # Get the data out of the node...
1410 notice = node.childNodes[0].data
1411
1412 # Figure out minimum indentation, skipping the first line (the same line
1413 # as the <notice> tag)...
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301414 minIndent = sys.maxsize
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001415 lines = notice.splitlines()
1416 for line in lines[1:]:
1417 lstrippedLine = line.lstrip()
1418 if lstrippedLine:
1419 indent = len(line) - len(lstrippedLine)
1420 minIndent = min(indent, minIndent)
1421
1422 # Strip leading / trailing blank lines and also indentation.
1423 cleanLines = [lines[0].strip()]
1424 for line in lines[1:]:
1425 cleanLines.append(line[minIndent:].rstrip())
1426
1427 # Clear completely blank lines from front and back...
1428 while cleanLines and not cleanLines[0]:
1429 del cleanLines[0]
1430 while cleanLines and not cleanLines[-1]:
1431 del cleanLines[-1]
1432
1433 return '\n'.join(cleanLines)
1434
LaMont Jonescc879a92021-11-18 22:40:18 +00001435 def _ParseSubmanifest(self, node):
1436 """Reads a <submanifest> element from the manifest file."""
1437 name = self._reqatt(node, 'name')
1438 remote = node.getAttribute('remote')
1439 if remote == '':
1440 remote = None
1441 project = node.getAttribute('project')
1442 if project == '':
1443 project = None
1444 revision = node.getAttribute('revision')
1445 if revision == '':
1446 revision = None
1447 manifestName = node.getAttribute('manifest-name')
1448 if manifestName == '':
1449 manifestName = None
1450 groups = ''
1451 if node.hasAttribute('groups'):
1452 groups = node.getAttribute('groups')
1453 groups = self._ParseList(groups)
1454 path = node.getAttribute('path')
1455 if path == '':
1456 path = None
1457 if revision:
1458 msg = self._CheckLocalPath(revision.split('/')[-1])
1459 if msg:
1460 raise ManifestInvalidPathError(
1461 '<submanifest> invalid "revision": %s: %s' % (revision, msg))
1462 else:
1463 msg = self._CheckLocalPath(name)
1464 if msg:
1465 raise ManifestInvalidPathError(
1466 '<submanifest> invalid "name": %s: %s' % (name, msg))
1467 else:
1468 msg = self._CheckLocalPath(path)
1469 if msg:
1470 raise ManifestInvalidPathError(
1471 '<submanifest> invalid "path": %s: %s' % (path, msg))
1472
1473 submanifest = _XmlSubmanifest(name, remote, project, revision, manifestName,
1474 groups, path, self)
1475
1476 for n in node.childNodes:
1477 if n.nodeName == 'annotation':
1478 self._ParseAnnotation(submanifest, n)
1479
1480 return submanifest
1481
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001482 def _JoinName(self, parent_name, name):
1483 return os.path.join(parent_name, name)
1484
1485 def _UnjoinName(self, parent_name, name):
1486 return os.path.relpath(name, parent_name)
1487
David Pursehousee5913ae2020-02-12 13:56:59 +09001488 def _ParseProject(self, node, parent=None, **extra_proj_attrs):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001489 """
1490 reads a <project> element from the manifest file
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001491 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001492 name = self._reqatt(node, 'name')
Mike Frysingera29424e2021-02-25 21:53:49 -05001493 msg = self._CheckLocalPath(name, dir_ok=True)
1494 if msg:
1495 raise ManifestInvalidPathError(
1496 '<project> invalid "name": %s: %s' % (name, msg))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001497 if parent:
1498 name = self._JoinName(parent.name, name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001499
1500 remote = self._get_remote(node)
1501 if remote is None:
1502 remote = self._default.remote
1503 if remote is None:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301504 raise ManifestParseError("no remote for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001505 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001506
Anthony King36ea2fb2014-05-06 11:54:01 +01001507 revisionExpr = node.getAttribute('revision') or remote.revision
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001508 if not revisionExpr:
1509 revisionExpr = self._default.revisionExpr
1510 if not revisionExpr:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301511 raise ManifestParseError("no revision for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001512 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001513
1514 path = node.getAttribute('path')
1515 if not path:
1516 path = name
Mike Frysingera29424e2021-02-25 21:53:49 -05001517 else:
Mike Frysinger0458faa2021-03-10 23:35:44 -05001518 # NB: The "." project is handled specially in Project.Sync_LocalHalf.
1519 msg = self._CheckLocalPath(path, dir_ok=True, cwd_dot_ok=True)
Mike Frysingera29424e2021-02-25 21:53:49 -05001520 if msg:
1521 raise ManifestInvalidPathError(
1522 '<project> invalid "path": %s: %s' % (path, msg))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001523
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001524 rebase = XmlBool(node, 'rebase', True)
1525 sync_c = XmlBool(node, 'sync-c', False)
1526 sync_s = XmlBool(node, 'sync-s', self._default.sync_s)
1527 sync_tags = XmlBool(node, 'sync-tags', self._default.sync_tags)
Mike Pontillod3153822012-02-28 11:53:24 -08001528
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001529 clone_depth = XmlInt(node, 'clone-depth')
1530 if clone_depth is not None and clone_depth <= 0:
1531 raise ManifestParseError('%s: clone-depth must be greater than 0, not "%s"' %
1532 (self.manifestFile, clone_depth))
David Pursehouseede7f122012-11-27 22:25:30 +09001533
Bryan Jacobsf609f912013-05-06 13:36:24 -04001534 dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
1535
Nasser Grainawida403412018-05-04 12:53:29 -06001536 upstream = node.getAttribute('upstream') or self._default.upstreamExpr
Brian Harring14a66742012-09-28 20:21:57 -07001537
Conley Owens971de8e2012-04-16 10:36:08 -07001538 groups = ''
1539 if node.hasAttribute('groups'):
1540 groups = node.getAttribute('groups')
Mike Frysinger51e39d52020-12-04 05:32:06 -05001541 groups = self._ParseList(groups)
Brian Harring7da13142012-06-15 02:24:20 -07001542
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001543 if parent is None:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001544 relpath, worktree, gitdir, objdir, use_git_worktrees = \
LaMont Jonescc879a92021-11-18 22:40:18 +00001545 self.GetProjectPaths(name, path, remote.name)
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001546 else:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001547 use_git_worktrees = False
David James8d201162013-10-11 17:03:19 -07001548 relpath, worktree, gitdir, objdir = \
1549 self.GetSubprojectPaths(parent, name, path)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001550
1551 default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
1552 groups.extend(set(default_groups).difference(groups))
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001553
Scott Fandb83b1b2013-02-28 09:34:14 +08001554 if self.IsMirror and node.hasAttribute('force-path'):
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001555 if XmlBool(node, 'force-path', False):
Scott Fandb83b1b2013-02-28 09:34:14 +08001556 gitdir = os.path.join(self.topdir, '%s.git' % path)
1557
David Pursehousee5913ae2020-02-12 13:56:59 +09001558 project = Project(manifest=self,
1559 name=name,
1560 remote=remote.ToRemoteSpec(name),
1561 gitdir=gitdir,
1562 objdir=objdir,
1563 worktree=worktree,
1564 relpath=relpath,
1565 revisionExpr=revisionExpr,
1566 revisionId=None,
1567 rebase=rebase,
1568 groups=groups,
1569 sync_c=sync_c,
1570 sync_s=sync_s,
1571 sync_tags=sync_tags,
1572 clone_depth=clone_depth,
1573 upstream=upstream,
1574 parent=parent,
1575 dest_branch=dest_branch,
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001576 use_git_worktrees=use_git_worktrees,
Simran Basib9a1b732015-08-20 12:19:28 -07001577 **extra_proj_attrs)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001578
1579 for n in node.childNodes:
Shawn O. Pearce242b5262009-05-19 13:00:29 -07001580 if n.nodeName == 'copyfile':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001581 self._ParseCopyFile(project, n)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001582 if n.nodeName == 'linkfile':
1583 self._ParseLinkFile(project, n)
James W. Mills24c13082012-04-12 15:04:13 -05001584 if n.nodeName == 'annotation':
1585 self._ParseAnnotation(project, n)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001586 if n.nodeName == 'project':
David Pursehousee5913ae2020-02-12 13:56:59 +09001587 project.subprojects.append(self._ParseProject(n, parent=project))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001588
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001589 return project
1590
LaMont Jonescc879a92021-11-18 22:40:18 +00001591 def GetProjectPaths(self, name, path, remote):
1592 """Return the paths for a project.
1593
1594 Args:
1595 name: a string, the name of the project.
1596 path: a string, the path of the project.
1597 remote: a string, the remote.name of the project.
1598 """
Mike Frysingercebf2272020-05-26 01:02:29 -04001599 # The manifest entries might have trailing slashes. Normalize them to avoid
1600 # unexpected filesystem behavior since we do string concatenation below.
1601 path = path.rstrip('/')
1602 name = name.rstrip('/')
LaMont Jonescc879a92021-11-18 22:40:18 +00001603 remote = remote.rstrip('/')
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001604 use_git_worktrees = False
LaMont Jonescc879a92021-11-18 22:40:18 +00001605 use_remote_name = bool(self._outer_client._submanifests)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001606 relpath = path
1607 if self.IsMirror:
1608 worktree = None
1609 gitdir = os.path.join(self.topdir, '%s.git' % name)
David James8d201162013-10-11 17:03:19 -07001610 objdir = gitdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001611 else:
LaMont Jonescc879a92021-11-18 22:40:18 +00001612 if use_remote_name:
1613 namepath = os.path.join(remote, f'{name}.git')
1614 else:
1615 namepath = f'{name}.git'
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001616 worktree = os.path.join(self.topdir, path).replace('\\', '/')
LaMont Jonescc879a92021-11-18 22:40:18 +00001617 gitdir = os.path.join(self.subdir, 'projects', '%s.git' % path)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001618 # We allow people to mix git worktrees & non-git worktrees for now.
1619 # This allows for in situ migration of repo clients.
1620 if os.path.exists(gitdir) or not self.UseGitWorktrees:
LaMont Jonescc879a92021-11-18 22:40:18 +00001621 objdir = os.path.join(self.subdir, 'project-objects', namepath)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001622 else:
1623 use_git_worktrees = True
LaMont Jonescc879a92021-11-18 22:40:18 +00001624 gitdir = os.path.join(self.repodir, 'worktrees', namepath)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001625 objdir = gitdir
1626 return relpath, worktree, gitdir, objdir, use_git_worktrees
David James8d201162013-10-11 17:03:19 -07001627
LaMont Jonescc879a92021-11-18 22:40:18 +00001628 def GetProjectsWithName(self, name, all_manifests=False):
1629 """All projects with |name|.
1630
1631 Args:
1632 name: a string, the name of the project.
1633 all_manifests: a boolean, if True, then all manifests are searched. If
1634 False, then only this manifest is searched.
1635 """
1636 if all_manifests:
1637 return list(itertools.chain.from_iterable(
1638 x._projects.get(name, []) for x in self.all_manifests))
David James8d201162013-10-11 17:03:19 -07001639 return self._projects.get(name, [])
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001640
1641 def GetSubprojectName(self, parent, submodule_path):
1642 return os.path.join(parent.name, submodule_path)
1643
1644 def _JoinRelpath(self, parent_relpath, relpath):
1645 return os.path.join(parent_relpath, relpath)
1646
1647 def _UnjoinRelpath(self, parent_relpath, relpath):
1648 return os.path.relpath(relpath, parent_relpath)
1649
David James8d201162013-10-11 17:03:19 -07001650 def GetSubprojectPaths(self, parent, name, path):
Mike Frysingercebf2272020-05-26 01:02:29 -04001651 # The manifest entries might have trailing slashes. Normalize them to avoid
1652 # unexpected filesystem behavior since we do string concatenation below.
1653 path = path.rstrip('/')
1654 name = name.rstrip('/')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001655 relpath = self._JoinRelpath(parent.relpath, path)
1656 gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
David James8d201162013-10-11 17:03:19 -07001657 objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001658 if self.IsMirror:
1659 worktree = None
1660 else:
1661 worktree = os.path.join(parent.worktree, path).replace('\\', '/')
David James8d201162013-10-11 17:03:19 -07001662 return relpath, worktree, gitdir, objdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001663
Mike Frysinger04122b72019-07-31 23:32:58 -04001664 @staticmethod
Mike Frysingera00c5f42021-02-25 18:26:31 -05001665 def _CheckLocalPath(path, dir_ok=False, cwd_dot_ok=False):
1666 """Verify |path| is reasonable for use in filesystem paths.
1667
Mike Frysingera29424e2021-02-25 21:53:49 -05001668 Used with <copyfile> & <linkfile> & <project> elements.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001669
1670 This only validates the |path| in isolation: it does not check against the
1671 current filesystem state. Thus it is suitable as a first-past in a parser.
1672
1673 It enforces a number of constraints:
1674 * No empty paths.
1675 * No "~" in paths.
1676 * No Unicode codepoints that filesystems might elide when normalizing.
1677 * No relative path components like "." or "..".
1678 * No absolute paths.
1679 * No ".git" or ".repo*" path components.
1680
1681 Args:
1682 path: The path name to validate.
1683 dir_ok: Whether |path| may force a directory (e.g. end in a /).
1684 cwd_dot_ok: Whether |path| may be just ".".
1685
1686 Returns:
1687 None if |path| is OK, a failure message otherwise.
1688 """
1689 if not path:
1690 return 'empty paths not allowed'
1691
Mike Frysinger04122b72019-07-31 23:32:58 -04001692 if '~' in path:
1693 return '~ not allowed (due to 8.3 filenames on Windows filesystems)'
1694
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001695 path_codepoints = set(path)
1696
Mike Frysinger04122b72019-07-31 23:32:58 -04001697 # Some filesystems (like Apple's HFS+) try to normalize Unicode codepoints
1698 # which means there are alternative names for ".git". Reject paths with
1699 # these in it as there shouldn't be any reasonable need for them here.
1700 # The set of codepoints here was cribbed from jgit's implementation:
1701 # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
1702 BAD_CODEPOINTS = {
1703 u'\u200C', # ZERO WIDTH NON-JOINER
1704 u'\u200D', # ZERO WIDTH JOINER
1705 u'\u200E', # LEFT-TO-RIGHT MARK
1706 u'\u200F', # RIGHT-TO-LEFT MARK
1707 u'\u202A', # LEFT-TO-RIGHT EMBEDDING
1708 u'\u202B', # RIGHT-TO-LEFT EMBEDDING
1709 u'\u202C', # POP DIRECTIONAL FORMATTING
1710 u'\u202D', # LEFT-TO-RIGHT OVERRIDE
1711 u'\u202E', # RIGHT-TO-LEFT OVERRIDE
1712 u'\u206A', # INHIBIT SYMMETRIC SWAPPING
1713 u'\u206B', # ACTIVATE SYMMETRIC SWAPPING
1714 u'\u206C', # INHIBIT ARABIC FORM SHAPING
1715 u'\u206D', # ACTIVATE ARABIC FORM SHAPING
1716 u'\u206E', # NATIONAL DIGIT SHAPES
1717 u'\u206F', # NOMINAL DIGIT SHAPES
1718 u'\uFEFF', # ZERO WIDTH NO-BREAK SPACE
1719 }
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001720 if BAD_CODEPOINTS & path_codepoints:
Mike Frysinger04122b72019-07-31 23:32:58 -04001721 # This message is more expansive than reality, but should be fine.
1722 return 'Unicode combining characters not allowed'
1723
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001724 # Reject newlines as there shouldn't be any legitmate use for them, they'll
1725 # be confusing to users, and they can easily break tools that expect to be
1726 # able to iterate over newline delimited lists. This even applies to our
1727 # own code like .repo/project.list.
1728 if {'\r', '\n'} & path_codepoints:
1729 return 'Newlines not allowed'
1730
Mike Frysinger04122b72019-07-31 23:32:58 -04001731 # Assume paths might be used on case-insensitive filesystems.
1732 path = path.lower()
1733
Mike Frysingerd9254592020-02-19 22:36:26 -05001734 # Split up the path by its components. We can't use os.path.sep exclusively
1735 # as some platforms (like Windows) will convert / to \ and that bypasses all
1736 # our constructed logic here. Especially since manifest authors only use
1737 # / in their paths.
1738 resep = re.compile(r'[/%s]' % re.escape(os.path.sep))
Mike Frysinger0458faa2021-03-10 23:35:44 -05001739 # Strip off trailing slashes as those only produce '' elements, and we use
1740 # parts to look for individual bad components.
1741 parts = resep.split(path.rstrip('/'))
Mike Frysingerd9254592020-02-19 22:36:26 -05001742
Mike Frysingerae625412020-02-10 17:10:03 -05001743 # Some people use src="." to create stable links to projects. Lets allow
1744 # that but reject all other uses of "." to keep things simple.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001745 if not cwd_dot_ok or parts != ['.']:
Mike Frysingerae625412020-02-10 17:10:03 -05001746 for part in set(parts):
1747 if part in {'.', '..', '.git'} or part.startswith('.repo'):
1748 return 'bad component: %s' % (part,)
Mike Frysinger04122b72019-07-31 23:32:58 -04001749
Mike Frysingera00c5f42021-02-25 18:26:31 -05001750 if not dir_ok and resep.match(path[-1]):
Mike Frysinger04122b72019-07-31 23:32:58 -04001751 return 'dirs not allowed'
1752
Mike Frysingerd9254592020-02-19 22:36:26 -05001753 # NB: The two abspath checks here are to handle platforms with multiple
1754 # filesystem path styles (e.g. Windows).
Mike Frysinger04122b72019-07-31 23:32:58 -04001755 norm = os.path.normpath(path)
Mike Frysingerd9254592020-02-19 22:36:26 -05001756 if (norm == '..' or
1757 (len(norm) >= 3 and norm.startswith('..') and resep.match(norm[0])) or
1758 os.path.isabs(norm) or
1759 norm.startswith('/')):
Mike Frysinger04122b72019-07-31 23:32:58 -04001760 return 'path cannot be outside'
1761
1762 @classmethod
1763 def _ValidateFilePaths(cls, element, src, dest):
1764 """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
1765
1766 We verify the path independent of any filesystem state as we won't have a
1767 checkout available to compare to. i.e. This is for parsing validation
1768 purposes only.
1769
1770 We'll do full/live sanity checking before we do the actual filesystem
1771 modifications in _CopyFile/_LinkFile/etc...
1772 """
1773 # |dest| is the file we write to or symlink we create.
1774 # It is relative to the top of the repo client checkout.
1775 msg = cls._CheckLocalPath(dest)
1776 if msg:
1777 raise ManifestInvalidPathError(
1778 '<%s> invalid "dest": %s: %s' % (element, dest, msg))
1779
1780 # |src| is the file we read from or path we point to for symlinks.
1781 # It is relative to the top of the git project checkout.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001782 is_linkfile = element == 'linkfile'
1783 msg = cls._CheckLocalPath(src, dir_ok=is_linkfile, cwd_dot_ok=is_linkfile)
Mike Frysinger04122b72019-07-31 23:32:58 -04001784 if msg:
1785 raise ManifestInvalidPathError(
1786 '<%s> invalid "src": %s: %s' % (element, src, msg))
1787
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001788 def _ParseCopyFile(self, project, node):
1789 src = self._reqatt(node, 'src')
1790 dest = self._reqatt(node, 'dest')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001791 if not self.IsMirror:
1792 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001793 # dest is relative to the top of the tree.
1794 # We only validate paths if we actually plan to process them.
1795 self._ValidateFilePaths('copyfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001796 project.AddCopyFile(src, dest, self.topdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001797
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001798 def _ParseLinkFile(self, project, node):
1799 src = self._reqatt(node, 'src')
1800 dest = self._reqatt(node, 'dest')
1801 if not self.IsMirror:
1802 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001803 # dest is relative to the top of the tree.
1804 # We only validate paths if we actually plan to process them.
1805 self._ValidateFilePaths('linkfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001806 project.AddLinkFile(src, dest, self.topdir)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001807
Jack Neus6ea0cae2021-07-20 20:52:33 +00001808 def _ParseAnnotation(self, element, node):
James W. Mills24c13082012-04-12 15:04:13 -05001809 name = self._reqatt(node, 'name')
1810 value = self._reqatt(node, 'value')
1811 try:
1812 keep = self._reqatt(node, 'keep').lower()
1813 except ManifestParseError:
1814 keep = "true"
1815 if keep != "true" and keep != "false":
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301816 raise ManifestParseError('optional "keep" attribute must be '
David Pursehouseabdf7502020-02-12 14:58:39 +09001817 '"true" or "false"')
Jack Neus6ea0cae2021-07-20 20:52:33 +00001818 element.AddAnnotation(name, value, keep)
James W. Mills24c13082012-04-12 15:04:13 -05001819
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001820 def _get_remote(self, node):
1821 name = node.getAttribute('remote')
1822 if not name:
1823 return None
1824
1825 v = self._remotes.get(name)
1826 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301827 raise ManifestParseError("remote %s not defined in %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001828 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001829 return v
1830
1831 def _reqatt(self, node, attname):
1832 """
1833 reads a required attribute from the node.
1834 """
1835 v = node.getAttribute(attname)
1836 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301837 raise ManifestParseError("no %s in <%s> within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001838 (attname, node.nodeName, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001839 return v
Julien Camperguedd654222014-01-09 16:21:37 +01001840
1841 def projectsDiff(self, manifest):
1842 """return the projects differences between two manifests.
1843
1844 The diff will be from self to given manifest.
1845
1846 """
1847 fromProjects = self.paths
1848 toProjects = manifest.paths
1849
Anthony King7446c592014-05-06 09:19:39 +01001850 fromKeys = sorted(fromProjects.keys())
1851 toKeys = sorted(toProjects.keys())
Julien Camperguedd654222014-01-09 16:21:37 +01001852
1853 diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
1854
1855 for proj in fromKeys:
David Pursehouseeeff3532020-02-12 11:24:10 +09001856 if proj not in toKeys:
Julien Camperguedd654222014-01-09 16:21:37 +01001857 diff['removed'].append(fromProjects[proj])
1858 else:
1859 fromProj = fromProjects[proj]
1860 toProj = toProjects[proj]
1861 try:
1862 fromRevId = fromProj.GetCommitRevisionId()
1863 toRevId = toProj.GetCommitRevisionId()
1864 except ManifestInvalidRevisionError:
1865 diff['unreachable'].append((fromProj, toProj))
1866 else:
1867 if fromRevId != toRevId:
1868 diff['changed'].append((fromProj, toProj))
1869 toKeys.remove(proj)
1870
1871 for proj in toKeys:
1872 diff['added'].append(toProjects[proj])
1873
1874 return diff
Simran Basib9a1b732015-08-20 12:19:28 -07001875
1876
1877class GitcManifest(XmlManifest):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001878 """Parser for GitC (git-in-the-cloud) manifests."""
Simran Basib9a1b732015-08-20 12:19:28 -07001879
David Pursehousee5913ae2020-02-12 13:56:59 +09001880 def _ParseProject(self, node, parent=None):
Simran Basib9a1b732015-08-20 12:19:28 -07001881 """Override _ParseProject and add support for GITC specific attributes."""
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001882 return super()._ParseProject(
Simran Basib9a1b732015-08-20 12:19:28 -07001883 node, parent=parent, old_revision=node.getAttribute('old-revision'))
1884
1885 def _output_manifest_project_extras(self, p, e):
1886 """Output GITC Specific Project attributes"""
1887 if p.old_revision:
Stefan Beller66851062016-06-17 16:40:08 -07001888 e.setAttribute('old-revision', str(p.old_revision))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001889
1890
1891class RepoClient(XmlManifest):
1892 """Manages a repo client checkout."""
1893
LaMont Jonescc879a92021-11-18 22:40:18 +00001894 def __init__(self, repodir, manifest_file=None, submanifest_path='', **kwargs):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001895 self.isGitcClient = False
LaMont Jonescc879a92021-11-18 22:40:18 +00001896 submanifest_path = submanifest_path or ''
1897 if submanifest_path:
1898 self._CheckLocalPath(submanifest_path)
1899 prefix = os.path.join(repodir, SUBMANIFEST_DIR, submanifest_path)
1900 else:
1901 prefix = repodir
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001902
LaMont Jonescc879a92021-11-18 22:40:18 +00001903 if os.path.exists(os.path.join(prefix, LOCAL_MANIFEST_NAME)):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001904 print('error: %s is not supported; put local manifests in `%s` instead' %
LaMont Jonescc879a92021-11-18 22:40:18 +00001905 (LOCAL_MANIFEST_NAME, os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME)),
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001906 file=sys.stderr)
1907 sys.exit(1)
1908
1909 if manifest_file is None:
LaMont Jonescc879a92021-11-18 22:40:18 +00001910 manifest_file = os.path.join(prefix, MANIFEST_FILE_NAME)
1911 local_manifests = os.path.abspath(os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME))
1912 super().__init__(repodir, manifest_file, local_manifests,
1913 submanifest_path=submanifest_path, **kwargs)
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001914
1915 # TODO: Completely separate manifest logic out of the client.
1916 self.manifest = self
1917
1918
1919class GitcClient(RepoClient, GitcManifest):
1920 """Manages a GitC client checkout."""
1921
1922 def __init__(self, repodir, gitc_client_name):
1923 """Initialize the GitcManifest object."""
1924 self.gitc_client_name = gitc_client_name
1925 self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
1926 gitc_client_name)
1927
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001928 super().__init__(repodir, os.path.join(self.gitc_client_dir, '.manifest'))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001929 self.isGitcClient = True