blob: 3c43295e356f2feacc2fdca41689594e038261b5 [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
LaMont Jonesd56e2eb2022-04-07 18:14:46 +000027from git_superproject import Superproject
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070028import platform_utils
LaMont Jones9b72cf22022-03-29 21:54:22 +000029from project import (Annotation, RemoteSpec, Project, RepoProject,
30 ManifestProject)
Mike Frysinger04122b72019-07-31 23:32:58 -040031from error import (ManifestParseError, ManifestInvalidPathError,
32 ManifestInvalidRevisionError)
Raman Tenneti993af5e2021-05-12 12:00:31 -070033from wrapper import Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070034
35MANIFEST_FILE_NAME = 'manifest.xml'
Shawn O. Pearce5cc66792008-10-23 16:19:27 -070036LOCAL_MANIFEST_NAME = 'local_manifest.xml'
David Pursehouse2d5a0df2012-11-13 02:50:36 +090037LOCAL_MANIFESTS_DIR_NAME = 'local_manifests'
LaMont Jonescc879a92021-11-18 22:40:18 +000038SUBMANIFEST_DIR = 'submanifests'
39# Limit submanifests to an arbitrary depth for loop detection.
40MAX_SUBMANIFEST_DEPTH = 8
LaMont Jonesb308db12022-02-25 17:05:21 +000041# Add all projects from sub manifest into a group.
42SUBMANIFEST_GROUP_PREFIX = 'submanifest:'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070043
Raman Tenneti78f4dd32021-06-07 13:27:37 -070044# Add all projects from local manifest into a group.
45LOCAL_MANIFEST_GROUP_PREFIX = 'local:'
46
Raman Tenneti993af5e2021-05-12 12:00:31 -070047# ContactInfo has the self-registered bug url, supplied by the manifest authors.
48ContactInfo = collections.namedtuple('ContactInfo', 'bugurl')
49
Anthony Kingcb07ba72015-03-28 23:26:04 +000050# urljoin gets confused if the scheme is not known.
Joe Kilner6e310792016-10-27 15:53:53 -070051urllib.parse.uses_relative.extend([
52 'ssh',
53 'git',
54 'persistent-https',
55 'sso',
56 'rpc'])
57urllib.parse.uses_netloc.extend([
58 'ssh',
59 'git',
60 'persistent-https',
61 'sso',
62 'rpc'])
Conley Owensdb728cd2011-09-26 16:34:01 -070063
David Pursehouse819827a2020-02-12 15:20:19 +090064
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050065def XmlBool(node, attr, default=None):
66 """Determine boolean value of |node|'s |attr|.
67
68 Invalid values will issue a non-fatal warning.
69
70 Args:
71 node: XML node whose attributes we access.
72 attr: The attribute to access.
73 default: If the attribute is not set (value is empty), then use this.
74
75 Returns:
76 True if the attribute is a valid string representing true.
77 False if the attribute is a valid string representing false.
78 |default| otherwise.
79 """
80 value = node.getAttribute(attr)
81 s = value.lower()
82 if s == '':
83 return default
84 elif s in {'yes', 'true', '1'}:
85 return True
86 elif s in {'no', 'false', '0'}:
87 return False
88 else:
89 print('warning: manifest: %s="%s": ignoring invalid XML boolean' %
90 (attr, value), file=sys.stderr)
91 return default
92
93
94def XmlInt(node, attr, default=None):
95 """Determine integer value of |node|'s |attr|.
96
97 Args:
98 node: XML node whose attributes we access.
99 attr: The attribute to access.
100 default: If the attribute is not set (value is empty), then use this.
101
102 Returns:
103 The number if the attribute is a valid number.
104
105 Raises:
106 ManifestParseError: The number is invalid.
107 """
108 value = node.getAttribute(attr)
109 if not value:
110 return default
111
112 try:
113 return int(value)
114 except ValueError:
115 raise ManifestParseError('manifest: invalid %s="%s" integer' %
116 (attr, value))
117
118
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700119class _Default(object):
120 """Project defaults within the manifest."""
121
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700122 revisionExpr = None
Conley Owensb6a16e62013-09-25 15:06:09 -0700123 destBranchExpr = None
Nasser Grainawida403412018-05-04 12:53:29 -0600124 upstreamExpr = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700125 remote = None
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700126 sync_j = 1
Anatol Pomazau79770d22012-04-20 14:41:59 -0700127 sync_c = False
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800128 sync_s = False
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900129 sync_tags = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700130
Julien Campergue74879922013-10-09 14:38:46 +0200131 def __eq__(self, other):
Jack Neus5ba21202021-06-09 15:21:25 +0000132 if not isinstance(other, _Default):
133 return False
Julien Campergue74879922013-10-09 14:38:46 +0200134 return self.__dict__ == other.__dict__
135
136 def __ne__(self, other):
Jack Neus5ba21202021-06-09 15:21:25 +0000137 if not isinstance(other, _Default):
138 return True
Julien Campergue74879922013-10-09 14:38:46 +0200139 return self.__dict__ != other.__dict__
140
David Pursehouse819827a2020-02-12 15:20:19 +0900141
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700142class _XmlRemote(object):
143 def __init__(self,
144 name,
Yestin Sunb292b982012-07-02 07:32:50 -0700145 alias=None,
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700146 fetch=None,
Steve Raed6480452016-08-10 15:00:00 -0700147 pushUrl=None,
Conley Owensdb728cd2011-09-26 16:34:01 -0700148 manifestUrl=None,
Anthony King36ea2fb2014-05-06 11:54:01 +0100149 review=None,
Jonathan Nieder93719792015-03-17 11:29:58 -0700150 revision=None):
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700151 self.name = name
152 self.fetchUrl = fetch
Steve Raed6480452016-08-10 15:00:00 -0700153 self.pushUrl = pushUrl
Conley Owensdb728cd2011-09-26 16:34:01 -0700154 self.manifestUrl = manifestUrl
Yestin Sunb292b982012-07-02 07:32:50 -0700155 self.remoteAlias = alias
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700156 self.reviewUrl = review
Anthony King36ea2fb2014-05-06 11:54:01 +0100157 self.revision = revision
Conley Owensceea3682011-10-20 10:45:47 -0700158 self.resolvedFetchUrl = self._resolveFetchUrl()
Jack Neus6ea0cae2021-07-20 20:52:33 +0000159 self.annotations = []
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700160
David Pursehouse717ece92012-11-13 08:49:16 +0900161 def __eq__(self, other):
Jack Neus5ba21202021-06-09 15:21:25 +0000162 if not isinstance(other, _XmlRemote):
163 return False
Jack Neus6ea0cae2021-07-20 20:52:33 +0000164 return (sorted(self.annotations) == sorted(other.annotations) and
165 self.name == other.name and self.fetchUrl == other.fetchUrl and
166 self.pushUrl == other.pushUrl and self.remoteAlias == other.remoteAlias
167 and self.reviewUrl == other.reviewUrl and self.revision == other.revision)
David Pursehouse717ece92012-11-13 08:49:16 +0900168
169 def __ne__(self, other):
Jack Neus6ea0cae2021-07-20 20:52:33 +0000170 return not self.__eq__(other)
David Pursehouse717ece92012-11-13 08:49:16 +0900171
Conley Owensceea3682011-10-20 10:45:47 -0700172 def _resolveFetchUrl(self):
Jack Neus5ba21202021-06-09 15:21:25 +0000173 if self.fetchUrl is None:
174 return ''
Conley Owensceea3682011-10-20 10:45:47 -0700175 url = self.fetchUrl.rstrip('/')
Conley Owensdb728cd2011-09-26 16:34:01 -0700176 manifestUrl = self.manifestUrl.rstrip('/')
Conley Owens2d0f5082014-01-31 15:03:51 -0800177 # urljoin will gets confused over quite a few things. The ones we care
178 # about here are:
179 # * no scheme in the base url, like <hostname:port>
Anthony Kingcb07ba72015-03-28 23:26:04 +0000180 # We handle no scheme by replacing it with an obscure protocol, gopher
181 # and then replacing it with the original when we are done.
182
Conley Owensdb728cd2011-09-26 16:34:01 -0700183 if manifestUrl.find(':') != manifestUrl.find('/') - 1:
Conley Owens4ccad752015-04-29 10:45:37 -0700184 url = urllib.parse.urljoin('gopher://' + manifestUrl, url)
185 url = re.sub(r'^gopher://', '', url)
Anthony Kingcb07ba72015-03-28 23:26:04 +0000186 else:
187 url = urllib.parse.urljoin(manifestUrl, url)
Shawn Pearcea9f11b32013-01-02 15:40:48 -0800188 return url
Conley Owensceea3682011-10-20 10:45:47 -0700189
190 def ToRemoteSpec(self, projectName):
David Rileye0684ad2017-04-05 00:02:59 -0700191 fetchUrl = self.resolvedFetchUrl.rstrip('/')
192 url = fetchUrl + '/' + projectName
Yestin Sunb292b982012-07-02 07:32:50 -0700193 remoteName = self.name
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700194 if self.remoteAlias:
David Pursehouse37128b62013-10-15 10:48:40 +0900195 remoteName = self.remoteAlias
Dan Willemsen96c2d652016-04-06 16:03:54 -0700196 return RemoteSpec(remoteName,
197 url=url,
Steve Raed6480452016-08-10 15:00:00 -0700198 pushUrl=self.pushUrl,
Dan Willemsen96c2d652016-04-06 16:03:54 -0700199 review=self.reviewUrl,
David Rileye0684ad2017-04-05 00:02:59 -0700200 orig_name=self.name,
201 fetchUrl=self.fetchUrl)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700202
Jack Neus6ea0cae2021-07-20 20:52:33 +0000203 def AddAnnotation(self, name, value, keep):
204 self.annotations.append(Annotation(name, value, keep))
205
David Pursehouse819827a2020-02-12 15:20:19 +0900206
LaMont Jonescc879a92021-11-18 22:40:18 +0000207class _XmlSubmanifest:
208 """Manage the <submanifest> element specified in the manifest.
209
210 Attributes:
211 name: a string, the name for this submanifest.
212 remote: a string, the remote.name for this submanifest.
213 project: a string, the name of the manifest project.
214 revision: a string, the commitish.
215 manifestName: a string, the submanifest file name.
216 groups: a list of strings, the groups to add to all projects in the submanifest.
LaMont Jones501733c2022-04-20 16:42:32 +0000217 default_groups: a list of strings, the default groups to sync.
LaMont Jonescc879a92021-11-18 22:40:18 +0000218 path: a string, the relative path for the submanifest checkout.
LaMont Jonesb90a4222022-04-14 15:00:09 +0000219 parent: an XmlManifest, the parent manifest.
LaMont Jonescc879a92021-11-18 22:40:18 +0000220 annotations: (derived) a list of annotations.
LaMont Jonesb90a4222022-04-14 15:00:09 +0000221 present: (derived) a boolean, whether the sub manifest file is present.
LaMont Jonescc879a92021-11-18 22:40:18 +0000222 """
223 def __init__(self,
224 name,
225 remote=None,
226 project=None,
227 revision=None,
228 manifestName=None,
229 groups=None,
LaMont Jones501733c2022-04-20 16:42:32 +0000230 default_groups=None,
LaMont Jonescc879a92021-11-18 22:40:18 +0000231 path=None,
232 parent=None):
233 self.name = name
234 self.remote = remote
235 self.project = project
236 self.revision = revision
237 self.manifestName = manifestName
238 self.groups = groups
LaMont Jones501733c2022-04-20 16:42:32 +0000239 self.default_groups = default_groups
LaMont Jonescc879a92021-11-18 22:40:18 +0000240 self.path = path
LaMont Jonesb90a4222022-04-14 15:00:09 +0000241 self.parent = parent
LaMont Jonescc879a92021-11-18 22:40:18 +0000242 self.annotations = []
243 outer_client = parent._outer_client or parent
244 if self.remote and not self.project:
245 raise ManifestParseError(
246 f'Submanifest {name}: must specify project when remote is given.')
LaMont Jones5d3291d2022-03-23 19:03:02 +0000247 # Construct the absolute path to the manifest file using the parent's
248 # method, so that we can correctly create our repo_client.
249 manifestFile = parent.SubmanifestInfoDir(
250 os.path.join(parent.path_prefix, self.relpath),
251 os.path.join('manifests', manifestName or 'default.xml'))
LaMont Jones55ee3042022-04-06 17:10:21 +0000252 linkFile = parent.SubmanifestInfoDir(
253 os.path.join(parent.path_prefix, self.relpath), MANIFEST_FILE_NAME)
LaMont Jonescc879a92021-11-18 22:40:18 +0000254 rc = self.repo_client = RepoClient(
LaMont Jones55ee3042022-04-06 17:10:21 +0000255 parent.repodir, linkFile, parent_groups=','.join(groups) or '',
LaMont Jones501733c2022-04-20 16:42:32 +0000256 submanifest_path=self.relpath, outer_client=outer_client,
257 default_groups=default_groups)
LaMont Jonescc879a92021-11-18 22:40:18 +0000258
LaMont Jones55ee3042022-04-06 17:10:21 +0000259 self.present = os.path.exists(manifestFile)
LaMont Jonescc879a92021-11-18 22:40:18 +0000260
261 def __eq__(self, other):
262 if not isinstance(other, _XmlSubmanifest):
263 return False
264 return (
265 self.name == other.name and
266 self.remote == other.remote and
267 self.project == other.project and
268 self.revision == other.revision and
269 self.manifestName == other.manifestName and
270 self.groups == other.groups and
LaMont Jones501733c2022-04-20 16:42:32 +0000271 self.default_groups == other.default_groups and
LaMont Jonescc879a92021-11-18 22:40:18 +0000272 self.path == other.path and
273 sorted(self.annotations) == sorted(other.annotations))
274
275 def __ne__(self, other):
276 return not self.__eq__(other)
277
LaMont Jonesb90a4222022-04-14 15:00:09 +0000278 def ToSubmanifestSpec(self):
LaMont Jonescc879a92021-11-18 22:40:18 +0000279 """Return a SubmanifestSpec object, populating attributes"""
LaMont Jonesb90a4222022-04-14 15:00:09 +0000280 mp = self.parent.manifestProject
281 remote = self.parent.remotes[self.remote or self.parent.default.remote.name]
LaMont Jonescc879a92021-11-18 22:40:18 +0000282 # If a project was given, generate the url from the remote and project.
283 # If not, use this manifestProject's url.
284 if self.project:
285 manifestUrl = remote.ToRemoteSpec(self.project).url
286 else:
287 manifestUrl = mp.GetRemote(mp.remote.name).url
288 manifestName = self.manifestName or 'default.xml'
289 revision = self.revision or self.name
290 path = self.path or revision.split('/')[-1]
291 groups = self.groups or []
LaMont Jones501733c2022-04-20 16:42:32 +0000292 default_groups = self.default_groups or []
LaMont Jonescc879a92021-11-18 22:40:18 +0000293
294 return SubmanifestSpec(self.name, manifestUrl, manifestName, revision, path,
295 groups)
296
297 @property
298 def relpath(self):
299 """The path of this submanifest relative to the parent manifest."""
300 revision = self.revision or self.name
301 return self.path or revision.split('/')[-1]
302
303 def GetGroupsStr(self):
304 """Returns the `groups` given for this submanifest."""
305 if self.groups:
306 return ','.join(self.groups)
307 return ''
308
LaMont Jones501733c2022-04-20 16:42:32 +0000309 def GetDefaultGroupsStr(self):
310 """Returns the `default-groups` given for this submanifest."""
311 return ','.join(self.default_groups or [])
312
LaMont Jonescc879a92021-11-18 22:40:18 +0000313 def AddAnnotation(self, name, value, keep):
314 """Add annotations to the submanifest."""
315 self.annotations.append(Annotation(name, value, keep))
316
317
318class SubmanifestSpec:
319 """The submanifest element, with all fields expanded."""
320
321 def __init__(self,
322 name,
323 manifestUrl,
324 manifestName,
325 revision,
326 path,
327 groups):
328 self.name = name
329 self.manifestUrl = manifestUrl
330 self.manifestName = manifestName
331 self.revision = revision
332 self.path = path
333 self.groups = groups or []
334
335
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700336class XmlManifest(object):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700337 """manages the repo configuration file"""
338
LaMont Jonescc879a92021-11-18 22:40:18 +0000339 def __init__(self, repodir, manifest_file, local_manifests=None,
LaMont Jones501733c2022-04-20 16:42:32 +0000340 outer_client=None, parent_groups='', submanifest_path='',
341 default_groups=None):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400342 """Initialize.
343
344 Args:
345 repodir: Path to the .repo/ dir for holding all internal checkout state.
346 It must be in the top directory of the repo client checkout.
347 manifest_file: Full path to the manifest file to parse. This will usually
348 be |repodir|/|MANIFEST_FILE_NAME|.
349 local_manifests: Full path to the directory of local override manifests.
350 This will usually be |repodir|/|LOCAL_MANIFESTS_DIR_NAME|.
LaMont Jonescc879a92021-11-18 22:40:18 +0000351 outer_client: RepoClient of the outertree.
352 parent_groups: a string, the groups to apply to this projects.
353 submanifest_path: The submanifest root relative to the repo root.
LaMont Jones501733c2022-04-20 16:42:32 +0000354 default_groups: a string, the default manifest groups to use.
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400355 """
356 # TODO(vapier): Move this out of this class.
357 self.globalConfig = GitConfig.ForUser()
358
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700359 self.repodir = os.path.abspath(repodir)
LaMont Jonescc879a92021-11-18 22:40:18 +0000360 self._CheckLocalPath(submanifest_path)
361 self.topdir = os.path.join(os.path.dirname(self.repodir), submanifest_path)
LaMont Jones5d3291d2022-03-23 19:03:02 +0000362 if manifest_file != os.path.abspath(manifest_file):
363 raise ManifestParseError('manifest_file must be abspath')
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400364 self.manifestFile = manifest_file
LaMont Jonesb90a4222022-04-14 15:00:09 +0000365 if not outer_client or outer_client == self:
366 # manifestFileOverrides only exists in the outer_client's manifest, since
367 # that is the only instance left when Unload() is called on the outer
368 # manifest.
369 self.manifestFileOverrides = {}
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400370 self.local_manifests = local_manifests
Basil Gelloc7453502018-05-25 20:23:52 +0300371 self._load_local_manifests = True
LaMont Jonescc879a92021-11-18 22:40:18 +0000372 self.parent_groups = parent_groups
LaMont Jones501733c2022-04-20 16:42:32 +0000373 self.default_groups = default_groups
LaMont Jonescc879a92021-11-18 22:40:18 +0000374
375 if outer_client and self.isGitcClient:
376 raise ManifestParseError('Multi-manifest is incompatible with `gitc-init`')
377
378 if submanifest_path and not outer_client:
379 # If passing a submanifest_path, there must be an outer_client.
380 raise ManifestParseError(f'Bad call to {self.__class__.__name__}')
381
382 # If self._outer_client is None, this is not a checkout that supports
383 # multi-tree.
384 self._outer_client = outer_client or self
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700385
LaMont Jones9b72cf22022-03-29 21:54:22 +0000386 self.repoProject = RepoProject(self, 'repo',
David Pursehouseabdf7502020-02-12 14:58:39 +0900387 gitdir=os.path.join(repodir, 'repo/.git'),
388 worktree=os.path.join(repodir, 'repo'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700389
LaMont Jonescc879a92021-11-18 22:40:18 +0000390 mp = self.SubmanifestProject(self.path_prefix)
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500391 self.manifestProject = mp
392
393 # This is a bit hacky, but we're in a chicken & egg situation: all the
394 # normal repo settings live in the manifestProject which we just setup
395 # above, so we couldn't easily query before that. We assume Project()
396 # init doesn't care if this changes afterwards.
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000397 if os.path.exists(mp.gitdir) and mp.use_worktree:
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500398 mp.use_git_worktrees = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700399
LaMont Jonesa2ff20d2022-04-07 16:49:06 +0000400 self.Unload()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700401
Basil Gelloc7453502018-05-25 20:23:52 +0300402 def Override(self, name, load_local_manifests=True):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700403 """Use a different manifest, just for the current instantiation.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700404 """
Basil Gelloc7453502018-05-25 20:23:52 +0300405 path = None
406
407 # Look for a manifest by path in the filesystem (including the cwd).
408 if not load_local_manifests:
409 local_path = os.path.abspath(name)
410 if os.path.isfile(local_path):
411 path = local_path
412
413 # Look for manifests by name from the manifests repo.
414 if path is None:
415 path = os.path.join(self.manifestProject.worktree, name)
416 if not os.path.isfile(path):
417 raise ManifestParseError('manifest %s not found' % name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700418
LaMont Jonesb90a4222022-04-14 15:00:09 +0000419 self._load_local_manifests = load_local_manifests
420 self._outer_client.manifestFileOverrides[self.path_prefix] = path
421 self.Unload()
422 self._Load()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700423
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700424 def Link(self, name):
425 """Update the repo metadata to use a different manifest.
426 """
427 self.Override(name)
428
Mike Frysingera269b1c2020-02-21 00:49:41 -0500429 # Old versions of repo would generate symlinks we need to clean up.
Mike Frysinger9d96f582021-09-28 11:27:24 -0400430 platform_utils.remove(self.manifestFile, missing_ok=True)
Mike Frysingera269b1c2020-02-21 00:49:41 -0500431 # This file is interpreted as if it existed inside the manifest repo.
432 # That allows us to use <include> with the relative file name.
433 with open(self.manifestFile, 'w') as fp:
434 fp.write("""<?xml version="1.0" encoding="UTF-8"?>
435<!--
436DO NOT EDIT THIS FILE! It is generated by repo and changes will be discarded.
437If you want to use a different manifest, use `repo init -m <file>` instead.
438
439If you want to customize your checkout by overriding manifest settings, use
440the local_manifests/ directory instead.
441
442For more information on repo manifests, check out:
443https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
444-->
445<manifest>
446 <include name="%s" />
447</manifest>
448""" % (name,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700449
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800450 def _RemoteToXml(self, r, doc, root):
451 e = doc.createElement('remote')
452 root.appendChild(e)
453 e.setAttribute('name', r.name)
454 e.setAttribute('fetch', r.fetchUrl)
Steve Raed6480452016-08-10 15:00:00 -0700455 if r.pushUrl is not None:
456 e.setAttribute('pushurl', r.pushUrl)
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700457 if r.remoteAlias is not None:
458 e.setAttribute('alias', r.remoteAlias)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800459 if r.reviewUrl is not None:
460 e.setAttribute('review', r.reviewUrl)
Anthony King36ea2fb2014-05-06 11:54:01 +0100461 if r.revision is not None:
462 e.setAttribute('revision', r.revision)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800463
Jack Neus6ea0cae2021-07-20 20:52:33 +0000464 for a in r.annotations:
465 if a.keep == 'true':
466 ae = doc.createElement('annotation')
467 ae.setAttribute('name', a.name)
468 ae.setAttribute('value', a.value)
469 e.appendChild(ae)
470
LaMont Jonescc879a92021-11-18 22:40:18 +0000471 def _SubmanifestToXml(self, r, doc, root):
472 """Generate XML <submanifest/> node."""
473 e = doc.createElement('submanifest')
474 root.appendChild(e)
475 e.setAttribute('name', r.name)
476 if r.remote is not None:
477 e.setAttribute('remote', r.remote)
478 if r.project is not None:
479 e.setAttribute('project', r.project)
480 if r.manifestName is not None:
481 e.setAttribute('manifest-name', r.manifestName)
482 if r.revision is not None:
483 e.setAttribute('revision', r.revision)
484 if r.path is not None:
485 e.setAttribute('path', r.path)
486 if r.groups:
487 e.setAttribute('groups', r.GetGroupsStr())
LaMont Jones501733c2022-04-20 16:42:32 +0000488 if r.default_groups:
489 e.setAttribute('default-groups', r.GetDefaultGroupsStr())
LaMont Jonescc879a92021-11-18 22:40:18 +0000490
491 for a in r.annotations:
492 if a.keep == 'true':
493 ae = doc.createElement('annotation')
494 ae.setAttribute('name', a.name)
495 ae.setAttribute('value', a.value)
496 e.appendChild(ae)
497
Mike Frysinger51e39d52020-12-04 05:32:06 -0500498 def _ParseList(self, field):
499 """Parse fields that contain flattened lists.
500
501 These are whitespace & comma separated. Empty elements will be discarded.
502 """
503 return [x for x in re.split(r'[,\s]+', field) if x]
Josh Triplett884a3872014-06-12 14:57:29 -0700504
Mike Frysinger23411d32020-09-02 04:31:10 -0400505 def ToXml(self, peg_rev=False, peg_rev_upstream=True, peg_rev_dest_branch=True, groups=None):
506 """Return the current manifest XML."""
Colin Cross5acde752012-03-28 20:15:45 -0700507 mp = self.manifestProject
508
Dan Willemsen5ea32d12015-09-08 13:27:20 -0700509 if groups is None:
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000510 groups = mp.manifest_groups
Matt Gumbel0c635bb2012-12-21 10:14:53 -0800511 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -0500512 groups = self._ParseList(groups)
Colin Cross5acde752012-03-28 20:15:45 -0700513
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800514 doc = xml.dom.minidom.Document()
515 root = doc.createElement('manifest')
LaMont Jonescc879a92021-11-18 22:40:18 +0000516 if self.is_submanifest:
517 root.setAttribute('path', self.path_prefix)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800518 doc.appendChild(root)
519
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700520 # Save out the notice. There's a little bit of work here to give it the
521 # right whitespace, which assumes that the notice is automatically indented
522 # by 4 by minidom.
523 if self.notice:
524 notice_element = root.appendChild(doc.createElement('notice'))
525 notice_lines = self.notice.splitlines()
David Pursehouse54a4e602020-02-12 14:31:05 +0900526 indented_notice = ('\n'.join(" " * 4 + line for line in notice_lines))[4:]
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700527 notice_element.appendChild(doc.createTextNode(indented_notice))
528
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800529 d = self.default
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800530
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530531 for r in sorted(self.remotes):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800532 self._RemoteToXml(self.remotes[r], doc, root)
533 if self.remotes:
534 root.appendChild(doc.createTextNode(''))
535
536 have_default = False
537 e = doc.createElement('default')
538 if d.remote:
539 have_default = True
540 e.setAttribute('remote', d.remote.name)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700541 if d.revisionExpr:
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800542 have_default = True
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700543 e.setAttribute('revision', d.revisionExpr)
Simon Ruggier7e59de22015-07-24 12:50:06 +0200544 if d.destBranchExpr:
545 have_default = True
546 e.setAttribute('dest-branch', d.destBranchExpr)
Nasser Grainawida403412018-05-04 12:53:29 -0600547 if d.upstreamExpr:
548 have_default = True
549 e.setAttribute('upstream', d.upstreamExpr)
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700550 if d.sync_j > 1:
551 have_default = True
552 e.setAttribute('sync-j', '%d' % d.sync_j)
Anatol Pomazau79770d22012-04-20 14:41:59 -0700553 if d.sync_c:
554 have_default = True
555 e.setAttribute('sync-c', 'true')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800556 if d.sync_s:
557 have_default = True
558 e.setAttribute('sync-s', 'true')
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900559 if not d.sync_tags:
560 have_default = True
561 e.setAttribute('sync-tags', 'false')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800562 if have_default:
563 root.appendChild(e)
564 root.appendChild(doc.createTextNode(''))
565
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700566 if self._manifest_server:
567 e = doc.createElement('manifest-server')
568 e.setAttribute('url', self._manifest_server)
569 root.appendChild(e)
570 root.appendChild(doc.createTextNode(''))
571
LaMont Jonescc879a92021-11-18 22:40:18 +0000572 for r in sorted(self.submanifests):
573 self._SubmanifestToXml(self.submanifests[r], doc, root)
574 if self.submanifests:
575 root.appendChild(doc.createTextNode(''))
576
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800577 def output_projects(parent, parent_node, projects):
David James8d201162013-10-11 17:03:19 -0700578 for project_name in projects:
579 for project in self._projects[project_name]:
580 output_project(parent, parent_node, project)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800581
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800582 def output_project(parent, parent_node, p):
Colin Cross5acde752012-03-28 20:15:45 -0700583 if not p.MatchesGroups(groups):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800584 return
585
586 name = p.name
587 relpath = p.relpath
588 if parent:
589 name = self._UnjoinName(parent.name, name)
590 relpath = self._UnjoinRelpath(parent.relpath, relpath)
Colin Cross5acde752012-03-28 20:15:45 -0700591
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800592 e = doc.createElement('project')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800593 parent_node.appendChild(e)
594 e.setAttribute('name', name)
595 if relpath != name:
596 e.setAttribute('path', relpath)
Conley Owensa17d7af2013-10-16 14:38:09 -0700597 remoteName = None
598 if d.remote:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700599 remoteName = d.remote.name
600 if not d.remote or p.remote.orig_name != remoteName:
601 remoteName = p.remote.orig_name
Anthony King36ea2fb2014-05-06 11:54:01 +0100602 e.setAttribute('remote', remoteName)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800603 if peg_rev:
604 if self.IsMirror:
Brian Harring14a66742012-09-28 20:21:57 -0700605 value = p.bare_git.rev_parse(p.revisionExpr + '^0')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800606 else:
Brian Harring14a66742012-09-28 20:21:57 -0700607 value = p.work_git.rev_parse(HEAD + '^0')
608 e.setAttribute('revision', value)
Conley Owens551dfec2015-07-10 14:54:54 -0700609 if peg_rev_upstream:
610 if p.upstream:
611 e.setAttribute('upstream', p.upstream)
612 elif value != p.revisionExpr:
613 # Only save the origin if the origin is not a sha1, and the default
614 # isn't our value
615 e.setAttribute('upstream', p.revisionExpr)
Sean McAllisteraf908cb2020-04-20 08:41:58 -0600616
617 if peg_rev_dest_branch:
618 if p.dest_branch:
619 e.setAttribute('dest-branch', p.dest_branch)
620 elif value != p.revisionExpr:
621 e.setAttribute('dest-branch', p.revisionExpr)
622
Anthony King36ea2fb2014-05-06 11:54:01 +0100623 else:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700624 revision = self.remotes[p.remote.orig_name].revision or d.revisionExpr
Anthony King36ea2fb2014-05-06 11:54:01 +0100625 if not revision or revision != p.revisionExpr:
626 e.setAttribute('revision', p.revisionExpr)
Raman Tennetib5c5a5e2021-02-06 09:44:15 -0800627 elif p.revisionId:
628 e.setAttribute('revision', p.revisionId)
Nasser Grainawida403412018-05-04 12:53:29 -0600629 if (p.upstream and (p.upstream != p.revisionExpr or
630 p.upstream != d.upstreamExpr)):
Mani Chandel7a91d512014-07-24 16:27:08 +0530631 e.setAttribute('upstream', p.upstream)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800632
Simon Ruggier7e59de22015-07-24 12:50:06 +0200633 if p.dest_branch and p.dest_branch != d.destBranchExpr:
634 e.setAttribute('dest-branch', p.dest_branch)
635
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800636 for c in p.copyfiles:
637 ce = doc.createElement('copyfile')
638 ce.setAttribute('src', c.src)
639 ce.setAttribute('dest', c.dest)
640 e.appendChild(ce)
641
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500642 for l in p.linkfiles:
643 le = doc.createElement('linkfile')
644 le.setAttribute('src', l.src)
645 le.setAttribute('dest', l.dest)
646 e.appendChild(le)
647
Conley Owensbb1b5f52012-08-13 13:11:18 -0700648 default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
Dmitry Fink17f85ea2012-08-06 14:52:29 -0700649 egroups = [g for g in p.groups if g not in default_groups]
Conley Owens971de8e2012-04-16 10:36:08 -0700650 if egroups:
651 e.setAttribute('groups', ','.join(egroups))
Colin Cross5acde752012-03-28 20:15:45 -0700652
James W. Mills24c13082012-04-12 15:04:13 -0500653 for a in p.annotations:
654 if a.keep == "true":
655 ae = doc.createElement('annotation')
656 ae.setAttribute('name', a.name)
657 ae.setAttribute('value', a.value)
658 e.appendChild(ae)
659
Anatol Pomazau79770d22012-04-20 14:41:59 -0700660 if p.sync_c:
661 e.setAttribute('sync-c', 'true')
662
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800663 if p.sync_s:
664 e.setAttribute('sync-s', 'true')
665
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900666 if not p.sync_tags:
667 e.setAttribute('sync-tags', 'false')
668
Dan Willemsen88409222015-08-17 15:29:10 -0700669 if p.clone_depth:
670 e.setAttribute('clone-depth', str(p.clone_depth))
671
Simran Basib9a1b732015-08-20 12:19:28 -0700672 self._output_manifest_project_extras(p, e)
673
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800674 if p.subprojects:
David James8d201162013-10-11 17:03:19 -0700675 subprojects = set(subp.name for subp in p.subprojects)
676 output_projects(p, e, list(sorted(subprojects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800677
David James8d201162013-10-11 17:03:19 -0700678 projects = set(p.name for p in self._paths.values() if not p.parent)
679 output_projects(None, root, list(sorted(projects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800680
Doug Anderson37282b42011-03-04 11:54:18 -0800681 if self._repo_hooks_project:
682 root.appendChild(doc.createTextNode(''))
683 e = doc.createElement('repo-hooks')
684 e.setAttribute('in-project', self._repo_hooks_project.name)
685 e.setAttribute('enabled-list',
686 ' '.join(self._repo_hooks_project.enabled_repo_hooks))
687 root.appendChild(e)
688
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800689 if self._superproject:
690 root.appendChild(doc.createTextNode(''))
691 e = doc.createElement('superproject')
LaMont Jonesd56e2eb2022-04-07 18:14:46 +0000692 e.setAttribute('name', self._superproject.name)
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800693 remoteName = None
694 if d.remote:
695 remoteName = d.remote.name
LaMont Jonesd56e2eb2022-04-07 18:14:46 +0000696 remote = self._superproject.remote
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800697 if not d.remote or remote.orig_name != remoteName:
698 remoteName = remote.orig_name
699 e.setAttribute('remote', remoteName)
Xin Lie0b16a22021-09-26 23:20:32 -0700700 revision = remote.revision or d.revisionExpr
LaMont Jonesd56e2eb2022-04-07 18:14:46 +0000701 if not revision or revision != self._superproject.revision:
702 e.setAttribute('revision', self._superproject.revision)
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800703 root.appendChild(e)
704
Raman Tenneti993af5e2021-05-12 12:00:31 -0700705 if self._contactinfo.bugurl != Wrapper().BUG_URL:
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700706 root.appendChild(doc.createTextNode(''))
707 e = doc.createElement('contactinfo')
Raman Tenneti993af5e2021-05-12 12:00:31 -0700708 e.setAttribute('bugurl', self._contactinfo.bugurl)
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700709 root.appendChild(e)
710
Mike Frysinger23411d32020-09-02 04:31:10 -0400711 return doc
712
713 def ToDict(self, **kwargs):
714 """Return the current manifest as a dictionary."""
715 # Elements that may only appear once.
716 SINGLE_ELEMENTS = {
717 'notice',
718 'default',
719 'manifest-server',
720 'repo-hooks',
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800721 'superproject',
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700722 'contactinfo',
Mike Frysinger23411d32020-09-02 04:31:10 -0400723 }
724 # Elements that may be repeated.
725 MULTI_ELEMENTS = {
726 'remote',
727 'remove-project',
728 'project',
729 'extend-project',
730 'include',
LaMont Jonescc879a92021-11-18 22:40:18 +0000731 'submanifest',
Mike Frysinger23411d32020-09-02 04:31:10 -0400732 # These are children of 'project' nodes.
733 'annotation',
734 'project',
735 'copyfile',
736 'linkfile',
737 }
738
739 doc = self.ToXml(**kwargs)
740 ret = {}
741
742 def append_children(ret, node):
743 for child in node.childNodes:
744 if child.nodeType == xml.dom.Node.ELEMENT_NODE:
745 attrs = child.attributes
746 element = dict((attrs.item(i).localName, attrs.item(i).value)
747 for i in range(attrs.length))
748 if child.nodeName in SINGLE_ELEMENTS:
749 ret[child.nodeName] = element
750 elif child.nodeName in MULTI_ELEMENTS:
751 ret.setdefault(child.nodeName, []).append(element)
752 else:
753 raise ManifestParseError('Unhandled element "%s"' % (child.nodeName,))
754
755 append_children(element, child)
756
757 append_children(ret, doc.firstChild)
758
759 return ret
760
761 def Save(self, fd, **kwargs):
762 """Write the current manifest out to the given file descriptor."""
763 doc = self.ToXml(**kwargs)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800764 doc.writexml(fd, '', ' ', '\n', 'UTF-8')
765
Simran Basib9a1b732015-08-20 12:19:28 -0700766 def _output_manifest_project_extras(self, p, e):
767 """Manifests can modify e if they support extra project attributes."""
Simran Basib9a1b732015-08-20 12:19:28 -0700768
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700769 @property
LaMont Jonescc879a92021-11-18 22:40:18 +0000770 def is_multimanifest(self):
771 """Whether this is a multimanifest checkout"""
772 return bool(self.outer_client.submanifests)
773
774 @property
775 def is_submanifest(self):
776 """Whether this manifest is a submanifest"""
777 return self._outer_client and self._outer_client != self
778
779 @property
780 def outer_client(self):
781 """The instance of the outermost manifest client"""
782 self._Load()
783 return self._outer_client
784
785 @property
786 def all_manifests(self):
787 """Generator yielding all (sub)manifests."""
788 self._Load()
789 outer = self._outer_client
790 yield outer
791 for tree in outer.all_children:
792 yield tree
793
794 @property
795 def all_children(self):
796 """Generator yielding all child submanifests."""
797 self._Load()
798 for child in self._submanifests.values():
799 if child.repo_client:
800 yield child.repo_client
801 for tree in child.repo_client.all_children:
802 yield tree
803
804 @property
805 def path_prefix(self):
806 """The path of this submanifest, relative to the outermost manifest."""
807 if not self._outer_client or self == self._outer_client:
808 return ''
809 return os.path.relpath(self.topdir, self._outer_client.topdir)
810
811 @property
812 def all_paths(self):
813 """All project paths for all (sub)manifests. See `paths`."""
814 ret = {}
815 for tree in self.all_manifests:
816 prefix = tree.path_prefix
817 ret.update({os.path.join(prefix, k): v for k, v in tree.paths.items()})
818 return ret
819
820 @property
821 def all_projects(self):
822 """All projects for all (sub)manifests. See `projects`."""
823 return list(itertools.chain.from_iterable(x._paths.values() for x in self.all_manifests))
824
825 @property
David James8d201162013-10-11 17:03:19 -0700826 def paths(self):
LaMont Jonescc879a92021-11-18 22:40:18 +0000827 """Return all paths for this manifest.
828
829 Return:
830 A dictionary of {path: Project()}. `path` is relative to this manifest.
831 """
David James8d201162013-10-11 17:03:19 -0700832 self._Load()
833 return self._paths
834
835 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700836 def projects(self):
LaMont Jonescc879a92021-11-18 22:40:18 +0000837 """Return a list of all Projects in this manifest."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700838 self._Load()
Anthony Kingd58bfe52014-05-05 23:30:49 +0100839 return list(self._paths.values())
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700840
841 @property
842 def remotes(self):
843 self._Load()
844 return self._remotes
845
846 @property
847 def default(self):
848 self._Load()
849 return self._default
850
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800851 @property
LaMont Jonescc879a92021-11-18 22:40:18 +0000852 def submanifests(self):
853 """All submanifests in this manifest."""
854 self._Load()
855 return self._submanifests
856
857 @property
Doug Anderson37282b42011-03-04 11:54:18 -0800858 def repo_hooks_project(self):
859 self._Load()
860 return self._repo_hooks_project
861
862 @property
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800863 def superproject(self):
864 self._Load()
865 return self._superproject
866
867 @property
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700868 def contactinfo(self):
869 self._Load()
870 return self._contactinfo
871
872 @property
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700873 def notice(self):
874 self._Load()
875 return self._notice
876
877 @property
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700878 def manifest_server(self):
879 self._Load()
Shawn O. Pearce34fb20f2011-11-30 13:41:02 -0800880 return self._manifest_server
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700881
882 @property
Xin Lid79a4bc2020-05-20 16:03:45 -0700883 def CloneBundle(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000884 clone_bundle = self.manifestProject.clone_bundle
Xin Lid79a4bc2020-05-20 16:03:45 -0700885 if clone_bundle is None:
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000886 return False if self.manifestProject.partial_clone else True
Xin Lid79a4bc2020-05-20 16:03:45 -0700887 else:
888 return clone_bundle
889
890 @property
Xin Li745be2e2019-06-03 11:24:30 -0700891 def CloneFilter(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000892 if self.manifestProject.partial_clone:
893 return self.manifestProject.clone_filter
Xin Li745be2e2019-06-03 11:24:30 -0700894 return None
895
896 @property
Raman Tennetif32f2432021-04-12 20:57:25 -0700897 def PartialCloneExclude(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000898 exclude = self.manifest.manifestProject.partial_clone_exclude or ''
Raman Tennetif32f2432021-04-12 20:57:25 -0700899 return set(x.strip() for x in exclude.split(','))
900
LaMont Jonesb90a4222022-04-14 15:00:09 +0000901 def SetManifestOverride(self, path):
902 """Override manifestFile. The caller must call Unload()"""
903 self._outer_client.manifest.manifestFileOverrides[self.path_prefix] = path
904
Raman Tennetif32f2432021-04-12 20:57:25 -0700905 @property
Michael Kellyc34b91c2021-07-02 09:25:48 -0700906 def UseLocalManifests(self):
907 return self._load_local_manifests
908
909 def SetUseLocalManifests(self, value):
910 self._load_local_manifests = value
911
912 @property
Raman Tennetifeb28912021-05-02 19:47:29 -0700913 def HasLocalManifests(self):
914 return self._load_local_manifests and self.local_manifests
915
LaMont Jones87cce682022-02-14 17:48:31 +0000916 def IsFromLocalManifest(self, project):
LaMont Jonescc879a92021-11-18 22:40:18 +0000917 """Is the project from a local manifest?"""
LaMont Jones87cce682022-02-14 17:48:31 +0000918 return any(x.startswith(LOCAL_MANIFEST_GROUP_PREFIX)
919 for x in project.groups)
920
Raman Tennetifeb28912021-05-02 19:47:29 -0700921 @property
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800922 def IsMirror(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000923 return self.manifestProject.mirror
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800924
Julien Campergue335f5ef2013-10-16 11:02:35 +0200925 @property
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500926 def UseGitWorktrees(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000927 return self.manifestProject.use_worktree
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500928
929 @property
Julien Campergue335f5ef2013-10-16 11:02:35 +0200930 def IsArchive(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000931 return self.manifestProject.archive
Julien Campergue335f5ef2013-10-16 11:02:35 +0200932
Martin Kellye4e94d22017-03-21 16:05:12 -0700933 @property
934 def HasSubmodules(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000935 return self.manifestProject.submodules
Martin Kellye4e94d22017-03-21 16:05:12 -0700936
XD Trol630876f2022-01-17 23:29:04 +0800937 @property
938 def EnableGitLfs(self):
LaMont Jonesd82be3e2022-04-05 19:30:46 +0000939 return self.manifestProject.git_lfs
XD Trol630876f2022-01-17 23:29:04 +0800940
LaMont Jonescc879a92021-11-18 22:40:18 +0000941 def FindManifestByPath(self, path):
942 """Returns the manifest containing path."""
943 path = os.path.abspath(path)
944 manifest = self._outer_client or self
945 old = None
946 while manifest._submanifests and manifest != old:
947 old = manifest
948 for name in manifest._submanifests:
949 tree = manifest._submanifests[name]
950 if path.startswith(tree.repo_client.manifest.topdir):
951 manifest = tree.repo_client
952 break
953 return manifest
954
955 @property
956 def subdir(self):
957 """Returns the path for per-submanifest objects for this manifest."""
958 return self.SubmanifestInfoDir(self.path_prefix)
959
960 def SubmanifestInfoDir(self, submanifest_path, object_path=''):
961 """Return the path to submanifest-specific info for a submanifest.
962
963 Return the full path of the directory in which to put per-manifest objects.
964
965 Args:
966 submanifest_path: a string, the path of the submanifest, relative to the
967 outermost topdir. If empty, then repodir is returned.
968 object_path: a string, relative path to append to the submanifest info
969 directory path.
970 """
971 if submanifest_path:
972 return os.path.join(self.repodir, SUBMANIFEST_DIR, submanifest_path,
973 object_path)
974 else:
975 return os.path.join(self.repodir, object_path)
976
977 def SubmanifestProject(self, submanifest_path):
978 """Return a manifestProject for a submanifest."""
979 subdir = self.SubmanifestInfoDir(submanifest_path)
LaMont Jones9b72cf22022-03-29 21:54:22 +0000980 mp = ManifestProject(self, 'manifests',
981 gitdir=os.path.join(subdir, 'manifests.git'),
982 worktree=os.path.join(subdir, 'manifests'))
LaMont Jonescc879a92021-11-18 22:40:18 +0000983 return mp
984
LaMont Jones501733c2022-04-20 16:42:32 +0000985 def GetDefaultGroupsStr(self, with_platform=True):
986 """Returns the default group string to use.
987
988 Args:
989 with_platform: a boolean, whether to include the group for the
990 underlying platform.
991 """
992 groups = ','.join(self.default_groups or ['default'])
993 if with_platform:
994 groups += f',platform-{platform.system().lower()}'
995 return groups
Raman Tenneti080877e2021-03-09 15:19:06 -0800996
997 def GetGroupsStr(self):
998 """Returns the manifest group string that should be synced."""
LaMont Jones501733c2022-04-20 16:42:32 +0000999 return self.manifestProject.manifest_groups or self.GetDefaultGroupsStr()
Raman Tenneti080877e2021-03-09 15:19:06 -08001000
LaMont Jonesa2ff20d2022-04-07 16:49:06 +00001001 def Unload(self):
1002 """Unload the manifest.
1003
1004 If the manifest files have been changed since Load() was called, this will
1005 cause the new/updated manifest to be used.
1006
1007 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001008 self._loaded = False
1009 self._projects = {}
David James8d201162013-10-11 17:03:19 -07001010 self._paths = {}
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001011 self._remotes = {}
1012 self._default = None
LaMont Jonescc879a92021-11-18 22:40:18 +00001013 self._submanifests = {}
Doug Anderson37282b42011-03-04 11:54:18 -08001014 self._repo_hooks_project = None
LaMont Jonesd56e2eb2022-04-07 18:14:46 +00001015 self._superproject = None
Raman Tenneti993af5e2021-05-12 12:00:31 -07001016 self._contactinfo = ContactInfo(Wrapper().BUG_URL)
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001017 self._notice = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001018 self.branch = None
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001019 self._manifest_server = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001020
LaMont Jonesa2ff20d2022-04-07 16:49:06 +00001021 def Load(self):
1022 """Read the manifest into memory."""
1023 # Do not expose internal arguments.
1024 self._Load()
1025
LaMont Jonescc879a92021-11-18 22:40:18 +00001026 def _Load(self, initial_client=None, submanifest_depth=0):
1027 if submanifest_depth > MAX_SUBMANIFEST_DEPTH:
1028 raise ManifestParseError('maximum submanifest depth %d exceeded.' %
1029 MAX_SUBMANIFEST_DEPTH)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001030 if not self._loaded:
LaMont Jonescc879a92021-11-18 22:40:18 +00001031 if self._outer_client and self._outer_client != self:
1032 # This will load all clients.
1033 self._outer_client._Load(initial_client=self)
1034
LaMont Jonesb90a4222022-04-14 15:00:09 +00001035 savedManifestFile = self.manifestFile
1036 override = self._outer_client.manifestFileOverrides.get(self.path_prefix)
1037 if override:
1038 self.manifestFile = override
David Pursehouse2d5a0df2012-11-13 02:50:36 +09001039
Joe Onorato26e24752013-01-11 12:35:53 -08001040 try:
LaMont Jonesb90a4222022-04-14 15:00:09 +00001041 m = self.manifestProject
1042 b = m.GetBranch(m.CurrentBranch).merge
1043 if b is not None and b.startswith(R_HEADS):
1044 b = b[len(R_HEADS):]
1045 self.branch = b
Shawn O. Pearce5cc66792008-10-23 16:19:27 -07001046
LaMont Jonesb90a4222022-04-14 15:00:09 +00001047 parent_groups = self.parent_groups
1048 if self.path_prefix:
1049 parent_groups = f'{SUBMANIFEST_GROUP_PREFIX}:path:{self.path_prefix},{parent_groups}'
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001050
LaMont Jonesb90a4222022-04-14 15:00:09 +00001051 # The manifestFile was specified by the user which is why we allow include
1052 # paths to point anywhere.
1053 nodes = []
1054 nodes.append(self._ParseManifestXml(
1055 self.manifestFile, self.manifestProject.worktree,
1056 parent_groups=parent_groups, restrict_includes=False))
1057
1058 if self._load_local_manifests and self.local_manifests:
1059 try:
1060 for local_file in sorted(platform_utils.listdir(self.local_manifests)):
1061 if local_file.endswith('.xml'):
1062 local = os.path.join(self.local_manifests, local_file)
1063 # Since local manifests are entirely managed by the user, allow
1064 # them to point anywhere the user wants.
1065 local_group = f'{LOCAL_MANIFEST_GROUP_PREFIX}:{local_file[:-4]}'
1066 nodes.append(self._ParseManifestXml(
1067 local, self.subdir,
1068 parent_groups=f'{local_group},{parent_groups}',
1069 restrict_includes=False))
1070 except OSError:
1071 pass
1072
1073 try:
1074 self._ParseManifest(nodes)
1075 except ManifestParseError as e:
1076 # There was a problem parsing, unload ourselves in case they catch
1077 # this error and try again later, we will show the correct error
1078 self.Unload()
1079 raise e
1080
1081 if self.IsMirror:
1082 self._AddMetaProjectMirror(self.repoProject)
1083 self._AddMetaProjectMirror(self.manifestProject)
1084
1085 self._loaded = True
1086 finally:
1087 if override:
1088 self.manifestFile = savedManifestFile
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001089
LaMont Jonescc879a92021-11-18 22:40:18 +00001090 # Now that we have loaded this manifest, load any submanifest manifests
1091 # as well. We need to do this after self._loaded is set to avoid looping.
LaMont Jonesd56e2eb2022-04-07 18:14:46 +00001092 for name in self._submanifests:
1093 tree = self._submanifests[name]
LaMont Jonesb90a4222022-04-14 15:00:09 +00001094 spec = tree.ToSubmanifestSpec()
LaMont Jonesd56e2eb2022-04-07 18:14:46 +00001095 present = os.path.exists(os.path.join(self.subdir, MANIFEST_FILE_NAME))
1096 if present and tree.present and not tree.repo_client:
1097 if initial_client and initial_client.topdir == self.topdir:
1098 tree.repo_client = self
1099 tree.present = present
1100 elif not os.path.exists(self.subdir):
1101 tree.present = False
1102 if present and tree.present:
1103 tree.repo_client._Load(initial_client=initial_client,
1104 submanifest_depth=submanifest_depth + 1)
LaMont Jonescc879a92021-11-18 22:40:18 +00001105
Mike Frysinger54133972021-03-01 21:38:08 -05001106 def _ParseManifestXml(self, path, include_root, parent_groups='',
1107 restrict_includes=True):
1108 """Parse a manifest XML and return the computed nodes.
1109
1110 Args:
1111 path: The XML file to read & parse.
1112 include_root: The path to interpret include "name"s relative to.
1113 parent_groups: The groups to apply to this projects.
1114 restrict_includes: Whether to constrain the "name" attribute of includes.
1115
1116 Returns:
1117 List of XML nodes.
1118 """
David Pursehousef7fc8a92012-11-13 04:00:28 +09001119 try:
1120 root = xml.dom.minidom.parse(path)
David Pursehouse2d5a0df2012-11-13 02:50:36 +09001121 except (OSError, xml.parsers.expat.ExpatError) as e:
David Pursehousef7fc8a92012-11-13 04:00:28 +09001122 raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
1123
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001124 if not root or not root.childNodes:
Brian Harring26448742011-04-28 05:04:41 -07001125 raise ManifestParseError("no root node in %s" % (path,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001126
Jooncheol Park34acdd22012-08-27 02:25:59 +09001127 for manifest in root.childNodes:
1128 if manifest.nodeName == 'manifest':
1129 break
1130 else:
Brian Harring26448742011-04-28 05:04:41 -07001131 raise ManifestParseError("no <manifest> in %s" % (path,))
1132
Colin Cross23acdd32012-04-21 00:33:54 -07001133 nodes = []
David Pursehouse65b0ba52018-06-24 16:21:51 +09001134 for node in manifest.childNodes:
David Pursehousec1b86a22012-11-14 11:36:51 +09001135 if node.nodeName == 'include':
1136 name = self._reqatt(node, 'name')
Mike Frysinger54133972021-03-01 21:38:08 -05001137 if restrict_includes:
1138 msg = self._CheckLocalPath(name)
1139 if msg:
1140 raise ManifestInvalidPathError(
1141 '<include> invalid "name": %s: %s' % (name, msg))
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001142 include_groups = ''
1143 if parent_groups:
1144 include_groups = parent_groups
1145 if node.hasAttribute('groups'):
1146 include_groups = node.getAttribute('groups') + ',' + include_groups
David Pursehousec1b86a22012-11-14 11:36:51 +09001147 fp = os.path.join(include_root, name)
1148 if not os.path.isfile(fp):
Mike Frysinger54133972021-03-01 21:38:08 -05001149 raise ManifestParseError("include [%s/]%s doesn't exist or isn't a file"
1150 % (include_root, name))
David Pursehousec1b86a22012-11-14 11:36:51 +09001151 try:
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001152 nodes.extend(self._ParseManifestXml(fp, include_root, include_groups))
David Pursehousec1b86a22012-11-14 11:36:51 +09001153 # should isolate this to the exact exception, but that's
1154 # tricky. actual parsing implementation may vary.
Mike Frysinger54133972021-03-01 21:38:08 -05001155 except (KeyboardInterrupt, RuntimeError, SystemExit, ManifestParseError):
David Pursehousec1b86a22012-11-14 11:36:51 +09001156 raise
1157 except Exception as e:
1158 raise ManifestParseError(
Mike Frysingerec558df2019-07-05 01:38:05 -04001159 "failed parsing included manifest %s: %s" % (name, e))
David Pursehousec1b86a22012-11-14 11:36:51 +09001160 else:
Fredrik de Groot352c93b2020-10-06 12:55:14 +02001161 if parent_groups and node.nodeName == 'project':
1162 nodeGroups = parent_groups
1163 if node.hasAttribute('groups'):
1164 nodeGroups = node.getAttribute('groups') + ',' + nodeGroups
1165 node.setAttribute('groups', nodeGroups)
David Pursehousec1b86a22012-11-14 11:36:51 +09001166 nodes.append(node)
Colin Cross23acdd32012-04-21 00:33:54 -07001167 return nodes
Brian Harring26448742011-04-28 05:04:41 -07001168
Colin Cross23acdd32012-04-21 00:33:54 -07001169 def _ParseManifest(self, node_list):
1170 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001171 if node.nodeName == 'remote':
1172 remote = self._ParseRemote(node)
David Pursehouse717ece92012-11-13 08:49:16 +09001173 if remote:
1174 if remote.name in self._remotes:
1175 if remote != self._remotes[remote.name]:
1176 raise ManifestParseError(
1177 'remote %s already exists with different attributes' %
1178 (remote.name))
1179 else:
1180 self._remotes[remote.name] = remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001181
Colin Cross23acdd32012-04-21 00:33:54 -07001182 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001183 if node.nodeName == 'default':
Julien Campergue74879922013-10-09 14:38:46 +02001184 new_default = self._ParseDefault(node)
Jack Neusb8c84482021-06-15 14:28:30 +00001185 emptyDefault = not node.hasAttributes() and not node.hasChildNodes()
Julien Campergue74879922013-10-09 14:38:46 +02001186 if self._default is None:
1187 self._default = new_default
Jack Neusb8c84482021-06-15 14:28:30 +00001188 elif not emptyDefault and new_default != self._default:
David Pursehouse37128b62013-10-15 10:48:40 +09001189 raise ManifestParseError('duplicate default in %s' %
1190 (self.manifestFile))
Julien Campergue74879922013-10-09 14:38:46 +02001191
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001192 if self._default is None:
1193 self._default = _Default()
1194
LaMont Jonescc879a92021-11-18 22:40:18 +00001195 submanifest_paths = set()
1196 for node in itertools.chain(*node_list):
1197 if node.nodeName == 'submanifest':
1198 submanifest = self._ParseSubmanifest(node)
1199 if submanifest:
1200 if submanifest.name in self._submanifests:
1201 if submanifest != self._submanifests[submanifest.name]:
1202 raise ManifestParseError(
1203 'submanifest %s already exists with different attributes' %
1204 (submanifest.name))
1205 else:
1206 self._submanifests[submanifest.name] = submanifest
1207 submanifest_paths.add(submanifest.relpath)
1208
Colin Cross23acdd32012-04-21 00:33:54 -07001209 for node in itertools.chain(*node_list):
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001210 if node.nodeName == 'notice':
1211 if self._notice is not None:
Doug Anderson37282b42011-03-04 11:54:18 -08001212 raise ManifestParseError(
1213 'duplicate notice in %s' %
1214 (self.manifestFile))
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001215 self._notice = self._ParseNotice(node)
1216
Colin Cross23acdd32012-04-21 00:33:54 -07001217 for node in itertools.chain(*node_list):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001218 if node.nodeName == 'manifest-server':
1219 url = self._reqatt(node, 'url')
1220 if self._manifest_server is not None:
David Pursehousec1b86a22012-11-14 11:36:51 +09001221 raise ManifestParseError(
1222 'duplicate manifest-server in %s' %
1223 (self.manifestFile))
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001224 self._manifest_server = url
1225
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001226 def recursively_add_projects(project):
David James8d201162013-10-11 17:03:19 -07001227 projects = self._projects.setdefault(project.name, [])
1228 if project.relpath is None:
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001229 raise ManifestParseError(
David James8d201162013-10-11 17:03:19 -07001230 'missing path for %s in %s' %
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001231 (project.name, self.manifestFile))
David James8d201162013-10-11 17:03:19 -07001232 if project.relpath in self._paths:
1233 raise ManifestParseError(
1234 'duplicate path %s in %s' %
1235 (project.relpath, self.manifestFile))
LaMont Jonescc879a92021-11-18 22:40:18 +00001236 for tree in submanifest_paths:
1237 if project.relpath.startswith(tree):
1238 raise ManifestParseError(
1239 'project %s conflicts with submanifest path %s' %
1240 (project.relpath, tree))
David James8d201162013-10-11 17:03:19 -07001241 self._paths[project.relpath] = project
1242 projects.append(project)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001243 for subproject in project.subprojects:
1244 recursively_add_projects(subproject)
1245
Jack Neusa84f43a2021-09-21 22:23:55 +00001246 repo_hooks_project = None
1247 enabled_repo_hooks = None
Colin Cross23acdd32012-04-21 00:33:54 -07001248 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001249 if node.nodeName == 'project':
1250 project = self._ParseProject(node)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001251 recursively_add_projects(project)
Josh Triplett884a3872014-06-12 14:57:29 -07001252 if node.nodeName == 'extend-project':
1253 name = self._reqatt(node, 'name')
1254
1255 if name not in self._projects:
1256 raise ManifestParseError('extend-project element specifies non-existent '
1257 'project: %s' % name)
1258
1259 path = node.getAttribute('path')
Michael Kelly37c21c22020-06-13 02:10:40 -07001260 dest_path = node.getAttribute('dest-path')
Josh Triplett884a3872014-06-12 14:57:29 -07001261 groups = node.getAttribute('groups')
1262 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -05001263 groups = self._ParseList(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -07001264 revision = node.getAttribute('revision')
LaMont Jonescc879a92021-11-18 22:40:18 +00001265 remote_name = node.getAttribute('remote')
1266 if not remote_name:
1267 remote = self._default.remote
1268 else:
Kyunam Jobd0aae92020-02-04 11:38:53 +09001269 remote = self._get_remote(node)
Josh Triplett884a3872014-06-12 14:57:29 -07001270
Michael Kelly37c21c22020-06-13 02:10:40 -07001271 named_projects = self._projects[name]
1272 if dest_path and not path and len(named_projects) > 1:
1273 raise ManifestParseError('extend-project cannot use dest-path when '
1274 'matching multiple projects: %s' % name)
Josh Triplett884a3872014-06-12 14:57:29 -07001275 for p in self._projects[name]:
1276 if path and p.relpath != path:
1277 continue
1278 if groups:
1279 p.groups.extend(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -07001280 if revision:
Michael Kelly2f3c3312020-07-21 19:40:38 -07001281 p.SetRevision(revision)
1282
LaMont Jonescc879a92021-11-18 22:40:18 +00001283 if remote_name:
Kyunam Jobd0aae92020-02-04 11:38:53 +09001284 p.remote = remote.ToRemoteSpec(name)
Michael Kelly2f3c3312020-07-21 19:40:38 -07001285
Michael Kelly37c21c22020-06-13 02:10:40 -07001286 if dest_path:
1287 del self._paths[p.relpath]
LaMont Jonescc879a92021-11-18 22:40:18 +00001288 relpath, worktree, gitdir, objdir, _ = self.GetProjectPaths(
1289 name, dest_path, remote.name)
Michael Kelly37c21c22020-06-13 02:10:40 -07001290 p.UpdatePaths(relpath, worktree, gitdir, objdir)
1291 self._paths[p.relpath] = p
1292
Doug Anderson37282b42011-03-04 11:54:18 -08001293 if node.nodeName == 'repo-hooks':
Doug Anderson37282b42011-03-04 11:54:18 -08001294 # Only one project can be the hooks project
Jack Neusa84f43a2021-09-21 22:23:55 +00001295 if repo_hooks_project is not None:
Doug Anderson37282b42011-03-04 11:54:18 -08001296 raise ManifestParseError(
1297 'duplicate repo-hooks in %s' %
1298 (self.manifestFile))
1299
Jack Neusa84f43a2021-09-21 22:23:55 +00001300 # Get the name of the project and the (space-separated) list of enabled.
1301 repo_hooks_project = self._reqatt(node, 'in-project')
1302 enabled_repo_hooks = self._ParseList(self._reqatt(node, 'enabled-list'))
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001303 if node.nodeName == 'superproject':
1304 name = self._reqatt(node, 'name')
1305 # There can only be one superproject.
LaMont Jonesd56e2eb2022-04-07 18:14:46 +00001306 if self._superproject:
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001307 raise ManifestParseError(
1308 'duplicate superproject in %s' %
1309 (self.manifestFile))
Raman Tenneti1bb4fb22021-01-07 16:50:45 -08001310 remote_name = node.getAttribute('remote')
1311 if not remote_name:
1312 remote = self._default.remote
1313 else:
1314 remote = self._get_remote(node)
1315 if remote is None:
1316 raise ManifestParseError("no remote for superproject %s within %s" %
1317 (name, self.manifestFile))
Xin Lie0b16a22021-09-26 23:20:32 -07001318 revision = node.getAttribute('revision') or remote.revision
1319 if not revision:
1320 revision = self._default.revisionExpr
1321 if not revision:
1322 raise ManifestParseError('no revision for superproject %s within %s' %
1323 (name, self.manifestFile))
LaMont Jonesd56e2eb2022-04-07 18:14:46 +00001324 self._superproject = Superproject(self,
1325 name=name,
1326 remote=remote.ToRemoteSpec(name),
1327 revision=revision)
Raman Tenneti1c3f57e2021-05-04 12:32:13 -07001328 if node.nodeName == 'contactinfo':
1329 bugurl = self._reqatt(node, 'bugurl')
1330 # This element can be repeated, later entries will clobber earlier ones.
Raman Tenneti993af5e2021-05-12 12:00:31 -07001331 self._contactinfo = ContactInfo(bugurl)
1332
Colin Cross23acdd32012-04-21 00:33:54 -07001333 if node.nodeName == 'remove-project':
1334 name = self._reqatt(node, 'name')
David Jamesb8433df2014-01-30 10:11:17 -08001335
Michael Kelly06da9982021-06-30 01:58:28 -07001336 if name in self._projects:
1337 for p in self._projects[name]:
1338 del self._paths[p.relpath]
1339 del self._projects[name]
1340
1341 # If the manifest removes the hooks project, treat it as if it deleted
1342 # the repo-hooks element too.
Jack Neusa84f43a2021-09-21 22:23:55 +00001343 if repo_hooks_project == name:
1344 repo_hooks_project = None
Michael Kelly06da9982021-06-30 01:58:28 -07001345 elif not XmlBool(node, 'optional', False):
David Pursehousef9107482012-11-16 19:12:32 +09001346 raise ManifestParseError('remove-project element specifies non-existent '
1347 'project: %s' % name)
Colin Cross23acdd32012-04-21 00:33:54 -07001348
Jack Neusa84f43a2021-09-21 22:23:55 +00001349 # Store repo hooks project information.
1350 if repo_hooks_project:
1351 # Store a reference to the Project.
1352 try:
1353 repo_hooks_projects = self._projects[repo_hooks_project]
1354 except KeyError:
1355 raise ManifestParseError(
1356 'project %s not found for repo-hooks' %
1357 (repo_hooks_project))
1358
1359 if len(repo_hooks_projects) != 1:
1360 raise ManifestParseError(
1361 'internal error parsing repo-hooks in %s' %
1362 (self.manifestFile))
1363 self._repo_hooks_project = repo_hooks_projects[0]
1364 # Store the enabled hooks in the Project object.
1365 self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
1366
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001367 def _AddMetaProjectMirror(self, m):
1368 name = None
1369 m_url = m.GetRemote(m.remote.name).url
1370 if m_url.endswith('/.git'):
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301371 raise ManifestParseError('refusing to mirror %s' % m_url)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001372
1373 if self._default and self._default.remote:
Conley Owensceea3682011-10-20 10:45:47 -07001374 url = self._default.remote.resolvedFetchUrl
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001375 if not url.endswith('/'):
1376 url += '/'
1377 if m_url.startswith(url):
1378 remote = self._default.remote
1379 name = m_url[len(url):]
1380
1381 if name is None:
1382 s = m_url.rindex('/') + 1
Conley Owensdb728cd2011-09-26 16:34:01 -07001383 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Shawn O. Pearcef35b2d92012-08-02 11:46:22 -07001384 remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001385 name = m_url[s:]
1386
1387 if name.endswith('.git'):
1388 name = name[:-4]
1389
1390 if name not in self._projects:
1391 m.PreSync()
1392 gitdir = os.path.join(self.topdir, '%s.git' % name)
David Pursehousee5913ae2020-02-12 13:56:59 +09001393 project = Project(manifest=self,
1394 name=name,
1395 remote=remote.ToRemoteSpec(name),
1396 gitdir=gitdir,
1397 objdir=gitdir,
1398 worktree=None,
1399 relpath=name or None,
1400 revisionExpr=m.revisionExpr,
1401 revisionId=None)
David James8d201162013-10-11 17:03:19 -07001402 self._projects[project.name] = [project]
Kwanhong Leeccd218c2014-02-17 13:07:32 +09001403 self._paths[project.relpath] = project
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001404
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001405 def _ParseRemote(self, node):
1406 """
1407 reads a <remote> element from the manifest file
1408 """
1409 name = self._reqatt(node, 'name')
Yestin Sunb292b982012-07-02 07:32:50 -07001410 alias = node.getAttribute('alias')
1411 if alias == '':
1412 alias = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001413 fetch = self._reqatt(node, 'fetch')
Steve Raed6480452016-08-10 15:00:00 -07001414 pushUrl = node.getAttribute('pushurl')
1415 if pushUrl == '':
1416 pushUrl = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001417 review = node.getAttribute('review')
Shawn O. Pearceae6e0942008-11-06 10:25:35 -08001418 if review == '':
1419 review = None
Anthony King36ea2fb2014-05-06 11:54:01 +01001420 revision = node.getAttribute('revision')
1421 if revision == '':
1422 revision = None
Conley Owensdb728cd2011-09-26 16:34:01 -07001423 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Jack Neus6ea0cae2021-07-20 20:52:33 +00001424
1425 remote = _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
1426
1427 for n in node.childNodes:
1428 if n.nodeName == 'annotation':
1429 self._ParseAnnotation(remote, n)
1430
1431 return remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001432
1433 def _ParseDefault(self, node):
1434 """
1435 reads a <default> element from the manifest file
1436 """
1437 d = _Default()
1438 d.remote = self._get_remote(node)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001439 d.revisionExpr = node.getAttribute('revision')
1440 if d.revisionExpr == '':
1441 d.revisionExpr = None
Anatol Pomazau79770d22012-04-20 14:41:59 -07001442
Bryan Jacobsf609f912013-05-06 13:36:24 -04001443 d.destBranchExpr = node.getAttribute('dest-branch') or None
Nasser Grainawida403412018-05-04 12:53:29 -06001444 d.upstreamExpr = node.getAttribute('upstream') or None
Bryan Jacobsf609f912013-05-06 13:36:24 -04001445
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001446 d.sync_j = XmlInt(node, 'sync-j', 1)
1447 if d.sync_j <= 0:
1448 raise ManifestParseError('%s: sync-j must be greater than 0, not "%s"' %
1449 (self.manifestFile, d.sync_j))
Anatol Pomazau79770d22012-04-20 14:41:59 -07001450
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001451 d.sync_c = XmlBool(node, 'sync-c', False)
1452 d.sync_s = XmlBool(node, 'sync-s', False)
1453 d.sync_tags = XmlBool(node, 'sync-tags', True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001454 return d
1455
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001456 def _ParseNotice(self, node):
1457 """
1458 reads a <notice> element from the manifest file
1459
1460 The <notice> element is distinct from other tags in the XML in that the
1461 data is conveyed between the start and end tag (it's not an empty-element
1462 tag).
1463
1464 The white space (carriage returns, indentation) for the notice element is
1465 relevant and is parsed in a way that is based on how python docstrings work.
1466 In fact, the code is remarkably similar to here:
1467 http://www.python.org/dev/peps/pep-0257/
1468 """
1469 # Get the data out of the node...
1470 notice = node.childNodes[0].data
1471
1472 # Figure out minimum indentation, skipping the first line (the same line
1473 # as the <notice> tag)...
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301474 minIndent = sys.maxsize
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001475 lines = notice.splitlines()
1476 for line in lines[1:]:
1477 lstrippedLine = line.lstrip()
1478 if lstrippedLine:
1479 indent = len(line) - len(lstrippedLine)
1480 minIndent = min(indent, minIndent)
1481
1482 # Strip leading / trailing blank lines and also indentation.
1483 cleanLines = [lines[0].strip()]
1484 for line in lines[1:]:
1485 cleanLines.append(line[minIndent:].rstrip())
1486
1487 # Clear completely blank lines from front and back...
1488 while cleanLines and not cleanLines[0]:
1489 del cleanLines[0]
1490 while cleanLines and not cleanLines[-1]:
1491 del cleanLines[-1]
1492
1493 return '\n'.join(cleanLines)
1494
LaMont Jonescc879a92021-11-18 22:40:18 +00001495 def _ParseSubmanifest(self, node):
1496 """Reads a <submanifest> element from the manifest file."""
1497 name = self._reqatt(node, 'name')
1498 remote = node.getAttribute('remote')
1499 if remote == '':
1500 remote = None
1501 project = node.getAttribute('project')
1502 if project == '':
1503 project = None
1504 revision = node.getAttribute('revision')
1505 if revision == '':
1506 revision = None
1507 manifestName = node.getAttribute('manifest-name')
1508 if manifestName == '':
1509 manifestName = None
1510 groups = ''
1511 if node.hasAttribute('groups'):
1512 groups = node.getAttribute('groups')
1513 groups = self._ParseList(groups)
LaMont Jones501733c2022-04-20 16:42:32 +00001514 default_groups = self._ParseList(node.getAttribute('default-groups'))
LaMont Jonescc879a92021-11-18 22:40:18 +00001515 path = node.getAttribute('path')
1516 if path == '':
1517 path = None
1518 if revision:
1519 msg = self._CheckLocalPath(revision.split('/')[-1])
1520 if msg:
1521 raise ManifestInvalidPathError(
1522 '<submanifest> invalid "revision": %s: %s' % (revision, msg))
1523 else:
1524 msg = self._CheckLocalPath(name)
1525 if msg:
1526 raise ManifestInvalidPathError(
1527 '<submanifest> invalid "name": %s: %s' % (name, msg))
1528 else:
1529 msg = self._CheckLocalPath(path)
1530 if msg:
1531 raise ManifestInvalidPathError(
1532 '<submanifest> invalid "path": %s: %s' % (path, msg))
1533
1534 submanifest = _XmlSubmanifest(name, remote, project, revision, manifestName,
LaMont Jones501733c2022-04-20 16:42:32 +00001535 groups, default_groups, path, self)
LaMont Jonescc879a92021-11-18 22:40:18 +00001536
1537 for n in node.childNodes:
1538 if n.nodeName == 'annotation':
1539 self._ParseAnnotation(submanifest, n)
1540
1541 return submanifest
1542
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001543 def _JoinName(self, parent_name, name):
1544 return os.path.join(parent_name, name)
1545
1546 def _UnjoinName(self, parent_name, name):
1547 return os.path.relpath(name, parent_name)
1548
David Pursehousee5913ae2020-02-12 13:56:59 +09001549 def _ParseProject(self, node, parent=None, **extra_proj_attrs):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001550 """
1551 reads a <project> element from the manifest file
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001552 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001553 name = self._reqatt(node, 'name')
Mike Frysingera29424e2021-02-25 21:53:49 -05001554 msg = self._CheckLocalPath(name, dir_ok=True)
1555 if msg:
1556 raise ManifestInvalidPathError(
1557 '<project> invalid "name": %s: %s' % (name, msg))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001558 if parent:
1559 name = self._JoinName(parent.name, name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001560
1561 remote = self._get_remote(node)
1562 if remote is None:
1563 remote = self._default.remote
1564 if remote is None:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301565 raise ManifestParseError("no remote for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001566 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001567
Anthony King36ea2fb2014-05-06 11:54:01 +01001568 revisionExpr = node.getAttribute('revision') or remote.revision
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001569 if not revisionExpr:
1570 revisionExpr = self._default.revisionExpr
1571 if not revisionExpr:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301572 raise ManifestParseError("no revision for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001573 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001574
1575 path = node.getAttribute('path')
1576 if not path:
1577 path = name
Mike Frysingera29424e2021-02-25 21:53:49 -05001578 else:
Mike Frysinger0458faa2021-03-10 23:35:44 -05001579 # NB: The "." project is handled specially in Project.Sync_LocalHalf.
1580 msg = self._CheckLocalPath(path, dir_ok=True, cwd_dot_ok=True)
Mike Frysingera29424e2021-02-25 21:53:49 -05001581 if msg:
1582 raise ManifestInvalidPathError(
1583 '<project> invalid "path": %s: %s' % (path, msg))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001584
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001585 rebase = XmlBool(node, 'rebase', True)
1586 sync_c = XmlBool(node, 'sync-c', False)
1587 sync_s = XmlBool(node, 'sync-s', self._default.sync_s)
1588 sync_tags = XmlBool(node, 'sync-tags', self._default.sync_tags)
Mike Pontillod3153822012-02-28 11:53:24 -08001589
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001590 clone_depth = XmlInt(node, 'clone-depth')
1591 if clone_depth is not None and clone_depth <= 0:
1592 raise ManifestParseError('%s: clone-depth must be greater than 0, not "%s"' %
1593 (self.manifestFile, clone_depth))
David Pursehouseede7f122012-11-27 22:25:30 +09001594
Bryan Jacobsf609f912013-05-06 13:36:24 -04001595 dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
1596
Nasser Grainawida403412018-05-04 12:53:29 -06001597 upstream = node.getAttribute('upstream') or self._default.upstreamExpr
Brian Harring14a66742012-09-28 20:21:57 -07001598
Conley Owens971de8e2012-04-16 10:36:08 -07001599 groups = ''
1600 if node.hasAttribute('groups'):
1601 groups = node.getAttribute('groups')
Mike Frysinger51e39d52020-12-04 05:32:06 -05001602 groups = self._ParseList(groups)
Brian Harring7da13142012-06-15 02:24:20 -07001603
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001604 if parent is None:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001605 relpath, worktree, gitdir, objdir, use_git_worktrees = \
LaMont Jonescc879a92021-11-18 22:40:18 +00001606 self.GetProjectPaths(name, path, remote.name)
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001607 else:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001608 use_git_worktrees = False
David James8d201162013-10-11 17:03:19 -07001609 relpath, worktree, gitdir, objdir = \
1610 self.GetSubprojectPaths(parent, name, path)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001611
1612 default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
1613 groups.extend(set(default_groups).difference(groups))
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001614
Scott Fandb83b1b2013-02-28 09:34:14 +08001615 if self.IsMirror and node.hasAttribute('force-path'):
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001616 if XmlBool(node, 'force-path', False):
Scott Fandb83b1b2013-02-28 09:34:14 +08001617 gitdir = os.path.join(self.topdir, '%s.git' % path)
1618
David Pursehousee5913ae2020-02-12 13:56:59 +09001619 project = Project(manifest=self,
1620 name=name,
1621 remote=remote.ToRemoteSpec(name),
1622 gitdir=gitdir,
1623 objdir=objdir,
1624 worktree=worktree,
1625 relpath=relpath,
1626 revisionExpr=revisionExpr,
1627 revisionId=None,
1628 rebase=rebase,
1629 groups=groups,
1630 sync_c=sync_c,
1631 sync_s=sync_s,
1632 sync_tags=sync_tags,
1633 clone_depth=clone_depth,
1634 upstream=upstream,
1635 parent=parent,
1636 dest_branch=dest_branch,
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001637 use_git_worktrees=use_git_worktrees,
Simran Basib9a1b732015-08-20 12:19:28 -07001638 **extra_proj_attrs)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001639
1640 for n in node.childNodes:
Shawn O. Pearce242b5262009-05-19 13:00:29 -07001641 if n.nodeName == 'copyfile':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001642 self._ParseCopyFile(project, n)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001643 if n.nodeName == 'linkfile':
1644 self._ParseLinkFile(project, n)
James W. Mills24c13082012-04-12 15:04:13 -05001645 if n.nodeName == 'annotation':
1646 self._ParseAnnotation(project, n)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001647 if n.nodeName == 'project':
David Pursehousee5913ae2020-02-12 13:56:59 +09001648 project.subprojects.append(self._ParseProject(n, parent=project))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001649
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001650 return project
1651
LaMont Jonescc879a92021-11-18 22:40:18 +00001652 def GetProjectPaths(self, name, path, remote):
1653 """Return the paths for a project.
1654
1655 Args:
1656 name: a string, the name of the project.
1657 path: a string, the path of the project.
1658 remote: a string, the remote.name of the project.
1659 """
Mike Frysingercebf2272020-05-26 01:02:29 -04001660 # The manifest entries might have trailing slashes. Normalize them to avoid
1661 # unexpected filesystem behavior since we do string concatenation below.
1662 path = path.rstrip('/')
1663 name = name.rstrip('/')
LaMont Jonescc879a92021-11-18 22:40:18 +00001664 remote = remote.rstrip('/')
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001665 use_git_worktrees = False
LaMont Jonescc879a92021-11-18 22:40:18 +00001666 use_remote_name = bool(self._outer_client._submanifests)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001667 relpath = path
1668 if self.IsMirror:
1669 worktree = None
1670 gitdir = os.path.join(self.topdir, '%s.git' % name)
David James8d201162013-10-11 17:03:19 -07001671 objdir = gitdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001672 else:
LaMont Jonescc879a92021-11-18 22:40:18 +00001673 if use_remote_name:
1674 namepath = os.path.join(remote, f'{name}.git')
1675 else:
1676 namepath = f'{name}.git'
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001677 worktree = os.path.join(self.topdir, path).replace('\\', '/')
LaMont Jonescc879a92021-11-18 22:40:18 +00001678 gitdir = os.path.join(self.subdir, 'projects', '%s.git' % path)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001679 # We allow people to mix git worktrees & non-git worktrees for now.
1680 # This allows for in situ migration of repo clients.
1681 if os.path.exists(gitdir) or not self.UseGitWorktrees:
LaMont Jonescc879a92021-11-18 22:40:18 +00001682 objdir = os.path.join(self.subdir, 'project-objects', namepath)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001683 else:
1684 use_git_worktrees = True
LaMont Jonescc879a92021-11-18 22:40:18 +00001685 gitdir = os.path.join(self.repodir, 'worktrees', namepath)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001686 objdir = gitdir
1687 return relpath, worktree, gitdir, objdir, use_git_worktrees
David James8d201162013-10-11 17:03:19 -07001688
LaMont Jonescc879a92021-11-18 22:40:18 +00001689 def GetProjectsWithName(self, name, all_manifests=False):
1690 """All projects with |name|.
1691
1692 Args:
1693 name: a string, the name of the project.
1694 all_manifests: a boolean, if True, then all manifests are searched. If
1695 False, then only this manifest is searched.
1696 """
1697 if all_manifests:
1698 return list(itertools.chain.from_iterable(
1699 x._projects.get(name, []) for x in self.all_manifests))
David James8d201162013-10-11 17:03:19 -07001700 return self._projects.get(name, [])
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001701
1702 def GetSubprojectName(self, parent, submodule_path):
1703 return os.path.join(parent.name, submodule_path)
1704
1705 def _JoinRelpath(self, parent_relpath, relpath):
1706 return os.path.join(parent_relpath, relpath)
1707
1708 def _UnjoinRelpath(self, parent_relpath, relpath):
1709 return os.path.relpath(relpath, parent_relpath)
1710
David James8d201162013-10-11 17:03:19 -07001711 def GetSubprojectPaths(self, parent, name, path):
Mike Frysingercebf2272020-05-26 01:02:29 -04001712 # The manifest entries might have trailing slashes. Normalize them to avoid
1713 # unexpected filesystem behavior since we do string concatenation below.
1714 path = path.rstrip('/')
1715 name = name.rstrip('/')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001716 relpath = self._JoinRelpath(parent.relpath, path)
1717 gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
David James8d201162013-10-11 17:03:19 -07001718 objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001719 if self.IsMirror:
1720 worktree = None
1721 else:
1722 worktree = os.path.join(parent.worktree, path).replace('\\', '/')
David James8d201162013-10-11 17:03:19 -07001723 return relpath, worktree, gitdir, objdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001724
Mike Frysinger04122b72019-07-31 23:32:58 -04001725 @staticmethod
Mike Frysingera00c5f42021-02-25 18:26:31 -05001726 def _CheckLocalPath(path, dir_ok=False, cwd_dot_ok=False):
1727 """Verify |path| is reasonable for use in filesystem paths.
1728
Mike Frysingera29424e2021-02-25 21:53:49 -05001729 Used with <copyfile> & <linkfile> & <project> elements.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001730
1731 This only validates the |path| in isolation: it does not check against the
1732 current filesystem state. Thus it is suitable as a first-past in a parser.
1733
1734 It enforces a number of constraints:
1735 * No empty paths.
1736 * No "~" in paths.
1737 * No Unicode codepoints that filesystems might elide when normalizing.
1738 * No relative path components like "." or "..".
1739 * No absolute paths.
1740 * No ".git" or ".repo*" path components.
1741
1742 Args:
1743 path: The path name to validate.
1744 dir_ok: Whether |path| may force a directory (e.g. end in a /).
1745 cwd_dot_ok: Whether |path| may be just ".".
1746
1747 Returns:
1748 None if |path| is OK, a failure message otherwise.
1749 """
1750 if not path:
1751 return 'empty paths not allowed'
1752
Mike Frysinger04122b72019-07-31 23:32:58 -04001753 if '~' in path:
1754 return '~ not allowed (due to 8.3 filenames on Windows filesystems)'
1755
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001756 path_codepoints = set(path)
1757
Mike Frysinger04122b72019-07-31 23:32:58 -04001758 # Some filesystems (like Apple's HFS+) try to normalize Unicode codepoints
1759 # which means there are alternative names for ".git". Reject paths with
1760 # these in it as there shouldn't be any reasonable need for them here.
1761 # The set of codepoints here was cribbed from jgit's implementation:
1762 # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
1763 BAD_CODEPOINTS = {
1764 u'\u200C', # ZERO WIDTH NON-JOINER
1765 u'\u200D', # ZERO WIDTH JOINER
1766 u'\u200E', # LEFT-TO-RIGHT MARK
1767 u'\u200F', # RIGHT-TO-LEFT MARK
1768 u'\u202A', # LEFT-TO-RIGHT EMBEDDING
1769 u'\u202B', # RIGHT-TO-LEFT EMBEDDING
1770 u'\u202C', # POP DIRECTIONAL FORMATTING
1771 u'\u202D', # LEFT-TO-RIGHT OVERRIDE
1772 u'\u202E', # RIGHT-TO-LEFT OVERRIDE
1773 u'\u206A', # INHIBIT SYMMETRIC SWAPPING
1774 u'\u206B', # ACTIVATE SYMMETRIC SWAPPING
1775 u'\u206C', # INHIBIT ARABIC FORM SHAPING
1776 u'\u206D', # ACTIVATE ARABIC FORM SHAPING
1777 u'\u206E', # NATIONAL DIGIT SHAPES
1778 u'\u206F', # NOMINAL DIGIT SHAPES
1779 u'\uFEFF', # ZERO WIDTH NO-BREAK SPACE
1780 }
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001781 if BAD_CODEPOINTS & path_codepoints:
Mike Frysinger04122b72019-07-31 23:32:58 -04001782 # This message is more expansive than reality, but should be fine.
1783 return 'Unicode combining characters not allowed'
1784
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001785 # Reject newlines as there shouldn't be any legitmate use for them, they'll
1786 # be confusing to users, and they can easily break tools that expect to be
1787 # able to iterate over newline delimited lists. This even applies to our
1788 # own code like .repo/project.list.
1789 if {'\r', '\n'} & path_codepoints:
1790 return 'Newlines not allowed'
1791
Mike Frysinger04122b72019-07-31 23:32:58 -04001792 # Assume paths might be used on case-insensitive filesystems.
1793 path = path.lower()
1794
Mike Frysingerd9254592020-02-19 22:36:26 -05001795 # Split up the path by its components. We can't use os.path.sep exclusively
1796 # as some platforms (like Windows) will convert / to \ and that bypasses all
1797 # our constructed logic here. Especially since manifest authors only use
1798 # / in their paths.
1799 resep = re.compile(r'[/%s]' % re.escape(os.path.sep))
Mike Frysinger0458faa2021-03-10 23:35:44 -05001800 # Strip off trailing slashes as those only produce '' elements, and we use
1801 # parts to look for individual bad components.
1802 parts = resep.split(path.rstrip('/'))
Mike Frysingerd9254592020-02-19 22:36:26 -05001803
Mike Frysingerae625412020-02-10 17:10:03 -05001804 # Some people use src="." to create stable links to projects. Lets allow
1805 # that but reject all other uses of "." to keep things simple.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001806 if not cwd_dot_ok or parts != ['.']:
Mike Frysingerae625412020-02-10 17:10:03 -05001807 for part in set(parts):
1808 if part in {'.', '..', '.git'} or part.startswith('.repo'):
1809 return 'bad component: %s' % (part,)
Mike Frysinger04122b72019-07-31 23:32:58 -04001810
Mike Frysingera00c5f42021-02-25 18:26:31 -05001811 if not dir_ok and resep.match(path[-1]):
Mike Frysinger04122b72019-07-31 23:32:58 -04001812 return 'dirs not allowed'
1813
Mike Frysingerd9254592020-02-19 22:36:26 -05001814 # NB: The two abspath checks here are to handle platforms with multiple
1815 # filesystem path styles (e.g. Windows).
Mike Frysinger04122b72019-07-31 23:32:58 -04001816 norm = os.path.normpath(path)
Mike Frysingerd9254592020-02-19 22:36:26 -05001817 if (norm == '..' or
1818 (len(norm) >= 3 and norm.startswith('..') and resep.match(norm[0])) or
1819 os.path.isabs(norm) or
1820 norm.startswith('/')):
Mike Frysinger04122b72019-07-31 23:32:58 -04001821 return 'path cannot be outside'
1822
1823 @classmethod
1824 def _ValidateFilePaths(cls, element, src, dest):
1825 """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
1826
1827 We verify the path independent of any filesystem state as we won't have a
1828 checkout available to compare to. i.e. This is for parsing validation
1829 purposes only.
1830
1831 We'll do full/live sanity checking before we do the actual filesystem
1832 modifications in _CopyFile/_LinkFile/etc...
1833 """
1834 # |dest| is the file we write to or symlink we create.
1835 # It is relative to the top of the repo client checkout.
1836 msg = cls._CheckLocalPath(dest)
1837 if msg:
1838 raise ManifestInvalidPathError(
1839 '<%s> invalid "dest": %s: %s' % (element, dest, msg))
1840
1841 # |src| is the file we read from or path we point to for symlinks.
1842 # It is relative to the top of the git project checkout.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001843 is_linkfile = element == 'linkfile'
1844 msg = cls._CheckLocalPath(src, dir_ok=is_linkfile, cwd_dot_ok=is_linkfile)
Mike Frysinger04122b72019-07-31 23:32:58 -04001845 if msg:
1846 raise ManifestInvalidPathError(
1847 '<%s> invalid "src": %s: %s' % (element, src, msg))
1848
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001849 def _ParseCopyFile(self, project, node):
1850 src = self._reqatt(node, 'src')
1851 dest = self._reqatt(node, 'dest')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001852 if not self.IsMirror:
1853 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001854 # dest is relative to the top of the tree.
1855 # We only validate paths if we actually plan to process them.
1856 self._ValidateFilePaths('copyfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001857 project.AddCopyFile(src, dest, self.topdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001858
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001859 def _ParseLinkFile(self, project, node):
1860 src = self._reqatt(node, 'src')
1861 dest = self._reqatt(node, 'dest')
1862 if not self.IsMirror:
1863 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001864 # dest is relative to the top of the tree.
1865 # We only validate paths if we actually plan to process them.
1866 self._ValidateFilePaths('linkfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001867 project.AddLinkFile(src, dest, self.topdir)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001868
Jack Neus6ea0cae2021-07-20 20:52:33 +00001869 def _ParseAnnotation(self, element, node):
James W. Mills24c13082012-04-12 15:04:13 -05001870 name = self._reqatt(node, 'name')
1871 value = self._reqatt(node, 'value')
1872 try:
1873 keep = self._reqatt(node, 'keep').lower()
1874 except ManifestParseError:
1875 keep = "true"
1876 if keep != "true" and keep != "false":
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301877 raise ManifestParseError('optional "keep" attribute must be '
David Pursehouseabdf7502020-02-12 14:58:39 +09001878 '"true" or "false"')
Jack Neus6ea0cae2021-07-20 20:52:33 +00001879 element.AddAnnotation(name, value, keep)
James W. Mills24c13082012-04-12 15:04:13 -05001880
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001881 def _get_remote(self, node):
1882 name = node.getAttribute('remote')
1883 if not name:
1884 return None
1885
1886 v = self._remotes.get(name)
1887 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301888 raise ManifestParseError("remote %s not defined in %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001889 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001890 return v
1891
1892 def _reqatt(self, node, attname):
1893 """
1894 reads a required attribute from the node.
1895 """
1896 v = node.getAttribute(attname)
1897 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301898 raise ManifestParseError("no %s in <%s> within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001899 (attname, node.nodeName, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001900 return v
Julien Camperguedd654222014-01-09 16:21:37 +01001901
1902 def projectsDiff(self, manifest):
1903 """return the projects differences between two manifests.
1904
1905 The diff will be from self to given manifest.
1906
1907 """
1908 fromProjects = self.paths
1909 toProjects = manifest.paths
1910
Anthony King7446c592014-05-06 09:19:39 +01001911 fromKeys = sorted(fromProjects.keys())
1912 toKeys = sorted(toProjects.keys())
Julien Camperguedd654222014-01-09 16:21:37 +01001913
1914 diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
1915
1916 for proj in fromKeys:
David Pursehouseeeff3532020-02-12 11:24:10 +09001917 if proj not in toKeys:
Julien Camperguedd654222014-01-09 16:21:37 +01001918 diff['removed'].append(fromProjects[proj])
1919 else:
1920 fromProj = fromProjects[proj]
1921 toProj = toProjects[proj]
1922 try:
1923 fromRevId = fromProj.GetCommitRevisionId()
1924 toRevId = toProj.GetCommitRevisionId()
1925 except ManifestInvalidRevisionError:
1926 diff['unreachable'].append((fromProj, toProj))
1927 else:
1928 if fromRevId != toRevId:
1929 diff['changed'].append((fromProj, toProj))
1930 toKeys.remove(proj)
1931
1932 for proj in toKeys:
1933 diff['added'].append(toProjects[proj])
1934
1935 return diff
Simran Basib9a1b732015-08-20 12:19:28 -07001936
1937
1938class GitcManifest(XmlManifest):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001939 """Parser for GitC (git-in-the-cloud) manifests."""
Simran Basib9a1b732015-08-20 12:19:28 -07001940
David Pursehousee5913ae2020-02-12 13:56:59 +09001941 def _ParseProject(self, node, parent=None):
Simran Basib9a1b732015-08-20 12:19:28 -07001942 """Override _ParseProject and add support for GITC specific attributes."""
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001943 return super()._ParseProject(
Simran Basib9a1b732015-08-20 12:19:28 -07001944 node, parent=parent, old_revision=node.getAttribute('old-revision'))
1945
1946 def _output_manifest_project_extras(self, p, e):
1947 """Output GITC Specific Project attributes"""
1948 if p.old_revision:
Stefan Beller66851062016-06-17 16:40:08 -07001949 e.setAttribute('old-revision', str(p.old_revision))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001950
1951
1952class RepoClient(XmlManifest):
1953 """Manages a repo client checkout."""
1954
LaMont Jonescc879a92021-11-18 22:40:18 +00001955 def __init__(self, repodir, manifest_file=None, submanifest_path='', **kwargs):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001956 self.isGitcClient = False
LaMont Jonescc879a92021-11-18 22:40:18 +00001957 submanifest_path = submanifest_path or ''
1958 if submanifest_path:
1959 self._CheckLocalPath(submanifest_path)
1960 prefix = os.path.join(repodir, SUBMANIFEST_DIR, submanifest_path)
1961 else:
1962 prefix = repodir
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001963
LaMont Jonescc879a92021-11-18 22:40:18 +00001964 if os.path.exists(os.path.join(prefix, LOCAL_MANIFEST_NAME)):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001965 print('error: %s is not supported; put local manifests in `%s` instead' %
LaMont Jonescc879a92021-11-18 22:40:18 +00001966 (LOCAL_MANIFEST_NAME, os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME)),
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001967 file=sys.stderr)
1968 sys.exit(1)
1969
1970 if manifest_file is None:
LaMont Jonescc879a92021-11-18 22:40:18 +00001971 manifest_file = os.path.join(prefix, MANIFEST_FILE_NAME)
1972 local_manifests = os.path.abspath(os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME))
1973 super().__init__(repodir, manifest_file, local_manifests,
1974 submanifest_path=submanifest_path, **kwargs)
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001975
1976 # TODO: Completely separate manifest logic out of the client.
1977 self.manifest = self
1978
1979
1980class GitcClient(RepoClient, GitcManifest):
1981 """Manages a GitC client checkout."""
1982
1983 def __init__(self, repodir, gitc_client_name):
1984 """Initialize the GitcManifest object."""
1985 self.gitc_client_name = gitc_client_name
1986 self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
1987 gitc_client_name)
1988
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001989 super().__init__(repodir, os.path.join(self.gitc_client_dir, '.manifest'))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001990 self.isGitcClient = True