blob: cd5954dfac5da1b77448108953f22db06b59d561 [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
Colin Cross23acdd32012-04-21 00:33:54 -070015import itertools
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070016import os
Conley Owensdb728cd2011-09-26 16:34:01 -070017import re
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070018import sys
David Pursehouse59bbb582013-05-17 10:49:33 +090019import xml.dom.minidom
Mike Frysingeracf63b22019-06-13 02:24:21 -040020import urllib.parse
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070021
Simran Basib9a1b732015-08-20 12:19:28 -070022import gitc_utils
Miguel Gaio1f207762020-07-17 14:09:13 +020023from git_config import GitConfig, IsId
David Pursehousee00aa6b2012-09-11 14:33:51 +090024from git_refs import R_HEADS, HEAD
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070025import platform_utils
David Pursehousee00aa6b2012-09-11 14:33:51 +090026from project import RemoteSpec, Project, MetaProject
Mike Frysinger04122b72019-07-31 23:32:58 -040027from error import (ManifestParseError, ManifestInvalidPathError,
28 ManifestInvalidRevisionError)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070029
30MANIFEST_FILE_NAME = 'manifest.xml'
Shawn O. Pearce5cc66792008-10-23 16:19:27 -070031LOCAL_MANIFEST_NAME = 'local_manifest.xml'
David Pursehouse2d5a0df2012-11-13 02:50:36 +090032LOCAL_MANIFESTS_DIR_NAME = 'local_manifests'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070033
Anthony Kingcb07ba72015-03-28 23:26:04 +000034# urljoin gets confused if the scheme is not known.
Joe Kilner6e310792016-10-27 15:53:53 -070035urllib.parse.uses_relative.extend([
36 'ssh',
37 'git',
38 'persistent-https',
39 'sso',
40 'rpc'])
41urllib.parse.uses_netloc.extend([
42 'ssh',
43 'git',
44 'persistent-https',
45 'sso',
46 'rpc'])
Conley Owensdb728cd2011-09-26 16:34:01 -070047
David Pursehouse819827a2020-02-12 15:20:19 +090048
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050049def XmlBool(node, attr, default=None):
50 """Determine boolean value of |node|'s |attr|.
51
52 Invalid values will issue a non-fatal warning.
53
54 Args:
55 node: XML node whose attributes we access.
56 attr: The attribute to access.
57 default: If the attribute is not set (value is empty), then use this.
58
59 Returns:
60 True if the attribute is a valid string representing true.
61 False if the attribute is a valid string representing false.
62 |default| otherwise.
63 """
64 value = node.getAttribute(attr)
65 s = value.lower()
66 if s == '':
67 return default
68 elif s in {'yes', 'true', '1'}:
69 return True
70 elif s in {'no', 'false', '0'}:
71 return False
72 else:
73 print('warning: manifest: %s="%s": ignoring invalid XML boolean' %
74 (attr, value), file=sys.stderr)
75 return default
76
77
78def XmlInt(node, attr, default=None):
79 """Determine integer value of |node|'s |attr|.
80
81 Args:
82 node: XML node whose attributes we access.
83 attr: The attribute to access.
84 default: If the attribute is not set (value is empty), then use this.
85
86 Returns:
87 The number if the attribute is a valid number.
88
89 Raises:
90 ManifestParseError: The number is invalid.
91 """
92 value = node.getAttribute(attr)
93 if not value:
94 return default
95
96 try:
97 return int(value)
98 except ValueError:
99 raise ManifestParseError('manifest: invalid %s="%s" integer' %
100 (attr, value))
101
102
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700103class _Default(object):
104 """Project defaults within the manifest."""
105
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700106 revisionExpr = None
Conley Owensb6a16e62013-09-25 15:06:09 -0700107 destBranchExpr = None
Nasser Grainawida403412018-05-04 12:53:29 -0600108 upstreamExpr = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700109 remote = None
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700110 sync_j = 1
Anatol Pomazau79770d22012-04-20 14:41:59 -0700111 sync_c = False
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800112 sync_s = False
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900113 sync_tags = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700114
Julien Campergue74879922013-10-09 14:38:46 +0200115 def __eq__(self, other):
116 return self.__dict__ == other.__dict__
117
118 def __ne__(self, other):
119 return self.__dict__ != other.__dict__
120
David Pursehouse819827a2020-02-12 15:20:19 +0900121
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700122class _XmlRemote(object):
123 def __init__(self,
124 name,
Yestin Sunb292b982012-07-02 07:32:50 -0700125 alias=None,
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700126 fetch=None,
Steve Raed6480452016-08-10 15:00:00 -0700127 pushUrl=None,
Conley Owensdb728cd2011-09-26 16:34:01 -0700128 manifestUrl=None,
Anthony King36ea2fb2014-05-06 11:54:01 +0100129 review=None,
Jonathan Nieder93719792015-03-17 11:29:58 -0700130 revision=None):
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700131 self.name = name
132 self.fetchUrl = fetch
Steve Raed6480452016-08-10 15:00:00 -0700133 self.pushUrl = pushUrl
Conley Owensdb728cd2011-09-26 16:34:01 -0700134 self.manifestUrl = manifestUrl
Yestin Sunb292b982012-07-02 07:32:50 -0700135 self.remoteAlias = alias
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700136 self.reviewUrl = review
Anthony King36ea2fb2014-05-06 11:54:01 +0100137 self.revision = revision
Conley Owensceea3682011-10-20 10:45:47 -0700138 self.resolvedFetchUrl = self._resolveFetchUrl()
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700139
David Pursehouse717ece92012-11-13 08:49:16 +0900140 def __eq__(self, other):
141 return self.__dict__ == other.__dict__
142
143 def __ne__(self, other):
144 return self.__dict__ != other.__dict__
145
Conley Owensceea3682011-10-20 10:45:47 -0700146 def _resolveFetchUrl(self):
147 url = self.fetchUrl.rstrip('/')
Conley Owensdb728cd2011-09-26 16:34:01 -0700148 manifestUrl = self.manifestUrl.rstrip('/')
Conley Owens2d0f5082014-01-31 15:03:51 -0800149 # urljoin will gets confused over quite a few things. The ones we care
150 # about here are:
151 # * no scheme in the base url, like <hostname:port>
Anthony Kingcb07ba72015-03-28 23:26:04 +0000152 # We handle no scheme by replacing it with an obscure protocol, gopher
153 # and then replacing it with the original when we are done.
154
Conley Owensdb728cd2011-09-26 16:34:01 -0700155 if manifestUrl.find(':') != manifestUrl.find('/') - 1:
Conley Owens4ccad752015-04-29 10:45:37 -0700156 url = urllib.parse.urljoin('gopher://' + manifestUrl, url)
157 url = re.sub(r'^gopher://', '', url)
Anthony Kingcb07ba72015-03-28 23:26:04 +0000158 else:
159 url = urllib.parse.urljoin(manifestUrl, url)
Shawn Pearcea9f11b32013-01-02 15:40:48 -0800160 return url
Conley Owensceea3682011-10-20 10:45:47 -0700161
162 def ToRemoteSpec(self, projectName):
David Rileye0684ad2017-04-05 00:02:59 -0700163 fetchUrl = self.resolvedFetchUrl.rstrip('/')
164 url = fetchUrl + '/' + projectName
Yestin Sunb292b982012-07-02 07:32:50 -0700165 remoteName = self.name
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700166 if self.remoteAlias:
David Pursehouse37128b62013-10-15 10:48:40 +0900167 remoteName = self.remoteAlias
Dan Willemsen96c2d652016-04-06 16:03:54 -0700168 return RemoteSpec(remoteName,
169 url=url,
Steve Raed6480452016-08-10 15:00:00 -0700170 pushUrl=self.pushUrl,
Dan Willemsen96c2d652016-04-06 16:03:54 -0700171 review=self.reviewUrl,
David Rileye0684ad2017-04-05 00:02:59 -0700172 orig_name=self.name,
173 fetchUrl=self.fetchUrl)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700174
David Pursehouse819827a2020-02-12 15:20:19 +0900175
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700176class XmlManifest(object):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700177 """manages the repo configuration file"""
178
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400179 def __init__(self, repodir, manifest_file, local_manifests=None):
180 """Initialize.
181
182 Args:
183 repodir: Path to the .repo/ dir for holding all internal checkout state.
184 It must be in the top directory of the repo client checkout.
185 manifest_file: Full path to the manifest file to parse. This will usually
186 be |repodir|/|MANIFEST_FILE_NAME|.
187 local_manifests: Full path to the directory of local override manifests.
188 This will usually be |repodir|/|LOCAL_MANIFESTS_DIR_NAME|.
189 """
190 # TODO(vapier): Move this out of this class.
191 self.globalConfig = GitConfig.ForUser()
192
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700193 self.repodir = os.path.abspath(repodir)
194 self.topdir = os.path.dirname(self.repodir)
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400195 self.manifestFile = manifest_file
196 self.local_manifests = local_manifests
Basil Gelloc7453502018-05-25 20:23:52 +0300197 self._load_local_manifests = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700198
199 self.repoProject = MetaProject(self, 'repo',
David Pursehouseabdf7502020-02-12 14:58:39 +0900200 gitdir=os.path.join(repodir, 'repo/.git'),
201 worktree=os.path.join(repodir, 'repo'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700202
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500203 mp = MetaProject(self, 'manifests',
204 gitdir=os.path.join(repodir, 'manifests.git'),
205 worktree=os.path.join(repodir, 'manifests'))
206 self.manifestProject = mp
207
208 # This is a bit hacky, but we're in a chicken & egg situation: all the
209 # normal repo settings live in the manifestProject which we just setup
210 # above, so we couldn't easily query before that. We assume Project()
211 # init doesn't care if this changes afterwards.
Mike Frysingerd957ec62020-02-24 14:40:25 -0500212 if os.path.exists(mp.gitdir) and mp.config.GetBoolean('repo.worktree'):
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500213 mp.use_git_worktrees = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700214
215 self._Unload()
216
Basil Gelloc7453502018-05-25 20:23:52 +0300217 def Override(self, name, load_local_manifests=True):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700218 """Use a different manifest, just for the current instantiation.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700219 """
Basil Gelloc7453502018-05-25 20:23:52 +0300220 path = None
221
222 # Look for a manifest by path in the filesystem (including the cwd).
223 if not load_local_manifests:
224 local_path = os.path.abspath(name)
225 if os.path.isfile(local_path):
226 path = local_path
227
228 # Look for manifests by name from the manifests repo.
229 if path is None:
230 path = os.path.join(self.manifestProject.worktree, name)
231 if not os.path.isfile(path):
232 raise ManifestParseError('manifest %s not found' % name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700233
234 old = self.manifestFile
235 try:
Basil Gelloc7453502018-05-25 20:23:52 +0300236 self._load_local_manifests = load_local_manifests
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700237 self.manifestFile = path
238 self._Unload()
239 self._Load()
240 finally:
241 self.manifestFile = old
242
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700243 def Link(self, name):
244 """Update the repo metadata to use a different manifest.
245 """
246 self.Override(name)
247
Mike Frysingera269b1c2020-02-21 00:49:41 -0500248 # Old versions of repo would generate symlinks we need to clean up.
249 if os.path.lexists(self.manifestFile):
250 platform_utils.remove(self.manifestFile)
251 # This file is interpreted as if it existed inside the manifest repo.
252 # That allows us to use <include> with the relative file name.
253 with open(self.manifestFile, 'w') as fp:
254 fp.write("""<?xml version="1.0" encoding="UTF-8"?>
255<!--
256DO NOT EDIT THIS FILE! It is generated by repo and changes will be discarded.
257If you want to use a different manifest, use `repo init -m <file>` instead.
258
259If you want to customize your checkout by overriding manifest settings, use
260the local_manifests/ directory instead.
261
262For more information on repo manifests, check out:
263https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
264-->
265<manifest>
266 <include name="%s" />
267</manifest>
268""" % (name,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700269
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800270 def _RemoteToXml(self, r, doc, root):
271 e = doc.createElement('remote')
272 root.appendChild(e)
273 e.setAttribute('name', r.name)
274 e.setAttribute('fetch', r.fetchUrl)
Steve Raed6480452016-08-10 15:00:00 -0700275 if r.pushUrl is not None:
276 e.setAttribute('pushurl', r.pushUrl)
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700277 if r.remoteAlias is not None:
278 e.setAttribute('alias', r.remoteAlias)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800279 if r.reviewUrl is not None:
280 e.setAttribute('review', r.reviewUrl)
Anthony King36ea2fb2014-05-06 11:54:01 +0100281 if r.revision is not None:
282 e.setAttribute('revision', r.revision)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800283
Mike Frysinger51e39d52020-12-04 05:32:06 -0500284 def _ParseList(self, field):
285 """Parse fields that contain flattened lists.
286
287 These are whitespace & comma separated. Empty elements will be discarded.
288 """
289 return [x for x in re.split(r'[,\s]+', field) if x]
Josh Triplett884a3872014-06-12 14:57:29 -0700290
Mike Frysinger23411d32020-09-02 04:31:10 -0400291 def ToXml(self, peg_rev=False, peg_rev_upstream=True, peg_rev_dest_branch=True, groups=None):
292 """Return the current manifest XML."""
Colin Cross5acde752012-03-28 20:15:45 -0700293 mp = self.manifestProject
294
Dan Willemsen5ea32d12015-09-08 13:27:20 -0700295 if groups is None:
296 groups = mp.config.GetString('manifest.groups')
Matt Gumbel0c635bb2012-12-21 10:14:53 -0800297 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -0500298 groups = self._ParseList(groups)
Colin Cross5acde752012-03-28 20:15:45 -0700299
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800300 doc = xml.dom.minidom.Document()
301 root = doc.createElement('manifest')
302 doc.appendChild(root)
303
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700304 # Save out the notice. There's a little bit of work here to give it the
305 # right whitespace, which assumes that the notice is automatically indented
306 # by 4 by minidom.
307 if self.notice:
308 notice_element = root.appendChild(doc.createElement('notice'))
309 notice_lines = self.notice.splitlines()
David Pursehouse54a4e602020-02-12 14:31:05 +0900310 indented_notice = ('\n'.join(" " * 4 + line for line in notice_lines))[4:]
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700311 notice_element.appendChild(doc.createTextNode(indented_notice))
312
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800313 d = self.default
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800314
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530315 for r in sorted(self.remotes):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800316 self._RemoteToXml(self.remotes[r], doc, root)
317 if self.remotes:
318 root.appendChild(doc.createTextNode(''))
319
320 have_default = False
321 e = doc.createElement('default')
322 if d.remote:
323 have_default = True
324 e.setAttribute('remote', d.remote.name)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700325 if d.revisionExpr:
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800326 have_default = True
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700327 e.setAttribute('revision', d.revisionExpr)
Simon Ruggier7e59de22015-07-24 12:50:06 +0200328 if d.destBranchExpr:
329 have_default = True
330 e.setAttribute('dest-branch', d.destBranchExpr)
Nasser Grainawida403412018-05-04 12:53:29 -0600331 if d.upstreamExpr:
332 have_default = True
333 e.setAttribute('upstream', d.upstreamExpr)
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700334 if d.sync_j > 1:
335 have_default = True
336 e.setAttribute('sync-j', '%d' % d.sync_j)
Anatol Pomazau79770d22012-04-20 14:41:59 -0700337 if d.sync_c:
338 have_default = True
339 e.setAttribute('sync-c', 'true')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800340 if d.sync_s:
341 have_default = True
342 e.setAttribute('sync-s', 'true')
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900343 if not d.sync_tags:
344 have_default = True
345 e.setAttribute('sync-tags', 'false')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800346 if have_default:
347 root.appendChild(e)
348 root.appendChild(doc.createTextNode(''))
349
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700350 if self._manifest_server:
351 e = doc.createElement('manifest-server')
352 e.setAttribute('url', self._manifest_server)
353 root.appendChild(e)
354 root.appendChild(doc.createTextNode(''))
355
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800356 def output_projects(parent, parent_node, projects):
David James8d201162013-10-11 17:03:19 -0700357 for project_name in projects:
358 for project in self._projects[project_name]:
359 output_project(parent, parent_node, project)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800360
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800361 def output_project(parent, parent_node, p):
Colin Cross5acde752012-03-28 20:15:45 -0700362 if not p.MatchesGroups(groups):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800363 return
364
365 name = p.name
366 relpath = p.relpath
367 if parent:
368 name = self._UnjoinName(parent.name, name)
369 relpath = self._UnjoinRelpath(parent.relpath, relpath)
Colin Cross5acde752012-03-28 20:15:45 -0700370
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800371 e = doc.createElement('project')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800372 parent_node.appendChild(e)
373 e.setAttribute('name', name)
374 if relpath != name:
375 e.setAttribute('path', relpath)
Conley Owensa17d7af2013-10-16 14:38:09 -0700376 remoteName = None
377 if d.remote:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700378 remoteName = d.remote.name
379 if not d.remote or p.remote.orig_name != remoteName:
380 remoteName = p.remote.orig_name
Anthony King36ea2fb2014-05-06 11:54:01 +0100381 e.setAttribute('remote', remoteName)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800382 if peg_rev:
383 if self.IsMirror:
Brian Harring14a66742012-09-28 20:21:57 -0700384 value = p.bare_git.rev_parse(p.revisionExpr + '^0')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800385 else:
Brian Harring14a66742012-09-28 20:21:57 -0700386 value = p.work_git.rev_parse(HEAD + '^0')
387 e.setAttribute('revision', value)
Conley Owens551dfec2015-07-10 14:54:54 -0700388 if peg_rev_upstream:
389 if p.upstream:
390 e.setAttribute('upstream', p.upstream)
391 elif value != p.revisionExpr:
392 # Only save the origin if the origin is not a sha1, and the default
393 # isn't our value
394 e.setAttribute('upstream', p.revisionExpr)
Sean McAllisteraf908cb2020-04-20 08:41:58 -0600395
396 if peg_rev_dest_branch:
397 if p.dest_branch:
398 e.setAttribute('dest-branch', p.dest_branch)
399 elif value != p.revisionExpr:
400 e.setAttribute('dest-branch', p.revisionExpr)
401
Anthony King36ea2fb2014-05-06 11:54:01 +0100402 else:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700403 revision = self.remotes[p.remote.orig_name].revision or d.revisionExpr
Anthony King36ea2fb2014-05-06 11:54:01 +0100404 if not revision or revision != p.revisionExpr:
405 e.setAttribute('revision', p.revisionExpr)
Raman Tennetib5c5a5e2021-02-06 09:44:15 -0800406 elif p.revisionId:
407 e.setAttribute('revision', p.revisionId)
Nasser Grainawida403412018-05-04 12:53:29 -0600408 if (p.upstream and (p.upstream != p.revisionExpr or
409 p.upstream != d.upstreamExpr)):
Mani Chandel7a91d512014-07-24 16:27:08 +0530410 e.setAttribute('upstream', p.upstream)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800411
Simon Ruggier7e59de22015-07-24 12:50:06 +0200412 if p.dest_branch and p.dest_branch != d.destBranchExpr:
413 e.setAttribute('dest-branch', p.dest_branch)
414
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800415 for c in p.copyfiles:
416 ce = doc.createElement('copyfile')
417 ce.setAttribute('src', c.src)
418 ce.setAttribute('dest', c.dest)
419 e.appendChild(ce)
420
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500421 for l in p.linkfiles:
422 le = doc.createElement('linkfile')
423 le.setAttribute('src', l.src)
424 le.setAttribute('dest', l.dest)
425 e.appendChild(le)
426
Conley Owensbb1b5f52012-08-13 13:11:18 -0700427 default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
Dmitry Fink17f85ea2012-08-06 14:52:29 -0700428 egroups = [g for g in p.groups if g not in default_groups]
Conley Owens971de8e2012-04-16 10:36:08 -0700429 if egroups:
430 e.setAttribute('groups', ','.join(egroups))
Colin Cross5acde752012-03-28 20:15:45 -0700431
James W. Mills24c13082012-04-12 15:04:13 -0500432 for a in p.annotations:
433 if a.keep == "true":
434 ae = doc.createElement('annotation')
435 ae.setAttribute('name', a.name)
436 ae.setAttribute('value', a.value)
437 e.appendChild(ae)
438
Anatol Pomazau79770d22012-04-20 14:41:59 -0700439 if p.sync_c:
440 e.setAttribute('sync-c', 'true')
441
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800442 if p.sync_s:
443 e.setAttribute('sync-s', 'true')
444
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900445 if not p.sync_tags:
446 e.setAttribute('sync-tags', 'false')
447
Dan Willemsen88409222015-08-17 15:29:10 -0700448 if p.clone_depth:
449 e.setAttribute('clone-depth', str(p.clone_depth))
450
Simran Basib9a1b732015-08-20 12:19:28 -0700451 self._output_manifest_project_extras(p, e)
452
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800453 if p.subprojects:
David James8d201162013-10-11 17:03:19 -0700454 subprojects = set(subp.name for subp in p.subprojects)
455 output_projects(p, e, list(sorted(subprojects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800456
David James8d201162013-10-11 17:03:19 -0700457 projects = set(p.name for p in self._paths.values() if not p.parent)
458 output_projects(None, root, list(sorted(projects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800459
Doug Anderson37282b42011-03-04 11:54:18 -0800460 if self._repo_hooks_project:
461 root.appendChild(doc.createTextNode(''))
462 e = doc.createElement('repo-hooks')
463 e.setAttribute('in-project', self._repo_hooks_project.name)
464 e.setAttribute('enabled-list',
465 ' '.join(self._repo_hooks_project.enabled_repo_hooks))
466 root.appendChild(e)
467
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800468 if self._superproject:
469 root.appendChild(doc.createTextNode(''))
470 e = doc.createElement('superproject')
471 e.setAttribute('name', self._superproject['name'])
472 remoteName = None
473 if d.remote:
474 remoteName = d.remote.name
475 remote = self._superproject.get('remote')
476 if not d.remote or remote.orig_name != remoteName:
477 remoteName = remote.orig_name
478 e.setAttribute('remote', remoteName)
479 root.appendChild(e)
480
Mike Frysinger23411d32020-09-02 04:31:10 -0400481 return doc
482
483 def ToDict(self, **kwargs):
484 """Return the current manifest as a dictionary."""
485 # Elements that may only appear once.
486 SINGLE_ELEMENTS = {
487 'notice',
488 'default',
489 'manifest-server',
490 'repo-hooks',
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800491 'superproject',
Mike Frysinger23411d32020-09-02 04:31:10 -0400492 }
493 # Elements that may be repeated.
494 MULTI_ELEMENTS = {
495 'remote',
496 'remove-project',
497 'project',
498 'extend-project',
499 'include',
500 # These are children of 'project' nodes.
501 'annotation',
502 'project',
503 'copyfile',
504 'linkfile',
505 }
506
507 doc = self.ToXml(**kwargs)
508 ret = {}
509
510 def append_children(ret, node):
511 for child in node.childNodes:
512 if child.nodeType == xml.dom.Node.ELEMENT_NODE:
513 attrs = child.attributes
514 element = dict((attrs.item(i).localName, attrs.item(i).value)
515 for i in range(attrs.length))
516 if child.nodeName in SINGLE_ELEMENTS:
517 ret[child.nodeName] = element
518 elif child.nodeName in MULTI_ELEMENTS:
519 ret.setdefault(child.nodeName, []).append(element)
520 else:
521 raise ManifestParseError('Unhandled element "%s"' % (child.nodeName,))
522
523 append_children(element, child)
524
525 append_children(ret, doc.firstChild)
526
527 return ret
528
529 def Save(self, fd, **kwargs):
530 """Write the current manifest out to the given file descriptor."""
531 doc = self.ToXml(**kwargs)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800532 doc.writexml(fd, '', ' ', '\n', 'UTF-8')
533
Simran Basib9a1b732015-08-20 12:19:28 -0700534 def _output_manifest_project_extras(self, p, e):
535 """Manifests can modify e if they support extra project attributes."""
Simran Basib9a1b732015-08-20 12:19:28 -0700536
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700537 @property
David James8d201162013-10-11 17:03:19 -0700538 def paths(self):
539 self._Load()
540 return self._paths
541
542 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700543 def projects(self):
544 self._Load()
Anthony Kingd58bfe52014-05-05 23:30:49 +0100545 return list(self._paths.values())
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700546
547 @property
548 def remotes(self):
549 self._Load()
550 return self._remotes
551
552 @property
553 def default(self):
554 self._Load()
555 return self._default
556
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800557 @property
Doug Anderson37282b42011-03-04 11:54:18 -0800558 def repo_hooks_project(self):
559 self._Load()
560 return self._repo_hooks_project
561
562 @property
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800563 def superproject(self):
564 self._Load()
565 return self._superproject
566
567 @property
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700568 def notice(self):
569 self._Load()
570 return self._notice
571
572 @property
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700573 def manifest_server(self):
574 self._Load()
Shawn O. Pearce34fb20f2011-11-30 13:41:02 -0800575 return self._manifest_server
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700576
577 @property
Xin Lid79a4bc2020-05-20 16:03:45 -0700578 def CloneBundle(self):
579 clone_bundle = self.manifestProject.config.GetBoolean('repo.clonebundle')
580 if clone_bundle is None:
581 return False if self.manifestProject.config.GetBoolean('repo.partialclone') else True
582 else:
583 return clone_bundle
584
585 @property
Xin Li745be2e2019-06-03 11:24:30 -0700586 def CloneFilter(self):
587 if self.manifestProject.config.GetBoolean('repo.partialclone'):
588 return self.manifestProject.config.GetString('repo.clonefilter')
589 return None
590
591 @property
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800592 def IsMirror(self):
593 return self.manifestProject.config.GetBoolean('repo.mirror')
594
Julien Campergue335f5ef2013-10-16 11:02:35 +0200595 @property
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500596 def UseGitWorktrees(self):
597 return self.manifestProject.config.GetBoolean('repo.worktree')
598
599 @property
Julien Campergue335f5ef2013-10-16 11:02:35 +0200600 def IsArchive(self):
601 return self.manifestProject.config.GetBoolean('repo.archive')
602
Martin Kellye4e94d22017-03-21 16:05:12 -0700603 @property
604 def HasSubmodules(self):
605 return self.manifestProject.config.GetBoolean('repo.submodules')
606
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700607 def _Unload(self):
608 self._loaded = False
609 self._projects = {}
David James8d201162013-10-11 17:03:19 -0700610 self._paths = {}
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700611 self._remotes = {}
612 self._default = None
Doug Anderson37282b42011-03-04 11:54:18 -0800613 self._repo_hooks_project = None
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800614 self._superproject = {}
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700615 self._notice = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700616 self.branch = None
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700617 self._manifest_server = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700618
619 def _Load(self):
620 if not self._loaded:
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800621 m = self.manifestProject
622 b = m.GetBranch(m.CurrentBranch).merge
Shawn O. Pearce21c5c342009-06-25 16:47:30 -0700623 if b is not None and b.startswith(R_HEADS):
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800624 b = b[len(R_HEADS):]
625 self.branch = b
626
Colin Cross23acdd32012-04-21 00:33:54 -0700627 nodes = []
Brian Harring475a47d2012-06-07 20:05:35 -0700628 nodes.append(self._ParseManifestXml(self.manifestFile,
629 self.manifestProject.worktree))
Shawn O. Pearce5cc66792008-10-23 16:19:27 -0700630
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400631 if self._load_local_manifests and self.local_manifests:
Basil Gelloc7453502018-05-25 20:23:52 +0300632 try:
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400633 for local_file in sorted(platform_utils.listdir(self.local_manifests)):
Basil Gelloc7453502018-05-25 20:23:52 +0300634 if local_file.endswith('.xml'):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400635 local = os.path.join(self.local_manifests, local_file)
Basil Gelloc7453502018-05-25 20:23:52 +0300636 nodes.append(self._ParseManifestXml(local, self.repodir))
637 except OSError:
638 pass
David Pursehouse2d5a0df2012-11-13 02:50:36 +0900639
Joe Onorato26e24752013-01-11 12:35:53 -0800640 try:
641 self._ParseManifest(nodes)
642 except ManifestParseError as e:
643 # There was a problem parsing, unload ourselves in case they catch
644 # this error and try again later, we will show the correct error
645 self._Unload()
646 raise e
Shawn O. Pearce5cc66792008-10-23 16:19:27 -0700647
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800648 if self.IsMirror:
649 self._AddMetaProjectMirror(self.repoProject)
650 self._AddMetaProjectMirror(self.manifestProject)
651
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700652 self._loaded = True
653
Fredrik de Groot352c93b2020-10-06 12:55:14 +0200654 def _ParseManifestXml(self, path, include_root, parent_groups=''):
David Pursehousef7fc8a92012-11-13 04:00:28 +0900655 try:
656 root = xml.dom.minidom.parse(path)
David Pursehouse2d5a0df2012-11-13 02:50:36 +0900657 except (OSError, xml.parsers.expat.ExpatError) as e:
David Pursehousef7fc8a92012-11-13 04:00:28 +0900658 raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
659
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700660 if not root or not root.childNodes:
Brian Harring26448742011-04-28 05:04:41 -0700661 raise ManifestParseError("no root node in %s" % (path,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700662
Jooncheol Park34acdd22012-08-27 02:25:59 +0900663 for manifest in root.childNodes:
664 if manifest.nodeName == 'manifest':
665 break
666 else:
Brian Harring26448742011-04-28 05:04:41 -0700667 raise ManifestParseError("no <manifest> in %s" % (path,))
668
Colin Cross23acdd32012-04-21 00:33:54 -0700669 nodes = []
David Pursehouse65b0ba52018-06-24 16:21:51 +0900670 for node in manifest.childNodes:
David Pursehousec1b86a22012-11-14 11:36:51 +0900671 if node.nodeName == 'include':
672 name = self._reqatt(node, 'name')
Mike Frysingera29424e2021-02-25 21:53:49 -0500673 msg = self._CheckLocalPath(name)
674 if msg:
675 raise ManifestInvalidPathError(
676 '<include> invalid "name": %s: %s' % (name, msg))
Fredrik de Groot352c93b2020-10-06 12:55:14 +0200677 include_groups = ''
678 if parent_groups:
679 include_groups = parent_groups
680 if node.hasAttribute('groups'):
681 include_groups = node.getAttribute('groups') + ',' + include_groups
David Pursehousec1b86a22012-11-14 11:36:51 +0900682 fp = os.path.join(include_root, name)
683 if not os.path.isfile(fp):
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530684 raise ManifestParseError("include %s doesn't exist or isn't a file"
David Pursehouseabdf7502020-02-12 14:58:39 +0900685 % (name,))
David Pursehousec1b86a22012-11-14 11:36:51 +0900686 try:
Fredrik de Groot352c93b2020-10-06 12:55:14 +0200687 nodes.extend(self._ParseManifestXml(fp, include_root, include_groups))
David Pursehousec1b86a22012-11-14 11:36:51 +0900688 # should isolate this to the exact exception, but that's
689 # tricky. actual parsing implementation may vary.
690 except (KeyboardInterrupt, RuntimeError, SystemExit):
691 raise
692 except Exception as e:
693 raise ManifestParseError(
Mike Frysingerec558df2019-07-05 01:38:05 -0400694 "failed parsing included manifest %s: %s" % (name, e))
David Pursehousec1b86a22012-11-14 11:36:51 +0900695 else:
Fredrik de Groot352c93b2020-10-06 12:55:14 +0200696 if parent_groups and node.nodeName == 'project':
697 nodeGroups = parent_groups
698 if node.hasAttribute('groups'):
699 nodeGroups = node.getAttribute('groups') + ',' + nodeGroups
700 node.setAttribute('groups', nodeGroups)
David Pursehousec1b86a22012-11-14 11:36:51 +0900701 nodes.append(node)
Colin Cross23acdd32012-04-21 00:33:54 -0700702 return nodes
Brian Harring26448742011-04-28 05:04:41 -0700703
Colin Cross23acdd32012-04-21 00:33:54 -0700704 def _ParseManifest(self, node_list):
705 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700706 if node.nodeName == 'remote':
707 remote = self._ParseRemote(node)
David Pursehouse717ece92012-11-13 08:49:16 +0900708 if remote:
709 if remote.name in self._remotes:
710 if remote != self._remotes[remote.name]:
711 raise ManifestParseError(
712 'remote %s already exists with different attributes' %
713 (remote.name))
714 else:
715 self._remotes[remote.name] = remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700716
Colin Cross23acdd32012-04-21 00:33:54 -0700717 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700718 if node.nodeName == 'default':
Julien Campergue74879922013-10-09 14:38:46 +0200719 new_default = self._ParseDefault(node)
720 if self._default is None:
721 self._default = new_default
722 elif new_default != self._default:
David Pursehouse37128b62013-10-15 10:48:40 +0900723 raise ManifestParseError('duplicate default in %s' %
724 (self.manifestFile))
Julien Campergue74879922013-10-09 14:38:46 +0200725
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700726 if self._default is None:
727 self._default = _Default()
728
Colin Cross23acdd32012-04-21 00:33:54 -0700729 for node in itertools.chain(*node_list):
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700730 if node.nodeName == 'notice':
731 if self._notice is not None:
Doug Anderson37282b42011-03-04 11:54:18 -0800732 raise ManifestParseError(
733 'duplicate notice in %s' %
734 (self.manifestFile))
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700735 self._notice = self._ParseNotice(node)
736
Colin Cross23acdd32012-04-21 00:33:54 -0700737 for node in itertools.chain(*node_list):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700738 if node.nodeName == 'manifest-server':
739 url = self._reqatt(node, 'url')
740 if self._manifest_server is not None:
David Pursehousec1b86a22012-11-14 11:36:51 +0900741 raise ManifestParseError(
742 'duplicate manifest-server in %s' %
743 (self.manifestFile))
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700744 self._manifest_server = url
745
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800746 def recursively_add_projects(project):
David James8d201162013-10-11 17:03:19 -0700747 projects = self._projects.setdefault(project.name, [])
748 if project.relpath is None:
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800749 raise ManifestParseError(
David James8d201162013-10-11 17:03:19 -0700750 'missing path for %s in %s' %
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800751 (project.name, self.manifestFile))
David James8d201162013-10-11 17:03:19 -0700752 if project.relpath in self._paths:
753 raise ManifestParseError(
754 'duplicate path %s in %s' %
755 (project.relpath, self.manifestFile))
756 self._paths[project.relpath] = project
757 projects.append(project)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800758 for subproject in project.subprojects:
759 recursively_add_projects(subproject)
760
Colin Cross23acdd32012-04-21 00:33:54 -0700761 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700762 if node.nodeName == 'project':
763 project = self._ParseProject(node)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800764 recursively_add_projects(project)
Josh Triplett884a3872014-06-12 14:57:29 -0700765 if node.nodeName == 'extend-project':
766 name = self._reqatt(node, 'name')
767
768 if name not in self._projects:
769 raise ManifestParseError('extend-project element specifies non-existent '
770 'project: %s' % name)
771
772 path = node.getAttribute('path')
773 groups = node.getAttribute('groups')
774 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -0500775 groups = self._ParseList(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -0700776 revision = node.getAttribute('revision')
Kyunam Jobd0aae92020-02-04 11:38:53 +0900777 remote = node.getAttribute('remote')
778 if remote:
779 remote = self._get_remote(node)
Josh Triplett884a3872014-06-12 14:57:29 -0700780
781 for p in self._projects[name]:
782 if path and p.relpath != path:
783 continue
784 if groups:
785 p.groups.extend(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -0700786 if revision:
787 p.revisionExpr = revision
Miguel Gaio1f207762020-07-17 14:09:13 +0200788 if IsId(revision):
789 p.revisionId = revision
790 else:
791 p.revisionId = None
Kyunam Jobd0aae92020-02-04 11:38:53 +0900792 if remote:
793 p.remote = remote.ToRemoteSpec(name)
Doug Anderson37282b42011-03-04 11:54:18 -0800794 if node.nodeName == 'repo-hooks':
795 # Get the name of the project and the (space-separated) list of enabled.
796 repo_hooks_project = self._reqatt(node, 'in-project')
Mike Frysinger51e39d52020-12-04 05:32:06 -0500797 enabled_repo_hooks = self._ParseList(self._reqatt(node, 'enabled-list'))
Doug Anderson37282b42011-03-04 11:54:18 -0800798
799 # Only one project can be the hooks project
800 if self._repo_hooks_project is not None:
801 raise ManifestParseError(
802 'duplicate repo-hooks in %s' %
803 (self.manifestFile))
804
805 # Store a reference to the Project.
806 try:
David James8d201162013-10-11 17:03:19 -0700807 repo_hooks_projects = self._projects[repo_hooks_project]
Doug Anderson37282b42011-03-04 11:54:18 -0800808 except KeyError:
809 raise ManifestParseError(
810 'project %s not found for repo-hooks' %
811 (repo_hooks_project))
812
David James8d201162013-10-11 17:03:19 -0700813 if len(repo_hooks_projects) != 1:
814 raise ManifestParseError(
815 'internal error parsing repo-hooks in %s' %
816 (self.manifestFile))
817 self._repo_hooks_project = repo_hooks_projects[0]
818
Doug Anderson37282b42011-03-04 11:54:18 -0800819 # Store the enabled hooks in the Project object.
820 self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800821 if node.nodeName == 'superproject':
822 name = self._reqatt(node, 'name')
823 # There can only be one superproject.
824 if self._superproject.get('name'):
825 raise ManifestParseError(
826 'duplicate superproject in %s' %
827 (self.manifestFile))
828 self._superproject['name'] = name
829 remote_name = node.getAttribute('remote')
830 if not remote_name:
831 remote = self._default.remote
832 else:
833 remote = self._get_remote(node)
834 if remote is None:
835 raise ManifestParseError("no remote for superproject %s within %s" %
836 (name, self.manifestFile))
837 self._superproject['remote'] = remote.ToRemoteSpec(name)
Colin Cross23acdd32012-04-21 00:33:54 -0700838 if node.nodeName == 'remove-project':
839 name = self._reqatt(node, 'name')
David Jamesb8433df2014-01-30 10:11:17 -0800840
841 if name not in self._projects:
David Pursehousef9107482012-11-16 19:12:32 +0900842 raise ManifestParseError('remove-project element specifies non-existent '
843 'project: %s' % name)
Colin Cross23acdd32012-04-21 00:33:54 -0700844
David Jamesb8433df2014-01-30 10:11:17 -0800845 for p in self._projects[name]:
846 del self._paths[p.relpath]
847 del self._projects[name]
848
Colin Cross23acdd32012-04-21 00:33:54 -0700849 # If the manifest removes the hooks project, treat it as if it deleted
850 # the repo-hooks element too.
851 if self._repo_hooks_project and (self._repo_hooks_project.name == name):
852 self._repo_hooks_project = None
853
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800854 def _AddMetaProjectMirror(self, m):
855 name = None
856 m_url = m.GetRemote(m.remote.name).url
857 if m_url.endswith('/.git'):
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530858 raise ManifestParseError('refusing to mirror %s' % m_url)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800859
860 if self._default and self._default.remote:
Conley Owensceea3682011-10-20 10:45:47 -0700861 url = self._default.remote.resolvedFetchUrl
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800862 if not url.endswith('/'):
863 url += '/'
864 if m_url.startswith(url):
865 remote = self._default.remote
866 name = m_url[len(url):]
867
868 if name is None:
869 s = m_url.rindex('/') + 1
Conley Owensdb728cd2011-09-26 16:34:01 -0700870 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Shawn O. Pearcef35b2d92012-08-02 11:46:22 -0700871 remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800872 name = m_url[s:]
873
874 if name.endswith('.git'):
875 name = name[:-4]
876
877 if name not in self._projects:
878 m.PreSync()
879 gitdir = os.path.join(self.topdir, '%s.git' % name)
David Pursehousee5913ae2020-02-12 13:56:59 +0900880 project = Project(manifest=self,
881 name=name,
882 remote=remote.ToRemoteSpec(name),
883 gitdir=gitdir,
884 objdir=gitdir,
885 worktree=None,
886 relpath=name or None,
887 revisionExpr=m.revisionExpr,
888 revisionId=None)
David James8d201162013-10-11 17:03:19 -0700889 self._projects[project.name] = [project]
Kwanhong Leeccd218c2014-02-17 13:07:32 +0900890 self._paths[project.relpath] = project
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800891
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700892 def _ParseRemote(self, node):
893 """
894 reads a <remote> element from the manifest file
895 """
896 name = self._reqatt(node, 'name')
Yestin Sunb292b982012-07-02 07:32:50 -0700897 alias = node.getAttribute('alias')
898 if alias == '':
899 alias = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700900 fetch = self._reqatt(node, 'fetch')
Steve Raed6480452016-08-10 15:00:00 -0700901 pushUrl = node.getAttribute('pushurl')
902 if pushUrl == '':
903 pushUrl = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700904 review = node.getAttribute('review')
Shawn O. Pearceae6e0942008-11-06 10:25:35 -0800905 if review == '':
906 review = None
Anthony King36ea2fb2014-05-06 11:54:01 +0100907 revision = node.getAttribute('revision')
908 if revision == '':
909 revision = None
Conley Owensdb728cd2011-09-26 16:34:01 -0700910 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Steve Raed6480452016-08-10 15:00:00 -0700911 return _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700912
913 def _ParseDefault(self, node):
914 """
915 reads a <default> element from the manifest file
916 """
917 d = _Default()
918 d.remote = self._get_remote(node)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700919 d.revisionExpr = node.getAttribute('revision')
920 if d.revisionExpr == '':
921 d.revisionExpr = None
Anatol Pomazau79770d22012-04-20 14:41:59 -0700922
Bryan Jacobsf609f912013-05-06 13:36:24 -0400923 d.destBranchExpr = node.getAttribute('dest-branch') or None
Nasser Grainawida403412018-05-04 12:53:29 -0600924 d.upstreamExpr = node.getAttribute('upstream') or None
Bryan Jacobsf609f912013-05-06 13:36:24 -0400925
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500926 d.sync_j = XmlInt(node, 'sync-j', 1)
927 if d.sync_j <= 0:
928 raise ManifestParseError('%s: sync-j must be greater than 0, not "%s"' %
929 (self.manifestFile, d.sync_j))
Anatol Pomazau79770d22012-04-20 14:41:59 -0700930
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500931 d.sync_c = XmlBool(node, 'sync-c', False)
932 d.sync_s = XmlBool(node, 'sync-s', False)
933 d.sync_tags = XmlBool(node, 'sync-tags', True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700934 return d
935
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700936 def _ParseNotice(self, node):
937 """
938 reads a <notice> element from the manifest file
939
940 The <notice> element is distinct from other tags in the XML in that the
941 data is conveyed between the start and end tag (it's not an empty-element
942 tag).
943
944 The white space (carriage returns, indentation) for the notice element is
945 relevant and is parsed in a way that is based on how python docstrings work.
946 In fact, the code is remarkably similar to here:
947 http://www.python.org/dev/peps/pep-0257/
948 """
949 # Get the data out of the node...
950 notice = node.childNodes[0].data
951
952 # Figure out minimum indentation, skipping the first line (the same line
953 # as the <notice> tag)...
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530954 minIndent = sys.maxsize
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700955 lines = notice.splitlines()
956 for line in lines[1:]:
957 lstrippedLine = line.lstrip()
958 if lstrippedLine:
959 indent = len(line) - len(lstrippedLine)
960 minIndent = min(indent, minIndent)
961
962 # Strip leading / trailing blank lines and also indentation.
963 cleanLines = [lines[0].strip()]
964 for line in lines[1:]:
965 cleanLines.append(line[minIndent:].rstrip())
966
967 # Clear completely blank lines from front and back...
968 while cleanLines and not cleanLines[0]:
969 del cleanLines[0]
970 while cleanLines and not cleanLines[-1]:
971 del cleanLines[-1]
972
973 return '\n'.join(cleanLines)
974
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800975 def _JoinName(self, parent_name, name):
976 return os.path.join(parent_name, name)
977
978 def _UnjoinName(self, parent_name, name):
979 return os.path.relpath(name, parent_name)
980
David Pursehousee5913ae2020-02-12 13:56:59 +0900981 def _ParseProject(self, node, parent=None, **extra_proj_attrs):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700982 """
983 reads a <project> element from the manifest file
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700984 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700985 name = self._reqatt(node, 'name')
Mike Frysingera29424e2021-02-25 21:53:49 -0500986 msg = self._CheckLocalPath(name, dir_ok=True)
987 if msg:
988 raise ManifestInvalidPathError(
989 '<project> invalid "name": %s: %s' % (name, msg))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800990 if parent:
991 name = self._JoinName(parent.name, name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700992
993 remote = self._get_remote(node)
994 if remote is None:
995 remote = self._default.remote
996 if remote is None:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530997 raise ManifestParseError("no remote for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +0900998 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700999
Anthony King36ea2fb2014-05-06 11:54:01 +01001000 revisionExpr = node.getAttribute('revision') or remote.revision
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001001 if not revisionExpr:
1002 revisionExpr = self._default.revisionExpr
1003 if not revisionExpr:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301004 raise ManifestParseError("no revision for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001005 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001006
1007 path = node.getAttribute('path')
1008 if not path:
1009 path = name
Mike Frysingera29424e2021-02-25 21:53:49 -05001010 else:
1011 msg = self._CheckLocalPath(path, dir_ok=True)
1012 if msg:
1013 raise ManifestInvalidPathError(
1014 '<project> invalid "path": %s: %s' % (path, msg))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001015
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001016 rebase = XmlBool(node, 'rebase', True)
1017 sync_c = XmlBool(node, 'sync-c', False)
1018 sync_s = XmlBool(node, 'sync-s', self._default.sync_s)
1019 sync_tags = XmlBool(node, 'sync-tags', self._default.sync_tags)
Mike Pontillod3153822012-02-28 11:53:24 -08001020
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001021 clone_depth = XmlInt(node, 'clone-depth')
1022 if clone_depth is not None and clone_depth <= 0:
1023 raise ManifestParseError('%s: clone-depth must be greater than 0, not "%s"' %
1024 (self.manifestFile, clone_depth))
David Pursehouseede7f122012-11-27 22:25:30 +09001025
Bryan Jacobsf609f912013-05-06 13:36:24 -04001026 dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
1027
Nasser Grainawida403412018-05-04 12:53:29 -06001028 upstream = node.getAttribute('upstream') or self._default.upstreamExpr
Brian Harring14a66742012-09-28 20:21:57 -07001029
Conley Owens971de8e2012-04-16 10:36:08 -07001030 groups = ''
1031 if node.hasAttribute('groups'):
1032 groups = node.getAttribute('groups')
Mike Frysinger51e39d52020-12-04 05:32:06 -05001033 groups = self._ParseList(groups)
Brian Harring7da13142012-06-15 02:24:20 -07001034
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001035 if parent is None:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001036 relpath, worktree, gitdir, objdir, use_git_worktrees = \
1037 self.GetProjectPaths(name, path)
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001038 else:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001039 use_git_worktrees = False
David James8d201162013-10-11 17:03:19 -07001040 relpath, worktree, gitdir, objdir = \
1041 self.GetSubprojectPaths(parent, name, path)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001042
1043 default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
1044 groups.extend(set(default_groups).difference(groups))
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001045
Scott Fandb83b1b2013-02-28 09:34:14 +08001046 if self.IsMirror and node.hasAttribute('force-path'):
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001047 if XmlBool(node, 'force-path', False):
Scott Fandb83b1b2013-02-28 09:34:14 +08001048 gitdir = os.path.join(self.topdir, '%s.git' % path)
1049
David Pursehousee5913ae2020-02-12 13:56:59 +09001050 project = Project(manifest=self,
1051 name=name,
1052 remote=remote.ToRemoteSpec(name),
1053 gitdir=gitdir,
1054 objdir=objdir,
1055 worktree=worktree,
1056 relpath=relpath,
1057 revisionExpr=revisionExpr,
1058 revisionId=None,
1059 rebase=rebase,
1060 groups=groups,
1061 sync_c=sync_c,
1062 sync_s=sync_s,
1063 sync_tags=sync_tags,
1064 clone_depth=clone_depth,
1065 upstream=upstream,
1066 parent=parent,
1067 dest_branch=dest_branch,
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001068 use_git_worktrees=use_git_worktrees,
Simran Basib9a1b732015-08-20 12:19:28 -07001069 **extra_proj_attrs)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001070
1071 for n in node.childNodes:
Shawn O. Pearce242b5262009-05-19 13:00:29 -07001072 if n.nodeName == 'copyfile':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001073 self._ParseCopyFile(project, n)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001074 if n.nodeName == 'linkfile':
1075 self._ParseLinkFile(project, n)
James W. Mills24c13082012-04-12 15:04:13 -05001076 if n.nodeName == 'annotation':
1077 self._ParseAnnotation(project, n)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001078 if n.nodeName == 'project':
David Pursehousee5913ae2020-02-12 13:56:59 +09001079 project.subprojects.append(self._ParseProject(n, parent=project))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001080
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001081 return project
1082
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001083 def GetProjectPaths(self, name, path):
Mike Frysingercebf2272020-05-26 01:02:29 -04001084 # The manifest entries might have trailing slashes. Normalize them to avoid
1085 # unexpected filesystem behavior since we do string concatenation below.
1086 path = path.rstrip('/')
1087 name = name.rstrip('/')
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001088 use_git_worktrees = False
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001089 relpath = path
1090 if self.IsMirror:
1091 worktree = None
1092 gitdir = os.path.join(self.topdir, '%s.git' % name)
David James8d201162013-10-11 17:03:19 -07001093 objdir = gitdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001094 else:
1095 worktree = os.path.join(self.topdir, path).replace('\\', '/')
1096 gitdir = os.path.join(self.repodir, 'projects', '%s.git' % path)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001097 # We allow people to mix git worktrees & non-git worktrees for now.
1098 # This allows for in situ migration of repo clients.
1099 if os.path.exists(gitdir) or not self.UseGitWorktrees:
1100 objdir = os.path.join(self.repodir, 'project-objects', '%s.git' % name)
1101 else:
1102 use_git_worktrees = True
1103 gitdir = os.path.join(self.repodir, 'worktrees', '%s.git' % name)
1104 objdir = gitdir
1105 return relpath, worktree, gitdir, objdir, use_git_worktrees
David James8d201162013-10-11 17:03:19 -07001106
1107 def GetProjectsWithName(self, name):
1108 return self._projects.get(name, [])
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001109
1110 def GetSubprojectName(self, parent, submodule_path):
1111 return os.path.join(parent.name, submodule_path)
1112
1113 def _JoinRelpath(self, parent_relpath, relpath):
1114 return os.path.join(parent_relpath, relpath)
1115
1116 def _UnjoinRelpath(self, parent_relpath, relpath):
1117 return os.path.relpath(relpath, parent_relpath)
1118
David James8d201162013-10-11 17:03:19 -07001119 def GetSubprojectPaths(self, parent, name, path):
Mike Frysingercebf2272020-05-26 01:02:29 -04001120 # The manifest entries might have trailing slashes. Normalize them to avoid
1121 # unexpected filesystem behavior since we do string concatenation below.
1122 path = path.rstrip('/')
1123 name = name.rstrip('/')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001124 relpath = self._JoinRelpath(parent.relpath, path)
1125 gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
David James8d201162013-10-11 17:03:19 -07001126 objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001127 if self.IsMirror:
1128 worktree = None
1129 else:
1130 worktree = os.path.join(parent.worktree, path).replace('\\', '/')
David James8d201162013-10-11 17:03:19 -07001131 return relpath, worktree, gitdir, objdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001132
Mike Frysinger04122b72019-07-31 23:32:58 -04001133 @staticmethod
Mike Frysingera00c5f42021-02-25 18:26:31 -05001134 def _CheckLocalPath(path, dir_ok=False, cwd_dot_ok=False):
1135 """Verify |path| is reasonable for use in filesystem paths.
1136
Mike Frysingera29424e2021-02-25 21:53:49 -05001137 Used with <copyfile> & <linkfile> & <project> elements.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001138
1139 This only validates the |path| in isolation: it does not check against the
1140 current filesystem state. Thus it is suitable as a first-past in a parser.
1141
1142 It enforces a number of constraints:
1143 * No empty paths.
1144 * No "~" in paths.
1145 * No Unicode codepoints that filesystems might elide when normalizing.
1146 * No relative path components like "." or "..".
1147 * No absolute paths.
1148 * No ".git" or ".repo*" path components.
1149
1150 Args:
1151 path: The path name to validate.
1152 dir_ok: Whether |path| may force a directory (e.g. end in a /).
1153 cwd_dot_ok: Whether |path| may be just ".".
1154
1155 Returns:
1156 None if |path| is OK, a failure message otherwise.
1157 """
1158 if not path:
1159 return 'empty paths not allowed'
1160
Mike Frysinger04122b72019-07-31 23:32:58 -04001161 if '~' in path:
1162 return '~ not allowed (due to 8.3 filenames on Windows filesystems)'
1163
1164 # Some filesystems (like Apple's HFS+) try to normalize Unicode codepoints
1165 # which means there are alternative names for ".git". Reject paths with
1166 # these in it as there shouldn't be any reasonable need for them here.
1167 # The set of codepoints here was cribbed from jgit's implementation:
1168 # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
1169 BAD_CODEPOINTS = {
1170 u'\u200C', # ZERO WIDTH NON-JOINER
1171 u'\u200D', # ZERO WIDTH JOINER
1172 u'\u200E', # LEFT-TO-RIGHT MARK
1173 u'\u200F', # RIGHT-TO-LEFT MARK
1174 u'\u202A', # LEFT-TO-RIGHT EMBEDDING
1175 u'\u202B', # RIGHT-TO-LEFT EMBEDDING
1176 u'\u202C', # POP DIRECTIONAL FORMATTING
1177 u'\u202D', # LEFT-TO-RIGHT OVERRIDE
1178 u'\u202E', # RIGHT-TO-LEFT OVERRIDE
1179 u'\u206A', # INHIBIT SYMMETRIC SWAPPING
1180 u'\u206B', # ACTIVATE SYMMETRIC SWAPPING
1181 u'\u206C', # INHIBIT ARABIC FORM SHAPING
1182 u'\u206D', # ACTIVATE ARABIC FORM SHAPING
1183 u'\u206E', # NATIONAL DIGIT SHAPES
1184 u'\u206F', # NOMINAL DIGIT SHAPES
1185 u'\uFEFF', # ZERO WIDTH NO-BREAK SPACE
1186 }
1187 if BAD_CODEPOINTS & set(path):
1188 # This message is more expansive than reality, but should be fine.
1189 return 'Unicode combining characters not allowed'
1190
1191 # Assume paths might be used on case-insensitive filesystems.
1192 path = path.lower()
1193
Mike Frysingerd9254592020-02-19 22:36:26 -05001194 # Split up the path by its components. We can't use os.path.sep exclusively
1195 # as some platforms (like Windows) will convert / to \ and that bypasses all
1196 # our constructed logic here. Especially since manifest authors only use
1197 # / in their paths.
1198 resep = re.compile(r'[/%s]' % re.escape(os.path.sep))
1199 parts = resep.split(path)
1200
Mike Frysingerae625412020-02-10 17:10:03 -05001201 # Some people use src="." to create stable links to projects. Lets allow
1202 # that but reject all other uses of "." to keep things simple.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001203 if not cwd_dot_ok or parts != ['.']:
Mike Frysingerae625412020-02-10 17:10:03 -05001204 for part in set(parts):
1205 if part in {'.', '..', '.git'} or part.startswith('.repo'):
1206 return 'bad component: %s' % (part,)
Mike Frysinger04122b72019-07-31 23:32:58 -04001207
Mike Frysingera00c5f42021-02-25 18:26:31 -05001208 if not dir_ok and resep.match(path[-1]):
Mike Frysinger04122b72019-07-31 23:32:58 -04001209 return 'dirs not allowed'
1210
Mike Frysingerd9254592020-02-19 22:36:26 -05001211 # NB: The two abspath checks here are to handle platforms with multiple
1212 # filesystem path styles (e.g. Windows).
Mike Frysinger04122b72019-07-31 23:32:58 -04001213 norm = os.path.normpath(path)
Mike Frysingerd9254592020-02-19 22:36:26 -05001214 if (norm == '..' or
1215 (len(norm) >= 3 and norm.startswith('..') and resep.match(norm[0])) or
1216 os.path.isabs(norm) or
1217 norm.startswith('/')):
Mike Frysinger04122b72019-07-31 23:32:58 -04001218 return 'path cannot be outside'
1219
1220 @classmethod
1221 def _ValidateFilePaths(cls, element, src, dest):
1222 """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
1223
1224 We verify the path independent of any filesystem state as we won't have a
1225 checkout available to compare to. i.e. This is for parsing validation
1226 purposes only.
1227
1228 We'll do full/live sanity checking before we do the actual filesystem
1229 modifications in _CopyFile/_LinkFile/etc...
1230 """
1231 # |dest| is the file we write to or symlink we create.
1232 # It is relative to the top of the repo client checkout.
1233 msg = cls._CheckLocalPath(dest)
1234 if msg:
1235 raise ManifestInvalidPathError(
1236 '<%s> invalid "dest": %s: %s' % (element, dest, msg))
1237
1238 # |src| is the file we read from or path we point to for symlinks.
1239 # It is relative to the top of the git project checkout.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001240 is_linkfile = element == 'linkfile'
1241 msg = cls._CheckLocalPath(src, dir_ok=is_linkfile, cwd_dot_ok=is_linkfile)
Mike Frysinger04122b72019-07-31 23:32:58 -04001242 if msg:
1243 raise ManifestInvalidPathError(
1244 '<%s> invalid "src": %s: %s' % (element, src, msg))
1245
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001246 def _ParseCopyFile(self, project, node):
1247 src = self._reqatt(node, 'src')
1248 dest = self._reqatt(node, 'dest')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001249 if not self.IsMirror:
1250 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001251 # dest is relative to the top of the tree.
1252 # We only validate paths if we actually plan to process them.
1253 self._ValidateFilePaths('copyfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001254 project.AddCopyFile(src, dest, self.topdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001255
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001256 def _ParseLinkFile(self, project, node):
1257 src = self._reqatt(node, 'src')
1258 dest = self._reqatt(node, 'dest')
1259 if not self.IsMirror:
1260 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001261 # dest is relative to the top of the tree.
1262 # We only validate paths if we actually plan to process them.
1263 self._ValidateFilePaths('linkfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001264 project.AddLinkFile(src, dest, self.topdir)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001265
James W. Mills24c13082012-04-12 15:04:13 -05001266 def _ParseAnnotation(self, project, node):
1267 name = self._reqatt(node, 'name')
1268 value = self._reqatt(node, 'value')
1269 try:
1270 keep = self._reqatt(node, 'keep').lower()
1271 except ManifestParseError:
1272 keep = "true"
1273 if keep != "true" and keep != "false":
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301274 raise ManifestParseError('optional "keep" attribute must be '
David Pursehouseabdf7502020-02-12 14:58:39 +09001275 '"true" or "false"')
James W. Mills24c13082012-04-12 15:04:13 -05001276 project.AddAnnotation(name, value, keep)
1277
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001278 def _get_remote(self, node):
1279 name = node.getAttribute('remote')
1280 if not name:
1281 return None
1282
1283 v = self._remotes.get(name)
1284 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301285 raise ManifestParseError("remote %s not defined in %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001286 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001287 return v
1288
1289 def _reqatt(self, node, attname):
1290 """
1291 reads a required attribute from the node.
1292 """
1293 v = node.getAttribute(attname)
1294 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301295 raise ManifestParseError("no %s in <%s> within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001296 (attname, node.nodeName, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001297 return v
Julien Camperguedd654222014-01-09 16:21:37 +01001298
1299 def projectsDiff(self, manifest):
1300 """return the projects differences between two manifests.
1301
1302 The diff will be from self to given manifest.
1303
1304 """
1305 fromProjects = self.paths
1306 toProjects = manifest.paths
1307
Anthony King7446c592014-05-06 09:19:39 +01001308 fromKeys = sorted(fromProjects.keys())
1309 toKeys = sorted(toProjects.keys())
Julien Camperguedd654222014-01-09 16:21:37 +01001310
1311 diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
1312
1313 for proj in fromKeys:
David Pursehouseeeff3532020-02-12 11:24:10 +09001314 if proj not in toKeys:
Julien Camperguedd654222014-01-09 16:21:37 +01001315 diff['removed'].append(fromProjects[proj])
1316 else:
1317 fromProj = fromProjects[proj]
1318 toProj = toProjects[proj]
1319 try:
1320 fromRevId = fromProj.GetCommitRevisionId()
1321 toRevId = toProj.GetCommitRevisionId()
1322 except ManifestInvalidRevisionError:
1323 diff['unreachable'].append((fromProj, toProj))
1324 else:
1325 if fromRevId != toRevId:
1326 diff['changed'].append((fromProj, toProj))
1327 toKeys.remove(proj)
1328
1329 for proj in toKeys:
1330 diff['added'].append(toProjects[proj])
1331
1332 return diff
Simran Basib9a1b732015-08-20 12:19:28 -07001333
1334
1335class GitcManifest(XmlManifest):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001336 """Parser for GitC (git-in-the-cloud) manifests."""
Simran Basib9a1b732015-08-20 12:19:28 -07001337
David Pursehousee5913ae2020-02-12 13:56:59 +09001338 def _ParseProject(self, node, parent=None):
Simran Basib9a1b732015-08-20 12:19:28 -07001339 """Override _ParseProject and add support for GITC specific attributes."""
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001340 return super()._ParseProject(
Simran Basib9a1b732015-08-20 12:19:28 -07001341 node, parent=parent, old_revision=node.getAttribute('old-revision'))
1342
1343 def _output_manifest_project_extras(self, p, e):
1344 """Output GITC Specific Project attributes"""
1345 if p.old_revision:
Stefan Beller66851062016-06-17 16:40:08 -07001346 e.setAttribute('old-revision', str(p.old_revision))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001347
1348
1349class RepoClient(XmlManifest):
1350 """Manages a repo client checkout."""
1351
1352 def __init__(self, repodir, manifest_file=None):
1353 self.isGitcClient = False
1354
1355 if os.path.exists(os.path.join(repodir, LOCAL_MANIFEST_NAME)):
1356 print('error: %s is not supported; put local manifests in `%s` instead' %
1357 (LOCAL_MANIFEST_NAME, os.path.join(repodir, LOCAL_MANIFESTS_DIR_NAME)),
1358 file=sys.stderr)
1359 sys.exit(1)
1360
1361 if manifest_file is None:
1362 manifest_file = os.path.join(repodir, MANIFEST_FILE_NAME)
1363 local_manifests = os.path.abspath(os.path.join(repodir, LOCAL_MANIFESTS_DIR_NAME))
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001364 super().__init__(repodir, manifest_file, local_manifests)
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001365
1366 # TODO: Completely separate manifest logic out of the client.
1367 self.manifest = self
1368
1369
1370class GitcClient(RepoClient, GitcManifest):
1371 """Manages a GitC client checkout."""
1372
1373 def __init__(self, repodir, gitc_client_name):
1374 """Initialize the GitcManifest object."""
1375 self.gitc_client_name = gitc_client_name
1376 self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
1377 gitc_client_name)
1378
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001379 super().__init__(repodir, os.path.join(self.gitc_client_dir, '.manifest'))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001380 self.isGitcClient = True