blob: 64b7fb4e15e041bcadbbafd13078b1bb644e4554 [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
Raman Tenneti080877e2021-03-09 15:19:06 -080017import platform
Conley Owensdb728cd2011-09-26 16:34:01 -070018import re
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070019import sys
David Pursehouse59bbb582013-05-17 10:49:33 +090020import xml.dom.minidom
Mike Frysingeracf63b22019-06-13 02:24:21 -040021import urllib.parse
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070022
Simran Basib9a1b732015-08-20 12:19:28 -070023import gitc_utils
Miguel Gaio1f207762020-07-17 14:09:13 +020024from git_config import GitConfig, IsId
David Pursehousee00aa6b2012-09-11 14:33:51 +090025from git_refs import R_HEADS, HEAD
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070026import platform_utils
David Pursehousee00aa6b2012-09-11 14:33:51 +090027from project import RemoteSpec, Project, MetaProject
Mike Frysinger04122b72019-07-31 23:32:58 -040028from error import (ManifestParseError, ManifestInvalidPathError,
29 ManifestInvalidRevisionError)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070030
31MANIFEST_FILE_NAME = 'manifest.xml'
Shawn O. Pearce5cc66792008-10-23 16:19:27 -070032LOCAL_MANIFEST_NAME = 'local_manifest.xml'
David Pursehouse2d5a0df2012-11-13 02:50:36 +090033LOCAL_MANIFESTS_DIR_NAME = 'local_manifests'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070034
Anthony Kingcb07ba72015-03-28 23:26:04 +000035# urljoin gets confused if the scheme is not known.
Joe Kilner6e310792016-10-27 15:53:53 -070036urllib.parse.uses_relative.extend([
37 'ssh',
38 'git',
39 'persistent-https',
40 'sso',
41 'rpc'])
42urllib.parse.uses_netloc.extend([
43 'ssh',
44 'git',
45 'persistent-https',
46 'sso',
47 'rpc'])
Conley Owensdb728cd2011-09-26 16:34:01 -070048
David Pursehouse819827a2020-02-12 15:20:19 +090049
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050050def XmlBool(node, attr, default=None):
51 """Determine boolean value of |node|'s |attr|.
52
53 Invalid values will issue a non-fatal warning.
54
55 Args:
56 node: XML node whose attributes we access.
57 attr: The attribute to access.
58 default: If the attribute is not set (value is empty), then use this.
59
60 Returns:
61 True if the attribute is a valid string representing true.
62 False if the attribute is a valid string representing false.
63 |default| otherwise.
64 """
65 value = node.getAttribute(attr)
66 s = value.lower()
67 if s == '':
68 return default
69 elif s in {'yes', 'true', '1'}:
70 return True
71 elif s in {'no', 'false', '0'}:
72 return False
73 else:
74 print('warning: manifest: %s="%s": ignoring invalid XML boolean' %
75 (attr, value), file=sys.stderr)
76 return default
77
78
79def XmlInt(node, attr, default=None):
80 """Determine integer value of |node|'s |attr|.
81
82 Args:
83 node: XML node whose attributes we access.
84 attr: The attribute to access.
85 default: If the attribute is not set (value is empty), then use this.
86
87 Returns:
88 The number if the attribute is a valid number.
89
90 Raises:
91 ManifestParseError: The number is invalid.
92 """
93 value = node.getAttribute(attr)
94 if not value:
95 return default
96
97 try:
98 return int(value)
99 except ValueError:
100 raise ManifestParseError('manifest: invalid %s="%s" integer' %
101 (attr, value))
102
103
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700104class _Default(object):
105 """Project defaults within the manifest."""
106
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700107 revisionExpr = None
Conley Owensb6a16e62013-09-25 15:06:09 -0700108 destBranchExpr = None
Nasser Grainawida403412018-05-04 12:53:29 -0600109 upstreamExpr = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700110 remote = None
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700111 sync_j = 1
Anatol Pomazau79770d22012-04-20 14:41:59 -0700112 sync_c = False
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800113 sync_s = False
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900114 sync_tags = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700115
Julien Campergue74879922013-10-09 14:38:46 +0200116 def __eq__(self, other):
117 return self.__dict__ == other.__dict__
118
119 def __ne__(self, other):
120 return self.__dict__ != other.__dict__
121
David Pursehouse819827a2020-02-12 15:20:19 +0900122
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700123class _XmlRemote(object):
124 def __init__(self,
125 name,
Yestin Sunb292b982012-07-02 07:32:50 -0700126 alias=None,
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700127 fetch=None,
Steve Raed6480452016-08-10 15:00:00 -0700128 pushUrl=None,
Conley Owensdb728cd2011-09-26 16:34:01 -0700129 manifestUrl=None,
Anthony King36ea2fb2014-05-06 11:54:01 +0100130 review=None,
Jonathan Nieder93719792015-03-17 11:29:58 -0700131 revision=None):
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700132 self.name = name
133 self.fetchUrl = fetch
Steve Raed6480452016-08-10 15:00:00 -0700134 self.pushUrl = pushUrl
Conley Owensdb728cd2011-09-26 16:34:01 -0700135 self.manifestUrl = manifestUrl
Yestin Sunb292b982012-07-02 07:32:50 -0700136 self.remoteAlias = alias
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700137 self.reviewUrl = review
Anthony King36ea2fb2014-05-06 11:54:01 +0100138 self.revision = revision
Conley Owensceea3682011-10-20 10:45:47 -0700139 self.resolvedFetchUrl = self._resolveFetchUrl()
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700140
David Pursehouse717ece92012-11-13 08:49:16 +0900141 def __eq__(self, other):
142 return self.__dict__ == other.__dict__
143
144 def __ne__(self, other):
145 return self.__dict__ != other.__dict__
146
Conley Owensceea3682011-10-20 10:45:47 -0700147 def _resolveFetchUrl(self):
148 url = self.fetchUrl.rstrip('/')
Conley Owensdb728cd2011-09-26 16:34:01 -0700149 manifestUrl = self.manifestUrl.rstrip('/')
Conley Owens2d0f5082014-01-31 15:03:51 -0800150 # urljoin will gets confused over quite a few things. The ones we care
151 # about here are:
152 # * no scheme in the base url, like <hostname:port>
Anthony Kingcb07ba72015-03-28 23:26:04 +0000153 # We handle no scheme by replacing it with an obscure protocol, gopher
154 # and then replacing it with the original when we are done.
155
Conley Owensdb728cd2011-09-26 16:34:01 -0700156 if manifestUrl.find(':') != manifestUrl.find('/') - 1:
Conley Owens4ccad752015-04-29 10:45:37 -0700157 url = urllib.parse.urljoin('gopher://' + manifestUrl, url)
158 url = re.sub(r'^gopher://', '', url)
Anthony Kingcb07ba72015-03-28 23:26:04 +0000159 else:
160 url = urllib.parse.urljoin(manifestUrl, url)
Shawn Pearcea9f11b32013-01-02 15:40:48 -0800161 return url
Conley Owensceea3682011-10-20 10:45:47 -0700162
163 def ToRemoteSpec(self, projectName):
David Rileye0684ad2017-04-05 00:02:59 -0700164 fetchUrl = self.resolvedFetchUrl.rstrip('/')
165 url = fetchUrl + '/' + projectName
Yestin Sunb292b982012-07-02 07:32:50 -0700166 remoteName = self.name
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700167 if self.remoteAlias:
David Pursehouse37128b62013-10-15 10:48:40 +0900168 remoteName = self.remoteAlias
Dan Willemsen96c2d652016-04-06 16:03:54 -0700169 return RemoteSpec(remoteName,
170 url=url,
Steve Raed6480452016-08-10 15:00:00 -0700171 pushUrl=self.pushUrl,
Dan Willemsen96c2d652016-04-06 16:03:54 -0700172 review=self.reviewUrl,
David Rileye0684ad2017-04-05 00:02:59 -0700173 orig_name=self.name,
174 fetchUrl=self.fetchUrl)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700175
David Pursehouse819827a2020-02-12 15:20:19 +0900176
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700177class XmlManifest(object):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700178 """manages the repo configuration file"""
179
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400180 def __init__(self, repodir, manifest_file, local_manifests=None):
181 """Initialize.
182
183 Args:
184 repodir: Path to the .repo/ dir for holding all internal checkout state.
185 It must be in the top directory of the repo client checkout.
186 manifest_file: Full path to the manifest file to parse. This will usually
187 be |repodir|/|MANIFEST_FILE_NAME|.
188 local_manifests: Full path to the directory of local override manifests.
189 This will usually be |repodir|/|LOCAL_MANIFESTS_DIR_NAME|.
190 """
191 # TODO(vapier): Move this out of this class.
192 self.globalConfig = GitConfig.ForUser()
193
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700194 self.repodir = os.path.abspath(repodir)
195 self.topdir = os.path.dirname(self.repodir)
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400196 self.manifestFile = manifest_file
197 self.local_manifests = local_manifests
Basil Gelloc7453502018-05-25 20:23:52 +0300198 self._load_local_manifests = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700199
200 self.repoProject = MetaProject(self, 'repo',
David Pursehouseabdf7502020-02-12 14:58:39 +0900201 gitdir=os.path.join(repodir, 'repo/.git'),
202 worktree=os.path.join(repodir, 'repo'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700203
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500204 mp = MetaProject(self, 'manifests',
205 gitdir=os.path.join(repodir, 'manifests.git'),
206 worktree=os.path.join(repodir, 'manifests'))
207 self.manifestProject = mp
208
209 # This is a bit hacky, but we're in a chicken & egg situation: all the
210 # normal repo settings live in the manifestProject which we just setup
211 # above, so we couldn't easily query before that. We assume Project()
212 # init doesn't care if this changes afterwards.
Mike Frysingerd957ec62020-02-24 14:40:25 -0500213 if os.path.exists(mp.gitdir) and mp.config.GetBoolean('repo.worktree'):
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500214 mp.use_git_worktrees = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700215
216 self._Unload()
217
Basil Gelloc7453502018-05-25 20:23:52 +0300218 def Override(self, name, load_local_manifests=True):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700219 """Use a different manifest, just for the current instantiation.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700220 """
Basil Gelloc7453502018-05-25 20:23:52 +0300221 path = None
222
223 # Look for a manifest by path in the filesystem (including the cwd).
224 if not load_local_manifests:
225 local_path = os.path.abspath(name)
226 if os.path.isfile(local_path):
227 path = local_path
228
229 # Look for manifests by name from the manifests repo.
230 if path is None:
231 path = os.path.join(self.manifestProject.worktree, name)
232 if not os.path.isfile(path):
233 raise ManifestParseError('manifest %s not found' % name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700234
235 old = self.manifestFile
236 try:
Basil Gelloc7453502018-05-25 20:23:52 +0300237 self._load_local_manifests = load_local_manifests
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700238 self.manifestFile = path
239 self._Unload()
240 self._Load()
241 finally:
242 self.manifestFile = old
243
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700244 def Link(self, name):
245 """Update the repo metadata to use a different manifest.
246 """
247 self.Override(name)
248
Mike Frysingera269b1c2020-02-21 00:49:41 -0500249 # Old versions of repo would generate symlinks we need to clean up.
250 if os.path.lexists(self.manifestFile):
251 platform_utils.remove(self.manifestFile)
252 # This file is interpreted as if it existed inside the manifest repo.
253 # That allows us to use <include> with the relative file name.
254 with open(self.manifestFile, 'w') as fp:
255 fp.write("""<?xml version="1.0" encoding="UTF-8"?>
256<!--
257DO NOT EDIT THIS FILE! It is generated by repo and changes will be discarded.
258If you want to use a different manifest, use `repo init -m <file>` instead.
259
260If you want to customize your checkout by overriding manifest settings, use
261the local_manifests/ directory instead.
262
263For more information on repo manifests, check out:
264https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
265-->
266<manifest>
267 <include name="%s" />
268</manifest>
269""" % (name,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700270
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800271 def _RemoteToXml(self, r, doc, root):
272 e = doc.createElement('remote')
273 root.appendChild(e)
274 e.setAttribute('name', r.name)
275 e.setAttribute('fetch', r.fetchUrl)
Steve Raed6480452016-08-10 15:00:00 -0700276 if r.pushUrl is not None:
277 e.setAttribute('pushurl', r.pushUrl)
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700278 if r.remoteAlias is not None:
279 e.setAttribute('alias', r.remoteAlias)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800280 if r.reviewUrl is not None:
281 e.setAttribute('review', r.reviewUrl)
Anthony King36ea2fb2014-05-06 11:54:01 +0100282 if r.revision is not None:
283 e.setAttribute('revision', r.revision)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800284
Mike Frysinger51e39d52020-12-04 05:32:06 -0500285 def _ParseList(self, field):
286 """Parse fields that contain flattened lists.
287
288 These are whitespace & comma separated. Empty elements will be discarded.
289 """
290 return [x for x in re.split(r'[,\s]+', field) if x]
Josh Triplett884a3872014-06-12 14:57:29 -0700291
Mike Frysinger23411d32020-09-02 04:31:10 -0400292 def ToXml(self, peg_rev=False, peg_rev_upstream=True, peg_rev_dest_branch=True, groups=None):
293 """Return the current manifest XML."""
Colin Cross5acde752012-03-28 20:15:45 -0700294 mp = self.manifestProject
295
Dan Willemsen5ea32d12015-09-08 13:27:20 -0700296 if groups is None:
297 groups = mp.config.GetString('manifest.groups')
Matt Gumbel0c635bb2012-12-21 10:14:53 -0800298 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -0500299 groups = self._ParseList(groups)
Colin Cross5acde752012-03-28 20:15:45 -0700300
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800301 doc = xml.dom.minidom.Document()
302 root = doc.createElement('manifest')
303 doc.appendChild(root)
304
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700305 # Save out the notice. There's a little bit of work here to give it the
306 # right whitespace, which assumes that the notice is automatically indented
307 # by 4 by minidom.
308 if self.notice:
309 notice_element = root.appendChild(doc.createElement('notice'))
310 notice_lines = self.notice.splitlines()
David Pursehouse54a4e602020-02-12 14:31:05 +0900311 indented_notice = ('\n'.join(" " * 4 + line for line in notice_lines))[4:]
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700312 notice_element.appendChild(doc.createTextNode(indented_notice))
313
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800314 d = self.default
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800315
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530316 for r in sorted(self.remotes):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800317 self._RemoteToXml(self.remotes[r], doc, root)
318 if self.remotes:
319 root.appendChild(doc.createTextNode(''))
320
321 have_default = False
322 e = doc.createElement('default')
323 if d.remote:
324 have_default = True
325 e.setAttribute('remote', d.remote.name)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700326 if d.revisionExpr:
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800327 have_default = True
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700328 e.setAttribute('revision', d.revisionExpr)
Simon Ruggier7e59de22015-07-24 12:50:06 +0200329 if d.destBranchExpr:
330 have_default = True
331 e.setAttribute('dest-branch', d.destBranchExpr)
Nasser Grainawida403412018-05-04 12:53:29 -0600332 if d.upstreamExpr:
333 have_default = True
334 e.setAttribute('upstream', d.upstreamExpr)
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700335 if d.sync_j > 1:
336 have_default = True
337 e.setAttribute('sync-j', '%d' % d.sync_j)
Anatol Pomazau79770d22012-04-20 14:41:59 -0700338 if d.sync_c:
339 have_default = True
340 e.setAttribute('sync-c', 'true')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800341 if d.sync_s:
342 have_default = True
343 e.setAttribute('sync-s', 'true')
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900344 if not d.sync_tags:
345 have_default = True
346 e.setAttribute('sync-tags', 'false')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800347 if have_default:
348 root.appendChild(e)
349 root.appendChild(doc.createTextNode(''))
350
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700351 if self._manifest_server:
352 e = doc.createElement('manifest-server')
353 e.setAttribute('url', self._manifest_server)
354 root.appendChild(e)
355 root.appendChild(doc.createTextNode(''))
356
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800357 def output_projects(parent, parent_node, projects):
David James8d201162013-10-11 17:03:19 -0700358 for project_name in projects:
359 for project in self._projects[project_name]:
360 output_project(parent, parent_node, project)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800361
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800362 def output_project(parent, parent_node, p):
Colin Cross5acde752012-03-28 20:15:45 -0700363 if not p.MatchesGroups(groups):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800364 return
365
366 name = p.name
367 relpath = p.relpath
368 if parent:
369 name = self._UnjoinName(parent.name, name)
370 relpath = self._UnjoinRelpath(parent.relpath, relpath)
Colin Cross5acde752012-03-28 20:15:45 -0700371
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800372 e = doc.createElement('project')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800373 parent_node.appendChild(e)
374 e.setAttribute('name', name)
375 if relpath != name:
376 e.setAttribute('path', relpath)
Conley Owensa17d7af2013-10-16 14:38:09 -0700377 remoteName = None
378 if d.remote:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700379 remoteName = d.remote.name
380 if not d.remote or p.remote.orig_name != remoteName:
381 remoteName = p.remote.orig_name
Anthony King36ea2fb2014-05-06 11:54:01 +0100382 e.setAttribute('remote', remoteName)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800383 if peg_rev:
384 if self.IsMirror:
Brian Harring14a66742012-09-28 20:21:57 -0700385 value = p.bare_git.rev_parse(p.revisionExpr + '^0')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800386 else:
Brian Harring14a66742012-09-28 20:21:57 -0700387 value = p.work_git.rev_parse(HEAD + '^0')
388 e.setAttribute('revision', value)
Conley Owens551dfec2015-07-10 14:54:54 -0700389 if peg_rev_upstream:
390 if p.upstream:
391 e.setAttribute('upstream', p.upstream)
392 elif value != p.revisionExpr:
393 # Only save the origin if the origin is not a sha1, and the default
394 # isn't our value
395 e.setAttribute('upstream', p.revisionExpr)
Sean McAllisteraf908cb2020-04-20 08:41:58 -0600396
397 if peg_rev_dest_branch:
398 if p.dest_branch:
399 e.setAttribute('dest-branch', p.dest_branch)
400 elif value != p.revisionExpr:
401 e.setAttribute('dest-branch', p.revisionExpr)
402
Anthony King36ea2fb2014-05-06 11:54:01 +0100403 else:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700404 revision = self.remotes[p.remote.orig_name].revision or d.revisionExpr
Anthony King36ea2fb2014-05-06 11:54:01 +0100405 if not revision or revision != p.revisionExpr:
406 e.setAttribute('revision', p.revisionExpr)
Raman Tennetib5c5a5e2021-02-06 09:44:15 -0800407 elif p.revisionId:
408 e.setAttribute('revision', p.revisionId)
Nasser Grainawida403412018-05-04 12:53:29 -0600409 if (p.upstream and (p.upstream != p.revisionExpr or
410 p.upstream != d.upstreamExpr)):
Mani Chandel7a91d512014-07-24 16:27:08 +0530411 e.setAttribute('upstream', p.upstream)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800412
Simon Ruggier7e59de22015-07-24 12:50:06 +0200413 if p.dest_branch and p.dest_branch != d.destBranchExpr:
414 e.setAttribute('dest-branch', p.dest_branch)
415
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800416 for c in p.copyfiles:
417 ce = doc.createElement('copyfile')
418 ce.setAttribute('src', c.src)
419 ce.setAttribute('dest', c.dest)
420 e.appendChild(ce)
421
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500422 for l in p.linkfiles:
423 le = doc.createElement('linkfile')
424 le.setAttribute('src', l.src)
425 le.setAttribute('dest', l.dest)
426 e.appendChild(le)
427
Conley Owensbb1b5f52012-08-13 13:11:18 -0700428 default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
Dmitry Fink17f85ea2012-08-06 14:52:29 -0700429 egroups = [g for g in p.groups if g not in default_groups]
Conley Owens971de8e2012-04-16 10:36:08 -0700430 if egroups:
431 e.setAttribute('groups', ','.join(egroups))
Colin Cross5acde752012-03-28 20:15:45 -0700432
James W. Mills24c13082012-04-12 15:04:13 -0500433 for a in p.annotations:
434 if a.keep == "true":
435 ae = doc.createElement('annotation')
436 ae.setAttribute('name', a.name)
437 ae.setAttribute('value', a.value)
438 e.appendChild(ae)
439
Anatol Pomazau79770d22012-04-20 14:41:59 -0700440 if p.sync_c:
441 e.setAttribute('sync-c', 'true')
442
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800443 if p.sync_s:
444 e.setAttribute('sync-s', 'true')
445
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900446 if not p.sync_tags:
447 e.setAttribute('sync-tags', 'false')
448
Dan Willemsen88409222015-08-17 15:29:10 -0700449 if p.clone_depth:
450 e.setAttribute('clone-depth', str(p.clone_depth))
451
Simran Basib9a1b732015-08-20 12:19:28 -0700452 self._output_manifest_project_extras(p, e)
453
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800454 if p.subprojects:
David James8d201162013-10-11 17:03:19 -0700455 subprojects = set(subp.name for subp in p.subprojects)
456 output_projects(p, e, list(sorted(subprojects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800457
David James8d201162013-10-11 17:03:19 -0700458 projects = set(p.name for p in self._paths.values() if not p.parent)
459 output_projects(None, root, list(sorted(projects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800460
Doug Anderson37282b42011-03-04 11:54:18 -0800461 if self._repo_hooks_project:
462 root.appendChild(doc.createTextNode(''))
463 e = doc.createElement('repo-hooks')
464 e.setAttribute('in-project', self._repo_hooks_project.name)
465 e.setAttribute('enabled-list',
466 ' '.join(self._repo_hooks_project.enabled_repo_hooks))
467 root.appendChild(e)
468
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800469 if self._superproject:
470 root.appendChild(doc.createTextNode(''))
471 e = doc.createElement('superproject')
472 e.setAttribute('name', self._superproject['name'])
473 remoteName = None
474 if d.remote:
475 remoteName = d.remote.name
476 remote = self._superproject.get('remote')
477 if not d.remote or remote.orig_name != remoteName:
478 remoteName = remote.orig_name
479 e.setAttribute('remote', remoteName)
480 root.appendChild(e)
481
Mike Frysinger23411d32020-09-02 04:31:10 -0400482 return doc
483
484 def ToDict(self, **kwargs):
485 """Return the current manifest as a dictionary."""
486 # Elements that may only appear once.
487 SINGLE_ELEMENTS = {
488 'notice',
489 'default',
490 'manifest-server',
491 'repo-hooks',
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800492 'superproject',
Mike Frysinger23411d32020-09-02 04:31:10 -0400493 }
494 # Elements that may be repeated.
495 MULTI_ELEMENTS = {
496 'remote',
497 'remove-project',
498 'project',
499 'extend-project',
500 'include',
501 # These are children of 'project' nodes.
502 'annotation',
503 'project',
504 'copyfile',
505 'linkfile',
506 }
507
508 doc = self.ToXml(**kwargs)
509 ret = {}
510
511 def append_children(ret, node):
512 for child in node.childNodes:
513 if child.nodeType == xml.dom.Node.ELEMENT_NODE:
514 attrs = child.attributes
515 element = dict((attrs.item(i).localName, attrs.item(i).value)
516 for i in range(attrs.length))
517 if child.nodeName in SINGLE_ELEMENTS:
518 ret[child.nodeName] = element
519 elif child.nodeName in MULTI_ELEMENTS:
520 ret.setdefault(child.nodeName, []).append(element)
521 else:
522 raise ManifestParseError('Unhandled element "%s"' % (child.nodeName,))
523
524 append_children(element, child)
525
526 append_children(ret, doc.firstChild)
527
528 return ret
529
530 def Save(self, fd, **kwargs):
531 """Write the current manifest out to the given file descriptor."""
532 doc = self.ToXml(**kwargs)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800533 doc.writexml(fd, '', ' ', '\n', 'UTF-8')
534
Simran Basib9a1b732015-08-20 12:19:28 -0700535 def _output_manifest_project_extras(self, p, e):
536 """Manifests can modify e if they support extra project attributes."""
Simran Basib9a1b732015-08-20 12:19:28 -0700537
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700538 @property
David James8d201162013-10-11 17:03:19 -0700539 def paths(self):
540 self._Load()
541 return self._paths
542
543 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700544 def projects(self):
545 self._Load()
Anthony Kingd58bfe52014-05-05 23:30:49 +0100546 return list(self._paths.values())
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700547
548 @property
549 def remotes(self):
550 self._Load()
551 return self._remotes
552
553 @property
554 def default(self):
555 self._Load()
556 return self._default
557
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800558 @property
Doug Anderson37282b42011-03-04 11:54:18 -0800559 def repo_hooks_project(self):
560 self._Load()
561 return self._repo_hooks_project
562
563 @property
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800564 def superproject(self):
565 self._Load()
566 return self._superproject
567
568 @property
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700569 def notice(self):
570 self._Load()
571 return self._notice
572
573 @property
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700574 def manifest_server(self):
575 self._Load()
Shawn O. Pearce34fb20f2011-11-30 13:41:02 -0800576 return self._manifest_server
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700577
578 @property
Xin Lid79a4bc2020-05-20 16:03:45 -0700579 def CloneBundle(self):
580 clone_bundle = self.manifestProject.config.GetBoolean('repo.clonebundle')
581 if clone_bundle is None:
582 return False if self.manifestProject.config.GetBoolean('repo.partialclone') else True
583 else:
584 return clone_bundle
585
586 @property
Xin Li745be2e2019-06-03 11:24:30 -0700587 def CloneFilter(self):
588 if self.manifestProject.config.GetBoolean('repo.partialclone'):
589 return self.manifestProject.config.GetString('repo.clonefilter')
590 return None
591
592 @property
Raman Tennetif32f2432021-04-12 20:57:25 -0700593 def PartialCloneExclude(self):
594 exclude = self.manifest.manifestProject.config.GetString(
595 'repo.partialcloneexclude') or ''
596 return set(x.strip() for x in exclude.split(','))
597
598 @property
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800599 def IsMirror(self):
600 return self.manifestProject.config.GetBoolean('repo.mirror')
601
Julien Campergue335f5ef2013-10-16 11:02:35 +0200602 @property
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500603 def UseGitWorktrees(self):
604 return self.manifestProject.config.GetBoolean('repo.worktree')
605
606 @property
Julien Campergue335f5ef2013-10-16 11:02:35 +0200607 def IsArchive(self):
608 return self.manifestProject.config.GetBoolean('repo.archive')
609
Martin Kellye4e94d22017-03-21 16:05:12 -0700610 @property
611 def HasSubmodules(self):
612 return self.manifestProject.config.GetBoolean('repo.submodules')
613
Raman Tenneti080877e2021-03-09 15:19:06 -0800614 def GetDefaultGroupsStr(self):
615 """Returns the default group string for the platform."""
616 return 'default,platform-' + platform.system().lower()
617
618 def GetGroupsStr(self):
619 """Returns the manifest group string that should be synced."""
620 groups = self.manifestProject.config.GetString('manifest.groups')
621 if not groups:
622 groups = self.GetDefaultGroupsStr()
623 return groups
624
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700625 def _Unload(self):
626 self._loaded = False
627 self._projects = {}
David James8d201162013-10-11 17:03:19 -0700628 self._paths = {}
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700629 self._remotes = {}
630 self._default = None
Doug Anderson37282b42011-03-04 11:54:18 -0800631 self._repo_hooks_project = None
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800632 self._superproject = {}
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700633 self._notice = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700634 self.branch = None
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700635 self._manifest_server = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700636
637 def _Load(self):
638 if not self._loaded:
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800639 m = self.manifestProject
640 b = m.GetBranch(m.CurrentBranch).merge
Shawn O. Pearce21c5c342009-06-25 16:47:30 -0700641 if b is not None and b.startswith(R_HEADS):
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800642 b = b[len(R_HEADS):]
643 self.branch = b
644
Mike Frysinger54133972021-03-01 21:38:08 -0500645 # The manifestFile was specified by the user which is why we allow include
646 # paths to point anywhere.
Colin Cross23acdd32012-04-21 00:33:54 -0700647 nodes = []
Mike Frysinger54133972021-03-01 21:38:08 -0500648 nodes.append(self._ParseManifestXml(
649 self.manifestFile, self.manifestProject.worktree,
650 restrict_includes=False))
Shawn O. Pearce5cc66792008-10-23 16:19:27 -0700651
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400652 if self._load_local_manifests and self.local_manifests:
Basil Gelloc7453502018-05-25 20:23:52 +0300653 try:
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400654 for local_file in sorted(platform_utils.listdir(self.local_manifests)):
Basil Gelloc7453502018-05-25 20:23:52 +0300655 if local_file.endswith('.xml'):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400656 local = os.path.join(self.local_manifests, local_file)
Mike Frysinger54133972021-03-01 21:38:08 -0500657 # Since local manifests are entirely managed by the user, allow
658 # them to point anywhere the user wants.
659 nodes.append(self._ParseManifestXml(
660 local, self.repodir, restrict_includes=False))
Basil Gelloc7453502018-05-25 20:23:52 +0300661 except OSError:
662 pass
David Pursehouse2d5a0df2012-11-13 02:50:36 +0900663
Joe Onorato26e24752013-01-11 12:35:53 -0800664 try:
665 self._ParseManifest(nodes)
666 except ManifestParseError as e:
667 # There was a problem parsing, unload ourselves in case they catch
668 # this error and try again later, we will show the correct error
669 self._Unload()
670 raise e
Shawn O. Pearce5cc66792008-10-23 16:19:27 -0700671
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800672 if self.IsMirror:
673 self._AddMetaProjectMirror(self.repoProject)
674 self._AddMetaProjectMirror(self.manifestProject)
675
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700676 self._loaded = True
677
Mike Frysinger54133972021-03-01 21:38:08 -0500678 def _ParseManifestXml(self, path, include_root, parent_groups='',
679 restrict_includes=True):
680 """Parse a manifest XML and return the computed nodes.
681
682 Args:
683 path: The XML file to read & parse.
684 include_root: The path to interpret include "name"s relative to.
685 parent_groups: The groups to apply to this projects.
686 restrict_includes: Whether to constrain the "name" attribute of includes.
687
688 Returns:
689 List of XML nodes.
690 """
David Pursehousef7fc8a92012-11-13 04:00:28 +0900691 try:
692 root = xml.dom.minidom.parse(path)
David Pursehouse2d5a0df2012-11-13 02:50:36 +0900693 except (OSError, xml.parsers.expat.ExpatError) as e:
David Pursehousef7fc8a92012-11-13 04:00:28 +0900694 raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
695
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700696 if not root or not root.childNodes:
Brian Harring26448742011-04-28 05:04:41 -0700697 raise ManifestParseError("no root node in %s" % (path,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700698
Jooncheol Park34acdd22012-08-27 02:25:59 +0900699 for manifest in root.childNodes:
700 if manifest.nodeName == 'manifest':
701 break
702 else:
Brian Harring26448742011-04-28 05:04:41 -0700703 raise ManifestParseError("no <manifest> in %s" % (path,))
704
Colin Cross23acdd32012-04-21 00:33:54 -0700705 nodes = []
David Pursehouse65b0ba52018-06-24 16:21:51 +0900706 for node in manifest.childNodes:
David Pursehousec1b86a22012-11-14 11:36:51 +0900707 if node.nodeName == 'include':
708 name = self._reqatt(node, 'name')
Mike Frysinger54133972021-03-01 21:38:08 -0500709 if restrict_includes:
710 msg = self._CheckLocalPath(name)
711 if msg:
712 raise ManifestInvalidPathError(
713 '<include> invalid "name": %s: %s' % (name, msg))
Fredrik de Groot352c93b2020-10-06 12:55:14 +0200714 include_groups = ''
715 if parent_groups:
716 include_groups = parent_groups
717 if node.hasAttribute('groups'):
718 include_groups = node.getAttribute('groups') + ',' + include_groups
David Pursehousec1b86a22012-11-14 11:36:51 +0900719 fp = os.path.join(include_root, name)
720 if not os.path.isfile(fp):
Mike Frysinger54133972021-03-01 21:38:08 -0500721 raise ManifestParseError("include [%s/]%s doesn't exist or isn't a file"
722 % (include_root, name))
David Pursehousec1b86a22012-11-14 11:36:51 +0900723 try:
Fredrik de Groot352c93b2020-10-06 12:55:14 +0200724 nodes.extend(self._ParseManifestXml(fp, include_root, include_groups))
David Pursehousec1b86a22012-11-14 11:36:51 +0900725 # should isolate this to the exact exception, but that's
726 # tricky. actual parsing implementation may vary.
Mike Frysinger54133972021-03-01 21:38:08 -0500727 except (KeyboardInterrupt, RuntimeError, SystemExit, ManifestParseError):
David Pursehousec1b86a22012-11-14 11:36:51 +0900728 raise
729 except Exception as e:
730 raise ManifestParseError(
Mike Frysingerec558df2019-07-05 01:38:05 -0400731 "failed parsing included manifest %s: %s" % (name, e))
David Pursehousec1b86a22012-11-14 11:36:51 +0900732 else:
Fredrik de Groot352c93b2020-10-06 12:55:14 +0200733 if parent_groups and node.nodeName == 'project':
734 nodeGroups = parent_groups
735 if node.hasAttribute('groups'):
736 nodeGroups = node.getAttribute('groups') + ',' + nodeGroups
737 node.setAttribute('groups', nodeGroups)
David Pursehousec1b86a22012-11-14 11:36:51 +0900738 nodes.append(node)
Colin Cross23acdd32012-04-21 00:33:54 -0700739 return nodes
Brian Harring26448742011-04-28 05:04:41 -0700740
Colin Cross23acdd32012-04-21 00:33:54 -0700741 def _ParseManifest(self, node_list):
742 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700743 if node.nodeName == 'remote':
744 remote = self._ParseRemote(node)
David Pursehouse717ece92012-11-13 08:49:16 +0900745 if remote:
746 if remote.name in self._remotes:
747 if remote != self._remotes[remote.name]:
748 raise ManifestParseError(
749 'remote %s already exists with different attributes' %
750 (remote.name))
751 else:
752 self._remotes[remote.name] = remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700753
Colin Cross23acdd32012-04-21 00:33:54 -0700754 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700755 if node.nodeName == 'default':
Julien Campergue74879922013-10-09 14:38:46 +0200756 new_default = self._ParseDefault(node)
757 if self._default is None:
758 self._default = new_default
759 elif new_default != self._default:
David Pursehouse37128b62013-10-15 10:48:40 +0900760 raise ManifestParseError('duplicate default in %s' %
761 (self.manifestFile))
Julien Campergue74879922013-10-09 14:38:46 +0200762
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700763 if self._default is None:
764 self._default = _Default()
765
Colin Cross23acdd32012-04-21 00:33:54 -0700766 for node in itertools.chain(*node_list):
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700767 if node.nodeName == 'notice':
768 if self._notice is not None:
Doug Anderson37282b42011-03-04 11:54:18 -0800769 raise ManifestParseError(
770 'duplicate notice in %s' %
771 (self.manifestFile))
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700772 self._notice = self._ParseNotice(node)
773
Colin Cross23acdd32012-04-21 00:33:54 -0700774 for node in itertools.chain(*node_list):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700775 if node.nodeName == 'manifest-server':
776 url = self._reqatt(node, 'url')
777 if self._manifest_server is not None:
David Pursehousec1b86a22012-11-14 11:36:51 +0900778 raise ManifestParseError(
779 'duplicate manifest-server in %s' %
780 (self.manifestFile))
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700781 self._manifest_server = url
782
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800783 def recursively_add_projects(project):
David James8d201162013-10-11 17:03:19 -0700784 projects = self._projects.setdefault(project.name, [])
785 if project.relpath is None:
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800786 raise ManifestParseError(
David James8d201162013-10-11 17:03:19 -0700787 'missing path for %s in %s' %
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800788 (project.name, self.manifestFile))
David James8d201162013-10-11 17:03:19 -0700789 if project.relpath in self._paths:
790 raise ManifestParseError(
791 'duplicate path %s in %s' %
792 (project.relpath, self.manifestFile))
793 self._paths[project.relpath] = project
794 projects.append(project)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800795 for subproject in project.subprojects:
796 recursively_add_projects(subproject)
797
Colin Cross23acdd32012-04-21 00:33:54 -0700798 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700799 if node.nodeName == 'project':
800 project = self._ParseProject(node)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800801 recursively_add_projects(project)
Josh Triplett884a3872014-06-12 14:57:29 -0700802 if node.nodeName == 'extend-project':
803 name = self._reqatt(node, 'name')
804
805 if name not in self._projects:
806 raise ManifestParseError('extend-project element specifies non-existent '
807 'project: %s' % name)
808
809 path = node.getAttribute('path')
810 groups = node.getAttribute('groups')
811 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -0500812 groups = self._ParseList(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -0700813 revision = node.getAttribute('revision')
Kyunam Jobd0aae92020-02-04 11:38:53 +0900814 remote = node.getAttribute('remote')
815 if remote:
816 remote = self._get_remote(node)
Josh Triplett884a3872014-06-12 14:57:29 -0700817
818 for p in self._projects[name]:
819 if path and p.relpath != path:
820 continue
821 if groups:
822 p.groups.extend(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -0700823 if revision:
824 p.revisionExpr = revision
Miguel Gaio1f207762020-07-17 14:09:13 +0200825 if IsId(revision):
826 p.revisionId = revision
827 else:
828 p.revisionId = None
Kyunam Jobd0aae92020-02-04 11:38:53 +0900829 if remote:
830 p.remote = remote.ToRemoteSpec(name)
Doug Anderson37282b42011-03-04 11:54:18 -0800831 if node.nodeName == 'repo-hooks':
832 # Get the name of the project and the (space-separated) list of enabled.
833 repo_hooks_project = self._reqatt(node, 'in-project')
Mike Frysinger51e39d52020-12-04 05:32:06 -0500834 enabled_repo_hooks = self._ParseList(self._reqatt(node, 'enabled-list'))
Doug Anderson37282b42011-03-04 11:54:18 -0800835
836 # Only one project can be the hooks project
837 if self._repo_hooks_project is not None:
838 raise ManifestParseError(
839 'duplicate repo-hooks in %s' %
840 (self.manifestFile))
841
842 # Store a reference to the Project.
843 try:
David James8d201162013-10-11 17:03:19 -0700844 repo_hooks_projects = self._projects[repo_hooks_project]
Doug Anderson37282b42011-03-04 11:54:18 -0800845 except KeyError:
846 raise ManifestParseError(
847 'project %s not found for repo-hooks' %
848 (repo_hooks_project))
849
David James8d201162013-10-11 17:03:19 -0700850 if len(repo_hooks_projects) != 1:
851 raise ManifestParseError(
852 'internal error parsing repo-hooks in %s' %
853 (self.manifestFile))
854 self._repo_hooks_project = repo_hooks_projects[0]
855
Doug Anderson37282b42011-03-04 11:54:18 -0800856 # Store the enabled hooks in the Project object.
857 self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800858 if node.nodeName == 'superproject':
859 name = self._reqatt(node, 'name')
860 # There can only be one superproject.
861 if self._superproject.get('name'):
862 raise ManifestParseError(
863 'duplicate superproject in %s' %
864 (self.manifestFile))
865 self._superproject['name'] = name
866 remote_name = node.getAttribute('remote')
867 if not remote_name:
868 remote = self._default.remote
869 else:
870 remote = self._get_remote(node)
871 if remote is None:
872 raise ManifestParseError("no remote for superproject %s within %s" %
873 (name, self.manifestFile))
874 self._superproject['remote'] = remote.ToRemoteSpec(name)
Colin Cross23acdd32012-04-21 00:33:54 -0700875 if node.nodeName == 'remove-project':
876 name = self._reqatt(node, 'name')
David Jamesb8433df2014-01-30 10:11:17 -0800877
878 if name not in self._projects:
David Pursehousef9107482012-11-16 19:12:32 +0900879 raise ManifestParseError('remove-project element specifies non-existent '
880 'project: %s' % name)
Colin Cross23acdd32012-04-21 00:33:54 -0700881
David Jamesb8433df2014-01-30 10:11:17 -0800882 for p in self._projects[name]:
883 del self._paths[p.relpath]
884 del self._projects[name]
885
Colin Cross23acdd32012-04-21 00:33:54 -0700886 # If the manifest removes the hooks project, treat it as if it deleted
887 # the repo-hooks element too.
888 if self._repo_hooks_project and (self._repo_hooks_project.name == name):
889 self._repo_hooks_project = None
890
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800891 def _AddMetaProjectMirror(self, m):
892 name = None
893 m_url = m.GetRemote(m.remote.name).url
894 if m_url.endswith('/.git'):
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530895 raise ManifestParseError('refusing to mirror %s' % m_url)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800896
897 if self._default and self._default.remote:
Conley Owensceea3682011-10-20 10:45:47 -0700898 url = self._default.remote.resolvedFetchUrl
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800899 if not url.endswith('/'):
900 url += '/'
901 if m_url.startswith(url):
902 remote = self._default.remote
903 name = m_url[len(url):]
904
905 if name is None:
906 s = m_url.rindex('/') + 1
Conley Owensdb728cd2011-09-26 16:34:01 -0700907 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Shawn O. Pearcef35b2d92012-08-02 11:46:22 -0700908 remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800909 name = m_url[s:]
910
911 if name.endswith('.git'):
912 name = name[:-4]
913
914 if name not in self._projects:
915 m.PreSync()
916 gitdir = os.path.join(self.topdir, '%s.git' % name)
David Pursehousee5913ae2020-02-12 13:56:59 +0900917 project = Project(manifest=self,
918 name=name,
919 remote=remote.ToRemoteSpec(name),
920 gitdir=gitdir,
921 objdir=gitdir,
922 worktree=None,
923 relpath=name or None,
924 revisionExpr=m.revisionExpr,
925 revisionId=None)
David James8d201162013-10-11 17:03:19 -0700926 self._projects[project.name] = [project]
Kwanhong Leeccd218c2014-02-17 13:07:32 +0900927 self._paths[project.relpath] = project
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800928
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700929 def _ParseRemote(self, node):
930 """
931 reads a <remote> element from the manifest file
932 """
933 name = self._reqatt(node, 'name')
Yestin Sunb292b982012-07-02 07:32:50 -0700934 alias = node.getAttribute('alias')
935 if alias == '':
936 alias = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700937 fetch = self._reqatt(node, 'fetch')
Steve Raed6480452016-08-10 15:00:00 -0700938 pushUrl = node.getAttribute('pushurl')
939 if pushUrl == '':
940 pushUrl = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700941 review = node.getAttribute('review')
Shawn O. Pearceae6e0942008-11-06 10:25:35 -0800942 if review == '':
943 review = None
Anthony King36ea2fb2014-05-06 11:54:01 +0100944 revision = node.getAttribute('revision')
945 if revision == '':
946 revision = None
Conley Owensdb728cd2011-09-26 16:34:01 -0700947 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Steve Raed6480452016-08-10 15:00:00 -0700948 return _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700949
950 def _ParseDefault(self, node):
951 """
952 reads a <default> element from the manifest file
953 """
954 d = _Default()
955 d.remote = self._get_remote(node)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700956 d.revisionExpr = node.getAttribute('revision')
957 if d.revisionExpr == '':
958 d.revisionExpr = None
Anatol Pomazau79770d22012-04-20 14:41:59 -0700959
Bryan Jacobsf609f912013-05-06 13:36:24 -0400960 d.destBranchExpr = node.getAttribute('dest-branch') or None
Nasser Grainawida403412018-05-04 12:53:29 -0600961 d.upstreamExpr = node.getAttribute('upstream') or None
Bryan Jacobsf609f912013-05-06 13:36:24 -0400962
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500963 d.sync_j = XmlInt(node, 'sync-j', 1)
964 if d.sync_j <= 0:
965 raise ManifestParseError('%s: sync-j must be greater than 0, not "%s"' %
966 (self.manifestFile, d.sync_j))
Anatol Pomazau79770d22012-04-20 14:41:59 -0700967
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500968 d.sync_c = XmlBool(node, 'sync-c', False)
969 d.sync_s = XmlBool(node, 'sync-s', False)
970 d.sync_tags = XmlBool(node, 'sync-tags', True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700971 return d
972
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700973 def _ParseNotice(self, node):
974 """
975 reads a <notice> element from the manifest file
976
977 The <notice> element is distinct from other tags in the XML in that the
978 data is conveyed between the start and end tag (it's not an empty-element
979 tag).
980
981 The white space (carriage returns, indentation) for the notice element is
982 relevant and is parsed in a way that is based on how python docstrings work.
983 In fact, the code is remarkably similar to here:
984 http://www.python.org/dev/peps/pep-0257/
985 """
986 # Get the data out of the node...
987 notice = node.childNodes[0].data
988
989 # Figure out minimum indentation, skipping the first line (the same line
990 # as the <notice> tag)...
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530991 minIndent = sys.maxsize
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700992 lines = notice.splitlines()
993 for line in lines[1:]:
994 lstrippedLine = line.lstrip()
995 if lstrippedLine:
996 indent = len(line) - len(lstrippedLine)
997 minIndent = min(indent, minIndent)
998
999 # Strip leading / trailing blank lines and also indentation.
1000 cleanLines = [lines[0].strip()]
1001 for line in lines[1:]:
1002 cleanLines.append(line[minIndent:].rstrip())
1003
1004 # Clear completely blank lines from front and back...
1005 while cleanLines and not cleanLines[0]:
1006 del cleanLines[0]
1007 while cleanLines and not cleanLines[-1]:
1008 del cleanLines[-1]
1009
1010 return '\n'.join(cleanLines)
1011
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001012 def _JoinName(self, parent_name, name):
1013 return os.path.join(parent_name, name)
1014
1015 def _UnjoinName(self, parent_name, name):
1016 return os.path.relpath(name, parent_name)
1017
David Pursehousee5913ae2020-02-12 13:56:59 +09001018 def _ParseProject(self, node, parent=None, **extra_proj_attrs):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001019 """
1020 reads a <project> element from the manifest file
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001021 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001022 name = self._reqatt(node, 'name')
Mike Frysingera29424e2021-02-25 21:53:49 -05001023 msg = self._CheckLocalPath(name, dir_ok=True)
1024 if msg:
1025 raise ManifestInvalidPathError(
1026 '<project> invalid "name": %s: %s' % (name, msg))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001027 if parent:
1028 name = self._JoinName(parent.name, name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001029
1030 remote = self._get_remote(node)
1031 if remote is None:
1032 remote = self._default.remote
1033 if remote is None:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301034 raise ManifestParseError("no remote for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001035 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001036
Anthony King36ea2fb2014-05-06 11:54:01 +01001037 revisionExpr = node.getAttribute('revision') or remote.revision
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001038 if not revisionExpr:
1039 revisionExpr = self._default.revisionExpr
1040 if not revisionExpr:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301041 raise ManifestParseError("no revision for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001042 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001043
1044 path = node.getAttribute('path')
1045 if not path:
1046 path = name
Mike Frysingera29424e2021-02-25 21:53:49 -05001047 else:
Mike Frysinger0458faa2021-03-10 23:35:44 -05001048 # NB: The "." project is handled specially in Project.Sync_LocalHalf.
1049 msg = self._CheckLocalPath(path, dir_ok=True, cwd_dot_ok=True)
Mike Frysingera29424e2021-02-25 21:53:49 -05001050 if msg:
1051 raise ManifestInvalidPathError(
1052 '<project> invalid "path": %s: %s' % (path, msg))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001053
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001054 rebase = XmlBool(node, 'rebase', True)
1055 sync_c = XmlBool(node, 'sync-c', False)
1056 sync_s = XmlBool(node, 'sync-s', self._default.sync_s)
1057 sync_tags = XmlBool(node, 'sync-tags', self._default.sync_tags)
Mike Pontillod3153822012-02-28 11:53:24 -08001058
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001059 clone_depth = XmlInt(node, 'clone-depth')
1060 if clone_depth is not None and clone_depth <= 0:
1061 raise ManifestParseError('%s: clone-depth must be greater than 0, not "%s"' %
1062 (self.manifestFile, clone_depth))
David Pursehouseede7f122012-11-27 22:25:30 +09001063
Bryan Jacobsf609f912013-05-06 13:36:24 -04001064 dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
1065
Nasser Grainawida403412018-05-04 12:53:29 -06001066 upstream = node.getAttribute('upstream') or self._default.upstreamExpr
Brian Harring14a66742012-09-28 20:21:57 -07001067
Conley Owens971de8e2012-04-16 10:36:08 -07001068 groups = ''
1069 if node.hasAttribute('groups'):
1070 groups = node.getAttribute('groups')
Mike Frysinger51e39d52020-12-04 05:32:06 -05001071 groups = self._ParseList(groups)
Brian Harring7da13142012-06-15 02:24:20 -07001072
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001073 if parent is None:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001074 relpath, worktree, gitdir, objdir, use_git_worktrees = \
1075 self.GetProjectPaths(name, path)
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001076 else:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001077 use_git_worktrees = False
David James8d201162013-10-11 17:03:19 -07001078 relpath, worktree, gitdir, objdir = \
1079 self.GetSubprojectPaths(parent, name, path)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001080
1081 default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
1082 groups.extend(set(default_groups).difference(groups))
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001083
Scott Fandb83b1b2013-02-28 09:34:14 +08001084 if self.IsMirror and node.hasAttribute('force-path'):
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001085 if XmlBool(node, 'force-path', False):
Scott Fandb83b1b2013-02-28 09:34:14 +08001086 gitdir = os.path.join(self.topdir, '%s.git' % path)
1087
David Pursehousee5913ae2020-02-12 13:56:59 +09001088 project = Project(manifest=self,
1089 name=name,
1090 remote=remote.ToRemoteSpec(name),
1091 gitdir=gitdir,
1092 objdir=objdir,
1093 worktree=worktree,
1094 relpath=relpath,
1095 revisionExpr=revisionExpr,
1096 revisionId=None,
1097 rebase=rebase,
1098 groups=groups,
1099 sync_c=sync_c,
1100 sync_s=sync_s,
1101 sync_tags=sync_tags,
1102 clone_depth=clone_depth,
1103 upstream=upstream,
1104 parent=parent,
1105 dest_branch=dest_branch,
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001106 use_git_worktrees=use_git_worktrees,
Simran Basib9a1b732015-08-20 12:19:28 -07001107 **extra_proj_attrs)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001108
1109 for n in node.childNodes:
Shawn O. Pearce242b5262009-05-19 13:00:29 -07001110 if n.nodeName == 'copyfile':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001111 self._ParseCopyFile(project, n)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001112 if n.nodeName == 'linkfile':
1113 self._ParseLinkFile(project, n)
James W. Mills24c13082012-04-12 15:04:13 -05001114 if n.nodeName == 'annotation':
1115 self._ParseAnnotation(project, n)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001116 if n.nodeName == 'project':
David Pursehousee5913ae2020-02-12 13:56:59 +09001117 project.subprojects.append(self._ParseProject(n, parent=project))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001118
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001119 return project
1120
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001121 def GetProjectPaths(self, name, path):
Mike Frysingercebf2272020-05-26 01:02:29 -04001122 # The manifest entries might have trailing slashes. Normalize them to avoid
1123 # unexpected filesystem behavior since we do string concatenation below.
1124 path = path.rstrip('/')
1125 name = name.rstrip('/')
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001126 use_git_worktrees = False
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001127 relpath = path
1128 if self.IsMirror:
1129 worktree = None
1130 gitdir = os.path.join(self.topdir, '%s.git' % name)
David James8d201162013-10-11 17:03:19 -07001131 objdir = gitdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001132 else:
1133 worktree = os.path.join(self.topdir, path).replace('\\', '/')
1134 gitdir = os.path.join(self.repodir, 'projects', '%s.git' % path)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001135 # We allow people to mix git worktrees & non-git worktrees for now.
1136 # This allows for in situ migration of repo clients.
1137 if os.path.exists(gitdir) or not self.UseGitWorktrees:
1138 objdir = os.path.join(self.repodir, 'project-objects', '%s.git' % name)
1139 else:
1140 use_git_worktrees = True
1141 gitdir = os.path.join(self.repodir, 'worktrees', '%s.git' % name)
1142 objdir = gitdir
1143 return relpath, worktree, gitdir, objdir, use_git_worktrees
David James8d201162013-10-11 17:03:19 -07001144
1145 def GetProjectsWithName(self, name):
1146 return self._projects.get(name, [])
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001147
1148 def GetSubprojectName(self, parent, submodule_path):
1149 return os.path.join(parent.name, submodule_path)
1150
1151 def _JoinRelpath(self, parent_relpath, relpath):
1152 return os.path.join(parent_relpath, relpath)
1153
1154 def _UnjoinRelpath(self, parent_relpath, relpath):
1155 return os.path.relpath(relpath, parent_relpath)
1156
David James8d201162013-10-11 17:03:19 -07001157 def GetSubprojectPaths(self, parent, name, path):
Mike Frysingercebf2272020-05-26 01:02:29 -04001158 # The manifest entries might have trailing slashes. Normalize them to avoid
1159 # unexpected filesystem behavior since we do string concatenation below.
1160 path = path.rstrip('/')
1161 name = name.rstrip('/')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001162 relpath = self._JoinRelpath(parent.relpath, path)
1163 gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
David James8d201162013-10-11 17:03:19 -07001164 objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001165 if self.IsMirror:
1166 worktree = None
1167 else:
1168 worktree = os.path.join(parent.worktree, path).replace('\\', '/')
David James8d201162013-10-11 17:03:19 -07001169 return relpath, worktree, gitdir, objdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001170
Mike Frysinger04122b72019-07-31 23:32:58 -04001171 @staticmethod
Mike Frysingera00c5f42021-02-25 18:26:31 -05001172 def _CheckLocalPath(path, dir_ok=False, cwd_dot_ok=False):
1173 """Verify |path| is reasonable for use in filesystem paths.
1174
Mike Frysingera29424e2021-02-25 21:53:49 -05001175 Used with <copyfile> & <linkfile> & <project> elements.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001176
1177 This only validates the |path| in isolation: it does not check against the
1178 current filesystem state. Thus it is suitable as a first-past in a parser.
1179
1180 It enforces a number of constraints:
1181 * No empty paths.
1182 * No "~" in paths.
1183 * No Unicode codepoints that filesystems might elide when normalizing.
1184 * No relative path components like "." or "..".
1185 * No absolute paths.
1186 * No ".git" or ".repo*" path components.
1187
1188 Args:
1189 path: The path name to validate.
1190 dir_ok: Whether |path| may force a directory (e.g. end in a /).
1191 cwd_dot_ok: Whether |path| may be just ".".
1192
1193 Returns:
1194 None if |path| is OK, a failure message otherwise.
1195 """
1196 if not path:
1197 return 'empty paths not allowed'
1198
Mike Frysinger04122b72019-07-31 23:32:58 -04001199 if '~' in path:
1200 return '~ not allowed (due to 8.3 filenames on Windows filesystems)'
1201
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001202 path_codepoints = set(path)
1203
Mike Frysinger04122b72019-07-31 23:32:58 -04001204 # Some filesystems (like Apple's HFS+) try to normalize Unicode codepoints
1205 # which means there are alternative names for ".git". Reject paths with
1206 # these in it as there shouldn't be any reasonable need for them here.
1207 # The set of codepoints here was cribbed from jgit's implementation:
1208 # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
1209 BAD_CODEPOINTS = {
1210 u'\u200C', # ZERO WIDTH NON-JOINER
1211 u'\u200D', # ZERO WIDTH JOINER
1212 u'\u200E', # LEFT-TO-RIGHT MARK
1213 u'\u200F', # RIGHT-TO-LEFT MARK
1214 u'\u202A', # LEFT-TO-RIGHT EMBEDDING
1215 u'\u202B', # RIGHT-TO-LEFT EMBEDDING
1216 u'\u202C', # POP DIRECTIONAL FORMATTING
1217 u'\u202D', # LEFT-TO-RIGHT OVERRIDE
1218 u'\u202E', # RIGHT-TO-LEFT OVERRIDE
1219 u'\u206A', # INHIBIT SYMMETRIC SWAPPING
1220 u'\u206B', # ACTIVATE SYMMETRIC SWAPPING
1221 u'\u206C', # INHIBIT ARABIC FORM SHAPING
1222 u'\u206D', # ACTIVATE ARABIC FORM SHAPING
1223 u'\u206E', # NATIONAL DIGIT SHAPES
1224 u'\u206F', # NOMINAL DIGIT SHAPES
1225 u'\uFEFF', # ZERO WIDTH NO-BREAK SPACE
1226 }
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001227 if BAD_CODEPOINTS & path_codepoints:
Mike Frysinger04122b72019-07-31 23:32:58 -04001228 # This message is more expansive than reality, but should be fine.
1229 return 'Unicode combining characters not allowed'
1230
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001231 # Reject newlines as there shouldn't be any legitmate use for them, they'll
1232 # be confusing to users, and they can easily break tools that expect to be
1233 # able to iterate over newline delimited lists. This even applies to our
1234 # own code like .repo/project.list.
1235 if {'\r', '\n'} & path_codepoints:
1236 return 'Newlines not allowed'
1237
Mike Frysinger04122b72019-07-31 23:32:58 -04001238 # Assume paths might be used on case-insensitive filesystems.
1239 path = path.lower()
1240
Mike Frysingerd9254592020-02-19 22:36:26 -05001241 # Split up the path by its components. We can't use os.path.sep exclusively
1242 # as some platforms (like Windows) will convert / to \ and that bypasses all
1243 # our constructed logic here. Especially since manifest authors only use
1244 # / in their paths.
1245 resep = re.compile(r'[/%s]' % re.escape(os.path.sep))
Mike Frysinger0458faa2021-03-10 23:35:44 -05001246 # Strip off trailing slashes as those only produce '' elements, and we use
1247 # parts to look for individual bad components.
1248 parts = resep.split(path.rstrip('/'))
Mike Frysingerd9254592020-02-19 22:36:26 -05001249
Mike Frysingerae625412020-02-10 17:10:03 -05001250 # Some people use src="." to create stable links to projects. Lets allow
1251 # that but reject all other uses of "." to keep things simple.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001252 if not cwd_dot_ok or parts != ['.']:
Mike Frysingerae625412020-02-10 17:10:03 -05001253 for part in set(parts):
1254 if part in {'.', '..', '.git'} or part.startswith('.repo'):
1255 return 'bad component: %s' % (part,)
Mike Frysinger04122b72019-07-31 23:32:58 -04001256
Mike Frysingera00c5f42021-02-25 18:26:31 -05001257 if not dir_ok and resep.match(path[-1]):
Mike Frysinger04122b72019-07-31 23:32:58 -04001258 return 'dirs not allowed'
1259
Mike Frysingerd9254592020-02-19 22:36:26 -05001260 # NB: The two abspath checks here are to handle platforms with multiple
1261 # filesystem path styles (e.g. Windows).
Mike Frysinger04122b72019-07-31 23:32:58 -04001262 norm = os.path.normpath(path)
Mike Frysingerd9254592020-02-19 22:36:26 -05001263 if (norm == '..' or
1264 (len(norm) >= 3 and norm.startswith('..') and resep.match(norm[0])) or
1265 os.path.isabs(norm) or
1266 norm.startswith('/')):
Mike Frysinger04122b72019-07-31 23:32:58 -04001267 return 'path cannot be outside'
1268
1269 @classmethod
1270 def _ValidateFilePaths(cls, element, src, dest):
1271 """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
1272
1273 We verify the path independent of any filesystem state as we won't have a
1274 checkout available to compare to. i.e. This is for parsing validation
1275 purposes only.
1276
1277 We'll do full/live sanity checking before we do the actual filesystem
1278 modifications in _CopyFile/_LinkFile/etc...
1279 """
1280 # |dest| is the file we write to or symlink we create.
1281 # It is relative to the top of the repo client checkout.
1282 msg = cls._CheckLocalPath(dest)
1283 if msg:
1284 raise ManifestInvalidPathError(
1285 '<%s> invalid "dest": %s: %s' % (element, dest, msg))
1286
1287 # |src| is the file we read from or path we point to for symlinks.
1288 # It is relative to the top of the git project checkout.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001289 is_linkfile = element == 'linkfile'
1290 msg = cls._CheckLocalPath(src, dir_ok=is_linkfile, cwd_dot_ok=is_linkfile)
Mike Frysinger04122b72019-07-31 23:32:58 -04001291 if msg:
1292 raise ManifestInvalidPathError(
1293 '<%s> invalid "src": %s: %s' % (element, src, msg))
1294
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001295 def _ParseCopyFile(self, project, node):
1296 src = self._reqatt(node, 'src')
1297 dest = self._reqatt(node, 'dest')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001298 if not self.IsMirror:
1299 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001300 # dest is relative to the top of the tree.
1301 # We only validate paths if we actually plan to process them.
1302 self._ValidateFilePaths('copyfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001303 project.AddCopyFile(src, dest, self.topdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001304
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001305 def _ParseLinkFile(self, project, node):
1306 src = self._reqatt(node, 'src')
1307 dest = self._reqatt(node, 'dest')
1308 if not self.IsMirror:
1309 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001310 # dest is relative to the top of the tree.
1311 # We only validate paths if we actually plan to process them.
1312 self._ValidateFilePaths('linkfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001313 project.AddLinkFile(src, dest, self.topdir)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001314
James W. Mills24c13082012-04-12 15:04:13 -05001315 def _ParseAnnotation(self, project, node):
1316 name = self._reqatt(node, 'name')
1317 value = self._reqatt(node, 'value')
1318 try:
1319 keep = self._reqatt(node, 'keep').lower()
1320 except ManifestParseError:
1321 keep = "true"
1322 if keep != "true" and keep != "false":
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301323 raise ManifestParseError('optional "keep" attribute must be '
David Pursehouseabdf7502020-02-12 14:58:39 +09001324 '"true" or "false"')
James W. Mills24c13082012-04-12 15:04:13 -05001325 project.AddAnnotation(name, value, keep)
1326
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001327 def _get_remote(self, node):
1328 name = node.getAttribute('remote')
1329 if not name:
1330 return None
1331
1332 v = self._remotes.get(name)
1333 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301334 raise ManifestParseError("remote %s not defined in %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001335 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001336 return v
1337
1338 def _reqatt(self, node, attname):
1339 """
1340 reads a required attribute from the node.
1341 """
1342 v = node.getAttribute(attname)
1343 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301344 raise ManifestParseError("no %s in <%s> within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001345 (attname, node.nodeName, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001346 return v
Julien Camperguedd654222014-01-09 16:21:37 +01001347
1348 def projectsDiff(self, manifest):
1349 """return the projects differences between two manifests.
1350
1351 The diff will be from self to given manifest.
1352
1353 """
1354 fromProjects = self.paths
1355 toProjects = manifest.paths
1356
Anthony King7446c592014-05-06 09:19:39 +01001357 fromKeys = sorted(fromProjects.keys())
1358 toKeys = sorted(toProjects.keys())
Julien Camperguedd654222014-01-09 16:21:37 +01001359
1360 diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
1361
1362 for proj in fromKeys:
David Pursehouseeeff3532020-02-12 11:24:10 +09001363 if proj not in toKeys:
Julien Camperguedd654222014-01-09 16:21:37 +01001364 diff['removed'].append(fromProjects[proj])
1365 else:
1366 fromProj = fromProjects[proj]
1367 toProj = toProjects[proj]
1368 try:
1369 fromRevId = fromProj.GetCommitRevisionId()
1370 toRevId = toProj.GetCommitRevisionId()
1371 except ManifestInvalidRevisionError:
1372 diff['unreachable'].append((fromProj, toProj))
1373 else:
1374 if fromRevId != toRevId:
1375 diff['changed'].append((fromProj, toProj))
1376 toKeys.remove(proj)
1377
1378 for proj in toKeys:
1379 diff['added'].append(toProjects[proj])
1380
1381 return diff
Simran Basib9a1b732015-08-20 12:19:28 -07001382
1383
1384class GitcManifest(XmlManifest):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001385 """Parser for GitC (git-in-the-cloud) manifests."""
Simran Basib9a1b732015-08-20 12:19:28 -07001386
David Pursehousee5913ae2020-02-12 13:56:59 +09001387 def _ParseProject(self, node, parent=None):
Simran Basib9a1b732015-08-20 12:19:28 -07001388 """Override _ParseProject and add support for GITC specific attributes."""
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001389 return super()._ParseProject(
Simran Basib9a1b732015-08-20 12:19:28 -07001390 node, parent=parent, old_revision=node.getAttribute('old-revision'))
1391
1392 def _output_manifest_project_extras(self, p, e):
1393 """Output GITC Specific Project attributes"""
1394 if p.old_revision:
Stefan Beller66851062016-06-17 16:40:08 -07001395 e.setAttribute('old-revision', str(p.old_revision))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001396
1397
1398class RepoClient(XmlManifest):
1399 """Manages a repo client checkout."""
1400
1401 def __init__(self, repodir, manifest_file=None):
1402 self.isGitcClient = False
1403
1404 if os.path.exists(os.path.join(repodir, LOCAL_MANIFEST_NAME)):
1405 print('error: %s is not supported; put local manifests in `%s` instead' %
1406 (LOCAL_MANIFEST_NAME, os.path.join(repodir, LOCAL_MANIFESTS_DIR_NAME)),
1407 file=sys.stderr)
1408 sys.exit(1)
1409
1410 if manifest_file is None:
1411 manifest_file = os.path.join(repodir, MANIFEST_FILE_NAME)
1412 local_manifests = os.path.abspath(os.path.join(repodir, LOCAL_MANIFESTS_DIR_NAME))
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001413 super().__init__(repodir, manifest_file, local_manifests)
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001414
1415 # TODO: Completely separate manifest logic out of the client.
1416 self.manifest = self
1417
1418
1419class GitcClient(RepoClient, GitcManifest):
1420 """Manages a GitC client checkout."""
1421
1422 def __init__(self, repodir, gitc_client_name):
1423 """Initialize the GitcManifest object."""
1424 self.gitc_client_name = gitc_client_name
1425 self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
1426 gitc_client_name)
1427
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001428 super().__init__(repodir, os.path.join(self.gitc_client_dir, '.manifest'))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001429 self.isGitcClient = True