blob: 30e96584d73daf641ee539f4c285b3512583c91c [file] [log] [blame]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001# Copyright (C) 2008 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
Raman Tenneti993af5e2021-05-12 12:00:31 -070015import collections
Colin Cross23acdd32012-04-21 00:33:54 -070016import itertools
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070017import os
Raman Tenneti080877e2021-03-09 15:19:06 -080018import platform
Conley Owensdb728cd2011-09-26 16:34:01 -070019import re
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070020import sys
David Pursehouse59bbb582013-05-17 10:49:33 +090021import xml.dom.minidom
Mike Frysingeracf63b22019-06-13 02:24:21 -040022import urllib.parse
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070023
Simran Basib9a1b732015-08-20 12:19:28 -070024import gitc_utils
Miguel Gaio1f207762020-07-17 14:09:13 +020025from git_config import GitConfig, IsId
David Pursehousee00aa6b2012-09-11 14:33:51 +090026from git_refs import R_HEADS, HEAD
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070027import platform_utils
David Pursehousee00aa6b2012-09-11 14:33:51 +090028from project import RemoteSpec, Project, MetaProject
Mike Frysinger04122b72019-07-31 23:32:58 -040029from error import (ManifestParseError, ManifestInvalidPathError,
30 ManifestInvalidRevisionError)
Raman Tenneti993af5e2021-05-12 12:00:31 -070031from wrapper import Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070032
33MANIFEST_FILE_NAME = 'manifest.xml'
Shawn O. Pearce5cc66792008-10-23 16:19:27 -070034LOCAL_MANIFEST_NAME = 'local_manifest.xml'
David Pursehouse2d5a0df2012-11-13 02:50:36 +090035LOCAL_MANIFESTS_DIR_NAME = 'local_manifests'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070036
Raman Tenneti78f4dd32021-06-07 13:27:37 -070037# Add all projects from local manifest into a group.
38LOCAL_MANIFEST_GROUP_PREFIX = 'local:'
39
Raman Tenneti993af5e2021-05-12 12:00:31 -070040# ContactInfo has the self-registered bug url, supplied by the manifest authors.
41ContactInfo = collections.namedtuple('ContactInfo', 'bugurl')
42
Anthony Kingcb07ba72015-03-28 23:26:04 +000043# urljoin gets confused if the scheme is not known.
Joe Kilner6e310792016-10-27 15:53:53 -070044urllib.parse.uses_relative.extend([
45 'ssh',
46 'git',
47 'persistent-https',
48 'sso',
49 'rpc'])
50urllib.parse.uses_netloc.extend([
51 'ssh',
52 'git',
53 'persistent-https',
54 'sso',
55 'rpc'])
Conley Owensdb728cd2011-09-26 16:34:01 -070056
David Pursehouse819827a2020-02-12 15:20:19 +090057
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050058def XmlBool(node, attr, default=None):
59 """Determine boolean value of |node|'s |attr|.
60
61 Invalid values will issue a non-fatal warning.
62
63 Args:
64 node: XML node whose attributes we access.
65 attr: The attribute to access.
66 default: If the attribute is not set (value is empty), then use this.
67
68 Returns:
69 True if the attribute is a valid string representing true.
70 False if the attribute is a valid string representing false.
71 |default| otherwise.
72 """
73 value = node.getAttribute(attr)
74 s = value.lower()
75 if s == '':
76 return default
77 elif s in {'yes', 'true', '1'}:
78 return True
79 elif s in {'no', 'false', '0'}:
80 return False
81 else:
82 print('warning: manifest: %s="%s": ignoring invalid XML boolean' %
83 (attr, value), file=sys.stderr)
84 return default
85
86
87def XmlInt(node, attr, default=None):
88 """Determine integer value of |node|'s |attr|.
89
90 Args:
91 node: XML node whose attributes we access.
92 attr: The attribute to access.
93 default: If the attribute is not set (value is empty), then use this.
94
95 Returns:
96 The number if the attribute is a valid number.
97
98 Raises:
99 ManifestParseError: The number is invalid.
100 """
101 value = node.getAttribute(attr)
102 if not value:
103 return default
104
105 try:
106 return int(value)
107 except ValueError:
108 raise ManifestParseError('manifest: invalid %s="%s" integer' %
109 (attr, value))
110
111
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700112class _Default(object):
113 """Project defaults within the manifest."""
114
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700115 revisionExpr = None
Conley Owensb6a16e62013-09-25 15:06:09 -0700116 destBranchExpr = None
Nasser Grainawida403412018-05-04 12:53:29 -0600117 upstreamExpr = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700118 remote = None
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700119 sync_j = 1
Anatol Pomazau79770d22012-04-20 14:41:59 -0700120 sync_c = False
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800121 sync_s = False
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900122 sync_tags = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700123
Julien Campergue74879922013-10-09 14:38:46 +0200124 def __eq__(self, other):
125 return self.__dict__ == other.__dict__
126
127 def __ne__(self, other):
128 return self.__dict__ != other.__dict__
129
David Pursehouse819827a2020-02-12 15:20:19 +0900130
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700131class _XmlRemote(object):
132 def __init__(self,
133 name,
Yestin Sunb292b982012-07-02 07:32:50 -0700134 alias=None,
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700135 fetch=None,
Steve Raed6480452016-08-10 15:00:00 -0700136 pushUrl=None,
Conley Owensdb728cd2011-09-26 16:34:01 -0700137 manifestUrl=None,
Anthony King36ea2fb2014-05-06 11:54:01 +0100138 review=None,
Jonathan Nieder93719792015-03-17 11:29:58 -0700139 revision=None):
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700140 self.name = name
141 self.fetchUrl = fetch
Steve Raed6480452016-08-10 15:00:00 -0700142 self.pushUrl = pushUrl
Conley Owensdb728cd2011-09-26 16:34:01 -0700143 self.manifestUrl = manifestUrl
Yestin Sunb292b982012-07-02 07:32:50 -0700144 self.remoteAlias = alias
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700145 self.reviewUrl = review
Anthony King36ea2fb2014-05-06 11:54:01 +0100146 self.revision = revision
Conley Owensceea3682011-10-20 10:45:47 -0700147 self.resolvedFetchUrl = self._resolveFetchUrl()
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700148
David Pursehouse717ece92012-11-13 08:49:16 +0900149 def __eq__(self, other):
150 return self.__dict__ == other.__dict__
151
152 def __ne__(self, other):
153 return self.__dict__ != other.__dict__
154
Conley Owensceea3682011-10-20 10:45:47 -0700155 def _resolveFetchUrl(self):
156 url = self.fetchUrl.rstrip('/')
Conley Owensdb728cd2011-09-26 16:34:01 -0700157 manifestUrl = self.manifestUrl.rstrip('/')
Conley Owens2d0f5082014-01-31 15:03:51 -0800158 # urljoin will gets confused over quite a few things. The ones we care
159 # about here are:
160 # * no scheme in the base url, like <hostname:port>
Anthony Kingcb07ba72015-03-28 23:26:04 +0000161 # We handle no scheme by replacing it with an obscure protocol, gopher
162 # and then replacing it with the original when we are done.
163
Conley Owensdb728cd2011-09-26 16:34:01 -0700164 if manifestUrl.find(':') != manifestUrl.find('/') - 1:
Conley Owens4ccad752015-04-29 10:45:37 -0700165 url = urllib.parse.urljoin('gopher://' + manifestUrl, url)
166 url = re.sub(r'^gopher://', '', url)
Anthony Kingcb07ba72015-03-28 23:26:04 +0000167 else:
168 url = urllib.parse.urljoin(manifestUrl, url)
Shawn Pearcea9f11b32013-01-02 15:40:48 -0800169 return url
Conley Owensceea3682011-10-20 10:45:47 -0700170
171 def ToRemoteSpec(self, projectName):
David Rileye0684ad2017-04-05 00:02:59 -0700172 fetchUrl = self.resolvedFetchUrl.rstrip('/')
173 url = fetchUrl + '/' + projectName
Yestin Sunb292b982012-07-02 07:32:50 -0700174 remoteName = self.name
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700175 if self.remoteAlias:
David Pursehouse37128b62013-10-15 10:48:40 +0900176 remoteName = self.remoteAlias
Dan Willemsen96c2d652016-04-06 16:03:54 -0700177 return RemoteSpec(remoteName,
178 url=url,
Steve Raed6480452016-08-10 15:00:00 -0700179 pushUrl=self.pushUrl,
Dan Willemsen96c2d652016-04-06 16:03:54 -0700180 review=self.reviewUrl,
David Rileye0684ad2017-04-05 00:02:59 -0700181 orig_name=self.name,
182 fetchUrl=self.fetchUrl)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700183
David Pursehouse819827a2020-02-12 15:20:19 +0900184
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700185class XmlManifest(object):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700186 """manages the repo configuration file"""
187
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400188 def __init__(self, repodir, manifest_file, local_manifests=None):
189 """Initialize.
190
191 Args:
192 repodir: Path to the .repo/ dir for holding all internal checkout state.
193 It must be in the top directory of the repo client checkout.
194 manifest_file: Full path to the manifest file to parse. This will usually
195 be |repodir|/|MANIFEST_FILE_NAME|.
196 local_manifests: Full path to the directory of local override manifests.
197 This will usually be |repodir|/|LOCAL_MANIFESTS_DIR_NAME|.
198 """
199 # TODO(vapier): Move this out of this class.
200 self.globalConfig = GitConfig.ForUser()
201
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700202 self.repodir = os.path.abspath(repodir)
203 self.topdir = os.path.dirname(self.repodir)
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400204 self.manifestFile = manifest_file
205 self.local_manifests = local_manifests
Basil Gelloc7453502018-05-25 20:23:52 +0300206 self._load_local_manifests = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700207
208 self.repoProject = MetaProject(self, 'repo',
David Pursehouseabdf7502020-02-12 14:58:39 +0900209 gitdir=os.path.join(repodir, 'repo/.git'),
210 worktree=os.path.join(repodir, 'repo'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700211
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500212 mp = MetaProject(self, 'manifests',
213 gitdir=os.path.join(repodir, 'manifests.git'),
214 worktree=os.path.join(repodir, 'manifests'))
215 self.manifestProject = mp
216
217 # This is a bit hacky, but we're in a chicken & egg situation: all the
218 # normal repo settings live in the manifestProject which we just setup
219 # above, so we couldn't easily query before that. We assume Project()
220 # init doesn't care if this changes afterwards.
Mike Frysingerd957ec62020-02-24 14:40:25 -0500221 if os.path.exists(mp.gitdir) and mp.config.GetBoolean('repo.worktree'):
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500222 mp.use_git_worktrees = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700223
224 self._Unload()
225
Basil Gelloc7453502018-05-25 20:23:52 +0300226 def Override(self, name, load_local_manifests=True):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700227 """Use a different manifest, just for the current instantiation.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700228 """
Basil Gelloc7453502018-05-25 20:23:52 +0300229 path = None
230
231 # Look for a manifest by path in the filesystem (including the cwd).
232 if not load_local_manifests:
233 local_path = os.path.abspath(name)
234 if os.path.isfile(local_path):
235 path = local_path
236
237 # Look for manifests by name from the manifests repo.
238 if path is None:
239 path = os.path.join(self.manifestProject.worktree, name)
240 if not os.path.isfile(path):
241 raise ManifestParseError('manifest %s not found' % name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700242
243 old = self.manifestFile
244 try:
Basil Gelloc7453502018-05-25 20:23:52 +0300245 self._load_local_manifests = load_local_manifests
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700246 self.manifestFile = path
247 self._Unload()
248 self._Load()
249 finally:
250 self.manifestFile = old
251
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700252 def Link(self, name):
253 """Update the repo metadata to use a different manifest.
254 """
255 self.Override(name)
256
Mike Frysingera269b1c2020-02-21 00:49:41 -0500257 # Old versions of repo would generate symlinks we need to clean up.
258 if os.path.lexists(self.manifestFile):
259 platform_utils.remove(self.manifestFile)
260 # This file is interpreted as if it existed inside the manifest repo.
261 # That allows us to use <include> with the relative file name.
262 with open(self.manifestFile, 'w') as fp:
263 fp.write("""<?xml version="1.0" encoding="UTF-8"?>
264<!--
265DO NOT EDIT THIS FILE! It is generated by repo and changes will be discarded.
266If you want to use a different manifest, use `repo init -m <file>` instead.
267
268If you want to customize your checkout by overriding manifest settings, use
269the local_manifests/ directory instead.
270
271For more information on repo manifests, check out:
272https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
273-->
274<manifest>
275 <include name="%s" />
276</manifest>
277""" % (name,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700278
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800279 def _RemoteToXml(self, r, doc, root):
280 e = doc.createElement('remote')
281 root.appendChild(e)
282 e.setAttribute('name', r.name)
283 e.setAttribute('fetch', r.fetchUrl)
Steve Raed6480452016-08-10 15:00:00 -0700284 if r.pushUrl is not None:
285 e.setAttribute('pushurl', r.pushUrl)
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700286 if r.remoteAlias is not None:
287 e.setAttribute('alias', r.remoteAlias)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800288 if r.reviewUrl is not None:
289 e.setAttribute('review', r.reviewUrl)
Anthony King36ea2fb2014-05-06 11:54:01 +0100290 if r.revision is not None:
291 e.setAttribute('revision', r.revision)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800292
Mike Frysinger51e39d52020-12-04 05:32:06 -0500293 def _ParseList(self, field):
294 """Parse fields that contain flattened lists.
295
296 These are whitespace & comma separated. Empty elements will be discarded.
297 """
298 return [x for x in re.split(r'[,\s]+', field) if x]
Josh Triplett884a3872014-06-12 14:57:29 -0700299
Mike Frysinger23411d32020-09-02 04:31:10 -0400300 def ToXml(self, peg_rev=False, peg_rev_upstream=True, peg_rev_dest_branch=True, groups=None):
301 """Return the current manifest XML."""
Colin Cross5acde752012-03-28 20:15:45 -0700302 mp = self.manifestProject
303
Dan Willemsen5ea32d12015-09-08 13:27:20 -0700304 if groups is None:
305 groups = mp.config.GetString('manifest.groups')
Matt Gumbel0c635bb2012-12-21 10:14:53 -0800306 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -0500307 groups = self._ParseList(groups)
Colin Cross5acde752012-03-28 20:15:45 -0700308
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800309 doc = xml.dom.minidom.Document()
310 root = doc.createElement('manifest')
311 doc.appendChild(root)
312
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700313 # Save out the notice. There's a little bit of work here to give it the
314 # right whitespace, which assumes that the notice is automatically indented
315 # by 4 by minidom.
316 if self.notice:
317 notice_element = root.appendChild(doc.createElement('notice'))
318 notice_lines = self.notice.splitlines()
David Pursehouse54a4e602020-02-12 14:31:05 +0900319 indented_notice = ('\n'.join(" " * 4 + line for line in notice_lines))[4:]
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700320 notice_element.appendChild(doc.createTextNode(indented_notice))
321
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800322 d = self.default
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800323
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530324 for r in sorted(self.remotes):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800325 self._RemoteToXml(self.remotes[r], doc, root)
326 if self.remotes:
327 root.appendChild(doc.createTextNode(''))
328
329 have_default = False
330 e = doc.createElement('default')
331 if d.remote:
332 have_default = True
333 e.setAttribute('remote', d.remote.name)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700334 if d.revisionExpr:
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800335 have_default = True
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700336 e.setAttribute('revision', d.revisionExpr)
Simon Ruggier7e59de22015-07-24 12:50:06 +0200337 if d.destBranchExpr:
338 have_default = True
339 e.setAttribute('dest-branch', d.destBranchExpr)
Nasser Grainawida403412018-05-04 12:53:29 -0600340 if d.upstreamExpr:
341 have_default = True
342 e.setAttribute('upstream', d.upstreamExpr)
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700343 if d.sync_j > 1:
344 have_default = True
345 e.setAttribute('sync-j', '%d' % d.sync_j)
Anatol Pomazau79770d22012-04-20 14:41:59 -0700346 if d.sync_c:
347 have_default = True
348 e.setAttribute('sync-c', 'true')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800349 if d.sync_s:
350 have_default = True
351 e.setAttribute('sync-s', 'true')
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900352 if not d.sync_tags:
353 have_default = True
354 e.setAttribute('sync-tags', 'false')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800355 if have_default:
356 root.appendChild(e)
357 root.appendChild(doc.createTextNode(''))
358
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700359 if self._manifest_server:
360 e = doc.createElement('manifest-server')
361 e.setAttribute('url', self._manifest_server)
362 root.appendChild(e)
363 root.appendChild(doc.createTextNode(''))
364
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800365 def output_projects(parent, parent_node, projects):
David James8d201162013-10-11 17:03:19 -0700366 for project_name in projects:
367 for project in self._projects[project_name]:
368 output_project(parent, parent_node, project)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800369
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800370 def output_project(parent, parent_node, p):
Colin Cross5acde752012-03-28 20:15:45 -0700371 if not p.MatchesGroups(groups):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800372 return
373
374 name = p.name
375 relpath = p.relpath
376 if parent:
377 name = self._UnjoinName(parent.name, name)
378 relpath = self._UnjoinRelpath(parent.relpath, relpath)
Colin Cross5acde752012-03-28 20:15:45 -0700379
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800380 e = doc.createElement('project')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800381 parent_node.appendChild(e)
382 e.setAttribute('name', name)
383 if relpath != name:
384 e.setAttribute('path', relpath)
Conley Owensa17d7af2013-10-16 14:38:09 -0700385 remoteName = None
386 if d.remote:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700387 remoteName = d.remote.name
388 if not d.remote or p.remote.orig_name != remoteName:
389 remoteName = p.remote.orig_name
Anthony King36ea2fb2014-05-06 11:54:01 +0100390 e.setAttribute('remote', remoteName)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800391 if peg_rev:
392 if self.IsMirror:
Brian Harring14a66742012-09-28 20:21:57 -0700393 value = p.bare_git.rev_parse(p.revisionExpr + '^0')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800394 else:
Brian Harring14a66742012-09-28 20:21:57 -0700395 value = p.work_git.rev_parse(HEAD + '^0')
396 e.setAttribute('revision', value)
Conley Owens551dfec2015-07-10 14:54:54 -0700397 if peg_rev_upstream:
398 if p.upstream:
399 e.setAttribute('upstream', p.upstream)
400 elif value != p.revisionExpr:
401 # Only save the origin if the origin is not a sha1, and the default
402 # isn't our value
403 e.setAttribute('upstream', p.revisionExpr)
Sean McAllisteraf908cb2020-04-20 08:41:58 -0600404
405 if peg_rev_dest_branch:
406 if p.dest_branch:
407 e.setAttribute('dest-branch', p.dest_branch)
408 elif value != p.revisionExpr:
409 e.setAttribute('dest-branch', p.revisionExpr)
410
Anthony King36ea2fb2014-05-06 11:54:01 +0100411 else:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700412 revision = self.remotes[p.remote.orig_name].revision or d.revisionExpr
Anthony King36ea2fb2014-05-06 11:54:01 +0100413 if not revision or revision != p.revisionExpr:
414 e.setAttribute('revision', p.revisionExpr)
Raman Tennetib5c5a5e2021-02-06 09:44:15 -0800415 elif p.revisionId:
416 e.setAttribute('revision', p.revisionId)
Nasser Grainawida403412018-05-04 12:53:29 -0600417 if (p.upstream and (p.upstream != p.revisionExpr or
418 p.upstream != d.upstreamExpr)):
Mani Chandel7a91d512014-07-24 16:27:08 +0530419 e.setAttribute('upstream', p.upstream)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800420
Simon Ruggier7e59de22015-07-24 12:50:06 +0200421 if p.dest_branch and p.dest_branch != d.destBranchExpr:
422 e.setAttribute('dest-branch', p.dest_branch)
423
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800424 for c in p.copyfiles:
425 ce = doc.createElement('copyfile')
426 ce.setAttribute('src', c.src)
427 ce.setAttribute('dest', c.dest)
428 e.appendChild(ce)
429
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500430 for l in p.linkfiles:
431 le = doc.createElement('linkfile')
432 le.setAttribute('src', l.src)
433 le.setAttribute('dest', l.dest)
434 e.appendChild(le)
435
Conley Owensbb1b5f52012-08-13 13:11:18 -0700436 default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
Dmitry Fink17f85ea2012-08-06 14:52:29 -0700437 egroups = [g for g in p.groups if g not in default_groups]
Conley Owens971de8e2012-04-16 10:36:08 -0700438 if egroups:
439 e.setAttribute('groups', ','.join(egroups))
Colin Cross5acde752012-03-28 20:15:45 -0700440
James W. Mills24c13082012-04-12 15:04:13 -0500441 for a in p.annotations:
442 if a.keep == "true":
443 ae = doc.createElement('annotation')
444 ae.setAttribute('name', a.name)
445 ae.setAttribute('value', a.value)
446 e.appendChild(ae)
447
Anatol Pomazau79770d22012-04-20 14:41:59 -0700448 if p.sync_c:
449 e.setAttribute('sync-c', 'true')
450
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800451 if p.sync_s:
452 e.setAttribute('sync-s', 'true')
453
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900454 if not p.sync_tags:
455 e.setAttribute('sync-tags', 'false')
456
Dan Willemsen88409222015-08-17 15:29:10 -0700457 if p.clone_depth:
458 e.setAttribute('clone-depth', str(p.clone_depth))
459
Simran Basib9a1b732015-08-20 12:19:28 -0700460 self._output_manifest_project_extras(p, e)
461
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800462 if p.subprojects:
David James8d201162013-10-11 17:03:19 -0700463 subprojects = set(subp.name for subp in p.subprojects)
464 output_projects(p, e, list(sorted(subprojects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800465
David James8d201162013-10-11 17:03:19 -0700466 projects = set(p.name for p in self._paths.values() if not p.parent)
467 output_projects(None, root, list(sorted(projects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800468
Doug Anderson37282b42011-03-04 11:54:18 -0800469 if self._repo_hooks_project:
470 root.appendChild(doc.createTextNode(''))
471 e = doc.createElement('repo-hooks')
472 e.setAttribute('in-project', self._repo_hooks_project.name)
473 e.setAttribute('enabled-list',
474 ' '.join(self._repo_hooks_project.enabled_repo_hooks))
475 root.appendChild(e)
476
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800477 if self._superproject:
478 root.appendChild(doc.createTextNode(''))
479 e = doc.createElement('superproject')
480 e.setAttribute('name', self._superproject['name'])
481 remoteName = None
482 if d.remote:
483 remoteName = d.remote.name
484 remote = self._superproject.get('remote')
485 if not d.remote or remote.orig_name != remoteName:
486 remoteName = remote.orig_name
487 e.setAttribute('remote', remoteName)
488 root.appendChild(e)
489
Raman Tenneti993af5e2021-05-12 12:00:31 -0700490 if self._contactinfo.bugurl != Wrapper().BUG_URL:
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700491 root.appendChild(doc.createTextNode(''))
492 e = doc.createElement('contactinfo')
Raman Tenneti993af5e2021-05-12 12:00:31 -0700493 e.setAttribute('bugurl', self._contactinfo.bugurl)
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700494 root.appendChild(e)
495
Mike Frysinger23411d32020-09-02 04:31:10 -0400496 return doc
497
498 def ToDict(self, **kwargs):
499 """Return the current manifest as a dictionary."""
500 # Elements that may only appear once.
501 SINGLE_ELEMENTS = {
502 'notice',
503 'default',
504 'manifest-server',
505 'repo-hooks',
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800506 'superproject',
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700507 'contactinfo',
Mike Frysinger23411d32020-09-02 04:31:10 -0400508 }
509 # Elements that may be repeated.
510 MULTI_ELEMENTS = {
511 'remote',
512 'remove-project',
513 'project',
514 'extend-project',
515 'include',
516 # These are children of 'project' nodes.
517 'annotation',
518 'project',
519 'copyfile',
520 'linkfile',
521 }
522
523 doc = self.ToXml(**kwargs)
524 ret = {}
525
526 def append_children(ret, node):
527 for child in node.childNodes:
528 if child.nodeType == xml.dom.Node.ELEMENT_NODE:
529 attrs = child.attributes
530 element = dict((attrs.item(i).localName, attrs.item(i).value)
531 for i in range(attrs.length))
532 if child.nodeName in SINGLE_ELEMENTS:
533 ret[child.nodeName] = element
534 elif child.nodeName in MULTI_ELEMENTS:
535 ret.setdefault(child.nodeName, []).append(element)
536 else:
537 raise ManifestParseError('Unhandled element "%s"' % (child.nodeName,))
538
539 append_children(element, child)
540
541 append_children(ret, doc.firstChild)
542
543 return ret
544
545 def Save(self, fd, **kwargs):
546 """Write the current manifest out to the given file descriptor."""
547 doc = self.ToXml(**kwargs)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800548 doc.writexml(fd, '', ' ', '\n', 'UTF-8')
549
Simran Basib9a1b732015-08-20 12:19:28 -0700550 def _output_manifest_project_extras(self, p, e):
551 """Manifests can modify e if they support extra project attributes."""
Simran Basib9a1b732015-08-20 12:19:28 -0700552
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700553 @property
David James8d201162013-10-11 17:03:19 -0700554 def paths(self):
555 self._Load()
556 return self._paths
557
558 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700559 def projects(self):
560 self._Load()
Anthony Kingd58bfe52014-05-05 23:30:49 +0100561 return list(self._paths.values())
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700562
563 @property
564 def remotes(self):
565 self._Load()
566 return self._remotes
567
568 @property
569 def default(self):
570 self._Load()
571 return self._default
572
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800573 @property
Doug Anderson37282b42011-03-04 11:54:18 -0800574 def repo_hooks_project(self):
575 self._Load()
576 return self._repo_hooks_project
577
578 @property
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800579 def superproject(self):
580 self._Load()
581 return self._superproject
582
583 @property
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700584 def contactinfo(self):
585 self._Load()
586 return self._contactinfo
587
588 @property
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700589 def notice(self):
590 self._Load()
591 return self._notice
592
593 @property
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700594 def manifest_server(self):
595 self._Load()
Shawn O. Pearce34fb20f2011-11-30 13:41:02 -0800596 return self._manifest_server
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700597
598 @property
Xin Lid79a4bc2020-05-20 16:03:45 -0700599 def CloneBundle(self):
600 clone_bundle = self.manifestProject.config.GetBoolean('repo.clonebundle')
601 if clone_bundle is None:
602 return False if self.manifestProject.config.GetBoolean('repo.partialclone') else True
603 else:
604 return clone_bundle
605
606 @property
Xin Li745be2e2019-06-03 11:24:30 -0700607 def CloneFilter(self):
608 if self.manifestProject.config.GetBoolean('repo.partialclone'):
609 return self.manifestProject.config.GetString('repo.clonefilter')
610 return None
611
612 @property
Raman Tennetif32f2432021-04-12 20:57:25 -0700613 def PartialCloneExclude(self):
614 exclude = self.manifest.manifestProject.config.GetString(
615 'repo.partialcloneexclude') or ''
616 return set(x.strip() for x in exclude.split(','))
617
618 @property
Raman Tennetifeb28912021-05-02 19:47:29 -0700619 def HasLocalManifests(self):
620 return self._load_local_manifests and self.local_manifests
621
622 @property
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800623 def IsMirror(self):
624 return self.manifestProject.config.GetBoolean('repo.mirror')
625
Julien Campergue335f5ef2013-10-16 11:02:35 +0200626 @property
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500627 def UseGitWorktrees(self):
628 return self.manifestProject.config.GetBoolean('repo.worktree')
629
630 @property
Julien Campergue335f5ef2013-10-16 11:02:35 +0200631 def IsArchive(self):
632 return self.manifestProject.config.GetBoolean('repo.archive')
633
Martin Kellye4e94d22017-03-21 16:05:12 -0700634 @property
635 def HasSubmodules(self):
636 return self.manifestProject.config.GetBoolean('repo.submodules')
637
Raman Tenneti080877e2021-03-09 15:19:06 -0800638 def GetDefaultGroupsStr(self):
639 """Returns the default group string for the platform."""
640 return 'default,platform-' + platform.system().lower()
641
642 def GetGroupsStr(self):
643 """Returns the manifest group string that should be synced."""
644 groups = self.manifestProject.config.GetString('manifest.groups')
645 if not groups:
646 groups = self.GetDefaultGroupsStr()
647 return groups
648
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700649 def _Unload(self):
650 self._loaded = False
651 self._projects = {}
David James8d201162013-10-11 17:03:19 -0700652 self._paths = {}
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700653 self._remotes = {}
654 self._default = None
Doug Anderson37282b42011-03-04 11:54:18 -0800655 self._repo_hooks_project = None
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800656 self._superproject = {}
Raman Tenneti993af5e2021-05-12 12:00:31 -0700657 self._contactinfo = ContactInfo(Wrapper().BUG_URL)
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700658 self._notice = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700659 self.branch = None
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700660 self._manifest_server = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700661
662 def _Load(self):
663 if not self._loaded:
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800664 m = self.manifestProject
665 b = m.GetBranch(m.CurrentBranch).merge
Shawn O. Pearce21c5c342009-06-25 16:47:30 -0700666 if b is not None and b.startswith(R_HEADS):
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800667 b = b[len(R_HEADS):]
668 self.branch = b
669
Mike Frysinger54133972021-03-01 21:38:08 -0500670 # The manifestFile was specified by the user which is why we allow include
671 # paths to point anywhere.
Colin Cross23acdd32012-04-21 00:33:54 -0700672 nodes = []
Mike Frysinger54133972021-03-01 21:38:08 -0500673 nodes.append(self._ParseManifestXml(
674 self.manifestFile, self.manifestProject.worktree,
675 restrict_includes=False))
Shawn O. Pearce5cc66792008-10-23 16:19:27 -0700676
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400677 if self._load_local_manifests and self.local_manifests:
Basil Gelloc7453502018-05-25 20:23:52 +0300678 try:
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400679 for local_file in sorted(platform_utils.listdir(self.local_manifests)):
Basil Gelloc7453502018-05-25 20:23:52 +0300680 if local_file.endswith('.xml'):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400681 local = os.path.join(self.local_manifests, local_file)
Mike Frysinger54133972021-03-01 21:38:08 -0500682 # Since local manifests are entirely managed by the user, allow
683 # them to point anywhere the user wants.
684 nodes.append(self._ParseManifestXml(
Raman Tenneti78f4dd32021-06-07 13:27:37 -0700685 local, self.repodir,
686 parent_groups=f'{LOCAL_MANIFEST_GROUP_PREFIX}:{local_file[:-4]}',
687 restrict_includes=False))
Basil Gelloc7453502018-05-25 20:23:52 +0300688 except OSError:
689 pass
David Pursehouse2d5a0df2012-11-13 02:50:36 +0900690
Joe Onorato26e24752013-01-11 12:35:53 -0800691 try:
692 self._ParseManifest(nodes)
693 except ManifestParseError as e:
694 # There was a problem parsing, unload ourselves in case they catch
695 # this error and try again later, we will show the correct error
696 self._Unload()
697 raise e
Shawn O. Pearce5cc66792008-10-23 16:19:27 -0700698
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800699 if self.IsMirror:
700 self._AddMetaProjectMirror(self.repoProject)
701 self._AddMetaProjectMirror(self.manifestProject)
702
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700703 self._loaded = True
704
Mike Frysinger54133972021-03-01 21:38:08 -0500705 def _ParseManifestXml(self, path, include_root, parent_groups='',
706 restrict_includes=True):
707 """Parse a manifest XML and return the computed nodes.
708
709 Args:
710 path: The XML file to read & parse.
711 include_root: The path to interpret include "name"s relative to.
712 parent_groups: The groups to apply to this projects.
713 restrict_includes: Whether to constrain the "name" attribute of includes.
714
715 Returns:
716 List of XML nodes.
717 """
David Pursehousef7fc8a92012-11-13 04:00:28 +0900718 try:
719 root = xml.dom.minidom.parse(path)
David Pursehouse2d5a0df2012-11-13 02:50:36 +0900720 except (OSError, xml.parsers.expat.ExpatError) as e:
David Pursehousef7fc8a92012-11-13 04:00:28 +0900721 raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
722
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700723 if not root or not root.childNodes:
Brian Harring26448742011-04-28 05:04:41 -0700724 raise ManifestParseError("no root node in %s" % (path,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700725
Jooncheol Park34acdd22012-08-27 02:25:59 +0900726 for manifest in root.childNodes:
727 if manifest.nodeName == 'manifest':
728 break
729 else:
Brian Harring26448742011-04-28 05:04:41 -0700730 raise ManifestParseError("no <manifest> in %s" % (path,))
731
Colin Cross23acdd32012-04-21 00:33:54 -0700732 nodes = []
David Pursehouse65b0ba52018-06-24 16:21:51 +0900733 for node in manifest.childNodes:
David Pursehousec1b86a22012-11-14 11:36:51 +0900734 if node.nodeName == 'include':
735 name = self._reqatt(node, 'name')
Mike Frysinger54133972021-03-01 21:38:08 -0500736 if restrict_includes:
737 msg = self._CheckLocalPath(name)
738 if msg:
739 raise ManifestInvalidPathError(
740 '<include> invalid "name": %s: %s' % (name, msg))
Fredrik de Groot352c93b2020-10-06 12:55:14 +0200741 include_groups = ''
742 if parent_groups:
743 include_groups = parent_groups
744 if node.hasAttribute('groups'):
745 include_groups = node.getAttribute('groups') + ',' + include_groups
David Pursehousec1b86a22012-11-14 11:36:51 +0900746 fp = os.path.join(include_root, name)
747 if not os.path.isfile(fp):
Mike Frysinger54133972021-03-01 21:38:08 -0500748 raise ManifestParseError("include [%s/]%s doesn't exist or isn't a file"
749 % (include_root, name))
David Pursehousec1b86a22012-11-14 11:36:51 +0900750 try:
Fredrik de Groot352c93b2020-10-06 12:55:14 +0200751 nodes.extend(self._ParseManifestXml(fp, include_root, include_groups))
David Pursehousec1b86a22012-11-14 11:36:51 +0900752 # should isolate this to the exact exception, but that's
753 # tricky. actual parsing implementation may vary.
Mike Frysinger54133972021-03-01 21:38:08 -0500754 except (KeyboardInterrupt, RuntimeError, SystemExit, ManifestParseError):
David Pursehousec1b86a22012-11-14 11:36:51 +0900755 raise
756 except Exception as e:
757 raise ManifestParseError(
Mike Frysingerec558df2019-07-05 01:38:05 -0400758 "failed parsing included manifest %s: %s" % (name, e))
David Pursehousec1b86a22012-11-14 11:36:51 +0900759 else:
Fredrik de Groot352c93b2020-10-06 12:55:14 +0200760 if parent_groups and node.nodeName == 'project':
761 nodeGroups = parent_groups
762 if node.hasAttribute('groups'):
763 nodeGroups = node.getAttribute('groups') + ',' + nodeGroups
764 node.setAttribute('groups', nodeGroups)
David Pursehousec1b86a22012-11-14 11:36:51 +0900765 nodes.append(node)
Colin Cross23acdd32012-04-21 00:33:54 -0700766 return nodes
Brian Harring26448742011-04-28 05:04:41 -0700767
Colin Cross23acdd32012-04-21 00:33:54 -0700768 def _ParseManifest(self, node_list):
769 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700770 if node.nodeName == 'remote':
771 remote = self._ParseRemote(node)
David Pursehouse717ece92012-11-13 08:49:16 +0900772 if remote:
773 if remote.name in self._remotes:
774 if remote != self._remotes[remote.name]:
775 raise ManifestParseError(
776 'remote %s already exists with different attributes' %
777 (remote.name))
778 else:
779 self._remotes[remote.name] = remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700780
Colin Cross23acdd32012-04-21 00:33:54 -0700781 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700782 if node.nodeName == 'default':
Julien Campergue74879922013-10-09 14:38:46 +0200783 new_default = self._ParseDefault(node)
784 if self._default is None:
785 self._default = new_default
786 elif new_default != self._default:
David Pursehouse37128b62013-10-15 10:48:40 +0900787 raise ManifestParseError('duplicate default in %s' %
788 (self.manifestFile))
Julien Campergue74879922013-10-09 14:38:46 +0200789
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700790 if self._default is None:
791 self._default = _Default()
792
Colin Cross23acdd32012-04-21 00:33:54 -0700793 for node in itertools.chain(*node_list):
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700794 if node.nodeName == 'notice':
795 if self._notice is not None:
Doug Anderson37282b42011-03-04 11:54:18 -0800796 raise ManifestParseError(
797 'duplicate notice in %s' %
798 (self.manifestFile))
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700799 self._notice = self._ParseNotice(node)
800
Colin Cross23acdd32012-04-21 00:33:54 -0700801 for node in itertools.chain(*node_list):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700802 if node.nodeName == 'manifest-server':
803 url = self._reqatt(node, 'url')
804 if self._manifest_server is not None:
David Pursehousec1b86a22012-11-14 11:36:51 +0900805 raise ManifestParseError(
806 'duplicate manifest-server in %s' %
807 (self.manifestFile))
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700808 self._manifest_server = url
809
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800810 def recursively_add_projects(project):
David James8d201162013-10-11 17:03:19 -0700811 projects = self._projects.setdefault(project.name, [])
812 if project.relpath is None:
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800813 raise ManifestParseError(
David James8d201162013-10-11 17:03:19 -0700814 'missing path for %s in %s' %
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800815 (project.name, self.manifestFile))
David James8d201162013-10-11 17:03:19 -0700816 if project.relpath in self._paths:
817 raise ManifestParseError(
818 'duplicate path %s in %s' %
819 (project.relpath, self.manifestFile))
820 self._paths[project.relpath] = project
821 projects.append(project)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800822 for subproject in project.subprojects:
823 recursively_add_projects(subproject)
824
Colin Cross23acdd32012-04-21 00:33:54 -0700825 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700826 if node.nodeName == 'project':
827 project = self._ParseProject(node)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800828 recursively_add_projects(project)
Josh Triplett884a3872014-06-12 14:57:29 -0700829 if node.nodeName == 'extend-project':
830 name = self._reqatt(node, 'name')
831
832 if name not in self._projects:
833 raise ManifestParseError('extend-project element specifies non-existent '
834 'project: %s' % name)
835
836 path = node.getAttribute('path')
837 groups = node.getAttribute('groups')
838 if groups:
Mike Frysinger51e39d52020-12-04 05:32:06 -0500839 groups = self._ParseList(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -0700840 revision = node.getAttribute('revision')
Kyunam Jobd0aae92020-02-04 11:38:53 +0900841 remote = node.getAttribute('remote')
842 if remote:
843 remote = self._get_remote(node)
Josh Triplett884a3872014-06-12 14:57:29 -0700844
845 for p in self._projects[name]:
846 if path and p.relpath != path:
847 continue
848 if groups:
849 p.groups.extend(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -0700850 if revision:
851 p.revisionExpr = revision
Miguel Gaio1f207762020-07-17 14:09:13 +0200852 if IsId(revision):
853 p.revisionId = revision
854 else:
855 p.revisionId = None
Kyunam Jobd0aae92020-02-04 11:38:53 +0900856 if remote:
857 p.remote = remote.ToRemoteSpec(name)
Doug Anderson37282b42011-03-04 11:54:18 -0800858 if node.nodeName == 'repo-hooks':
859 # Get the name of the project and the (space-separated) list of enabled.
860 repo_hooks_project = self._reqatt(node, 'in-project')
Mike Frysinger51e39d52020-12-04 05:32:06 -0500861 enabled_repo_hooks = self._ParseList(self._reqatt(node, 'enabled-list'))
Doug Anderson37282b42011-03-04 11:54:18 -0800862
863 # Only one project can be the hooks project
864 if self._repo_hooks_project is not None:
865 raise ManifestParseError(
866 'duplicate repo-hooks in %s' %
867 (self.manifestFile))
868
869 # Store a reference to the Project.
870 try:
David James8d201162013-10-11 17:03:19 -0700871 repo_hooks_projects = self._projects[repo_hooks_project]
Doug Anderson37282b42011-03-04 11:54:18 -0800872 except KeyError:
873 raise ManifestParseError(
874 'project %s not found for repo-hooks' %
875 (repo_hooks_project))
876
David James8d201162013-10-11 17:03:19 -0700877 if len(repo_hooks_projects) != 1:
878 raise ManifestParseError(
879 'internal error parsing repo-hooks in %s' %
880 (self.manifestFile))
881 self._repo_hooks_project = repo_hooks_projects[0]
882
Doug Anderson37282b42011-03-04 11:54:18 -0800883 # Store the enabled hooks in the Project object.
884 self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
Raman Tenneti1bb4fb22021-01-07 16:50:45 -0800885 if node.nodeName == 'superproject':
886 name = self._reqatt(node, 'name')
887 # There can only be one superproject.
888 if self._superproject.get('name'):
889 raise ManifestParseError(
890 'duplicate superproject in %s' %
891 (self.manifestFile))
892 self._superproject['name'] = name
893 remote_name = node.getAttribute('remote')
894 if not remote_name:
895 remote = self._default.remote
896 else:
897 remote = self._get_remote(node)
898 if remote is None:
899 raise ManifestParseError("no remote for superproject %s within %s" %
900 (name, self.manifestFile))
901 self._superproject['remote'] = remote.ToRemoteSpec(name)
Raman Tenneti1c3f57e2021-05-04 12:32:13 -0700902 if node.nodeName == 'contactinfo':
903 bugurl = self._reqatt(node, 'bugurl')
904 # This element can be repeated, later entries will clobber earlier ones.
Raman Tenneti993af5e2021-05-12 12:00:31 -0700905 self._contactinfo = ContactInfo(bugurl)
906
Colin Cross23acdd32012-04-21 00:33:54 -0700907 if node.nodeName == 'remove-project':
908 name = self._reqatt(node, 'name')
David Jamesb8433df2014-01-30 10:11:17 -0800909
910 if name not in self._projects:
David Pursehousef9107482012-11-16 19:12:32 +0900911 raise ManifestParseError('remove-project element specifies non-existent '
912 'project: %s' % name)
Colin Cross23acdd32012-04-21 00:33:54 -0700913
David Jamesb8433df2014-01-30 10:11:17 -0800914 for p in self._projects[name]:
915 del self._paths[p.relpath]
916 del self._projects[name]
917
Colin Cross23acdd32012-04-21 00:33:54 -0700918 # If the manifest removes the hooks project, treat it as if it deleted
919 # the repo-hooks element too.
920 if self._repo_hooks_project and (self._repo_hooks_project.name == name):
921 self._repo_hooks_project = None
922
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800923 def _AddMetaProjectMirror(self, m):
924 name = None
925 m_url = m.GetRemote(m.remote.name).url
926 if m_url.endswith('/.git'):
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530927 raise ManifestParseError('refusing to mirror %s' % m_url)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800928
929 if self._default and self._default.remote:
Conley Owensceea3682011-10-20 10:45:47 -0700930 url = self._default.remote.resolvedFetchUrl
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800931 if not url.endswith('/'):
932 url += '/'
933 if m_url.startswith(url):
934 remote = self._default.remote
935 name = m_url[len(url):]
936
937 if name is None:
938 s = m_url.rindex('/') + 1
Conley Owensdb728cd2011-09-26 16:34:01 -0700939 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Shawn O. Pearcef35b2d92012-08-02 11:46:22 -0700940 remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800941 name = m_url[s:]
942
943 if name.endswith('.git'):
944 name = name[:-4]
945
946 if name not in self._projects:
947 m.PreSync()
948 gitdir = os.path.join(self.topdir, '%s.git' % name)
David Pursehousee5913ae2020-02-12 13:56:59 +0900949 project = Project(manifest=self,
950 name=name,
951 remote=remote.ToRemoteSpec(name),
952 gitdir=gitdir,
953 objdir=gitdir,
954 worktree=None,
955 relpath=name or None,
956 revisionExpr=m.revisionExpr,
957 revisionId=None)
David James8d201162013-10-11 17:03:19 -0700958 self._projects[project.name] = [project]
Kwanhong Leeccd218c2014-02-17 13:07:32 +0900959 self._paths[project.relpath] = project
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800960
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700961 def _ParseRemote(self, node):
962 """
963 reads a <remote> element from the manifest file
964 """
965 name = self._reqatt(node, 'name')
Yestin Sunb292b982012-07-02 07:32:50 -0700966 alias = node.getAttribute('alias')
967 if alias == '':
968 alias = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700969 fetch = self._reqatt(node, 'fetch')
Steve Raed6480452016-08-10 15:00:00 -0700970 pushUrl = node.getAttribute('pushurl')
971 if pushUrl == '':
972 pushUrl = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700973 review = node.getAttribute('review')
Shawn O. Pearceae6e0942008-11-06 10:25:35 -0800974 if review == '':
975 review = None
Anthony King36ea2fb2014-05-06 11:54:01 +0100976 revision = node.getAttribute('revision')
977 if revision == '':
978 revision = None
Conley Owensdb728cd2011-09-26 16:34:01 -0700979 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Steve Raed6480452016-08-10 15:00:00 -0700980 return _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700981
982 def _ParseDefault(self, node):
983 """
984 reads a <default> element from the manifest file
985 """
986 d = _Default()
987 d.remote = self._get_remote(node)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700988 d.revisionExpr = node.getAttribute('revision')
989 if d.revisionExpr == '':
990 d.revisionExpr = None
Anatol Pomazau79770d22012-04-20 14:41:59 -0700991
Bryan Jacobsf609f912013-05-06 13:36:24 -0400992 d.destBranchExpr = node.getAttribute('dest-branch') or None
Nasser Grainawida403412018-05-04 12:53:29 -0600993 d.upstreamExpr = node.getAttribute('upstream') or None
Bryan Jacobsf609f912013-05-06 13:36:24 -0400994
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500995 d.sync_j = XmlInt(node, 'sync-j', 1)
996 if d.sync_j <= 0:
997 raise ManifestParseError('%s: sync-j must be greater than 0, not "%s"' %
998 (self.manifestFile, d.sync_j))
Anatol Pomazau79770d22012-04-20 14:41:59 -0700999
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001000 d.sync_c = XmlBool(node, 'sync-c', False)
1001 d.sync_s = XmlBool(node, 'sync-s', False)
1002 d.sync_tags = XmlBool(node, 'sync-tags', True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001003 return d
1004
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001005 def _ParseNotice(self, node):
1006 """
1007 reads a <notice> element from the manifest file
1008
1009 The <notice> element is distinct from other tags in the XML in that the
1010 data is conveyed between the start and end tag (it's not an empty-element
1011 tag).
1012
1013 The white space (carriage returns, indentation) for the notice element is
1014 relevant and is parsed in a way that is based on how python docstrings work.
1015 In fact, the code is remarkably similar to here:
1016 http://www.python.org/dev/peps/pep-0257/
1017 """
1018 # Get the data out of the node...
1019 notice = node.childNodes[0].data
1020
1021 # Figure out minimum indentation, skipping the first line (the same line
1022 # as the <notice> tag)...
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301023 minIndent = sys.maxsize
Doug Anderson2b8db3c2010-11-01 15:08:06 -07001024 lines = notice.splitlines()
1025 for line in lines[1:]:
1026 lstrippedLine = line.lstrip()
1027 if lstrippedLine:
1028 indent = len(line) - len(lstrippedLine)
1029 minIndent = min(indent, minIndent)
1030
1031 # Strip leading / trailing blank lines and also indentation.
1032 cleanLines = [lines[0].strip()]
1033 for line in lines[1:]:
1034 cleanLines.append(line[minIndent:].rstrip())
1035
1036 # Clear completely blank lines from front and back...
1037 while cleanLines and not cleanLines[0]:
1038 del cleanLines[0]
1039 while cleanLines and not cleanLines[-1]:
1040 del cleanLines[-1]
1041
1042 return '\n'.join(cleanLines)
1043
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001044 def _JoinName(self, parent_name, name):
1045 return os.path.join(parent_name, name)
1046
1047 def _UnjoinName(self, parent_name, name):
1048 return os.path.relpath(name, parent_name)
1049
David Pursehousee5913ae2020-02-12 13:56:59 +09001050 def _ParseProject(self, node, parent=None, **extra_proj_attrs):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001051 """
1052 reads a <project> element from the manifest file
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -07001053 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001054 name = self._reqatt(node, 'name')
Mike Frysingera29424e2021-02-25 21:53:49 -05001055 msg = self._CheckLocalPath(name, dir_ok=True)
1056 if msg:
1057 raise ManifestInvalidPathError(
1058 '<project> invalid "name": %s: %s' % (name, msg))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001059 if parent:
1060 name = self._JoinName(parent.name, name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001061
1062 remote = self._get_remote(node)
1063 if remote is None:
1064 remote = self._default.remote
1065 if remote is None:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301066 raise ManifestParseError("no remote for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001067 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001068
Anthony King36ea2fb2014-05-06 11:54:01 +01001069 revisionExpr = node.getAttribute('revision') or remote.revision
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -07001070 if not revisionExpr:
1071 revisionExpr = self._default.revisionExpr
1072 if not revisionExpr:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301073 raise ManifestParseError("no revision for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001074 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001075
1076 path = node.getAttribute('path')
1077 if not path:
1078 path = name
Mike Frysingera29424e2021-02-25 21:53:49 -05001079 else:
Mike Frysinger0458faa2021-03-10 23:35:44 -05001080 # NB: The "." project is handled specially in Project.Sync_LocalHalf.
1081 msg = self._CheckLocalPath(path, dir_ok=True, cwd_dot_ok=True)
Mike Frysingera29424e2021-02-25 21:53:49 -05001082 if msg:
1083 raise ManifestInvalidPathError(
1084 '<project> invalid "path": %s: %s' % (path, msg))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001085
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001086 rebase = XmlBool(node, 'rebase', True)
1087 sync_c = XmlBool(node, 'sync-c', False)
1088 sync_s = XmlBool(node, 'sync-s', self._default.sync_s)
1089 sync_tags = XmlBool(node, 'sync-tags', self._default.sync_tags)
Mike Pontillod3153822012-02-28 11:53:24 -08001090
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001091 clone_depth = XmlInt(node, 'clone-depth')
1092 if clone_depth is not None and clone_depth <= 0:
1093 raise ManifestParseError('%s: clone-depth must be greater than 0, not "%s"' %
1094 (self.manifestFile, clone_depth))
David Pursehouseede7f122012-11-27 22:25:30 +09001095
Bryan Jacobsf609f912013-05-06 13:36:24 -04001096 dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
1097
Nasser Grainawida403412018-05-04 12:53:29 -06001098 upstream = node.getAttribute('upstream') or self._default.upstreamExpr
Brian Harring14a66742012-09-28 20:21:57 -07001099
Conley Owens971de8e2012-04-16 10:36:08 -07001100 groups = ''
1101 if node.hasAttribute('groups'):
1102 groups = node.getAttribute('groups')
Mike Frysinger51e39d52020-12-04 05:32:06 -05001103 groups = self._ParseList(groups)
Brian Harring7da13142012-06-15 02:24:20 -07001104
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001105 if parent is None:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001106 relpath, worktree, gitdir, objdir, use_git_worktrees = \
1107 self.GetProjectPaths(name, path)
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001108 else:
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001109 use_git_worktrees = False
David James8d201162013-10-11 17:03:19 -07001110 relpath, worktree, gitdir, objdir = \
1111 self.GetSubprojectPaths(parent, name, path)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001112
1113 default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
1114 groups.extend(set(default_groups).difference(groups))
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -07001115
Scott Fandb83b1b2013-02-28 09:34:14 +08001116 if self.IsMirror and node.hasAttribute('force-path'):
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -05001117 if XmlBool(node, 'force-path', False):
Scott Fandb83b1b2013-02-28 09:34:14 +08001118 gitdir = os.path.join(self.topdir, '%s.git' % path)
1119
David Pursehousee5913ae2020-02-12 13:56:59 +09001120 project = Project(manifest=self,
1121 name=name,
1122 remote=remote.ToRemoteSpec(name),
1123 gitdir=gitdir,
1124 objdir=objdir,
1125 worktree=worktree,
1126 relpath=relpath,
1127 revisionExpr=revisionExpr,
1128 revisionId=None,
1129 rebase=rebase,
1130 groups=groups,
1131 sync_c=sync_c,
1132 sync_s=sync_s,
1133 sync_tags=sync_tags,
1134 clone_depth=clone_depth,
1135 upstream=upstream,
1136 parent=parent,
1137 dest_branch=dest_branch,
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001138 use_git_worktrees=use_git_worktrees,
Simran Basib9a1b732015-08-20 12:19:28 -07001139 **extra_proj_attrs)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001140
1141 for n in node.childNodes:
Shawn O. Pearce242b5262009-05-19 13:00:29 -07001142 if n.nodeName == 'copyfile':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001143 self._ParseCopyFile(project, n)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001144 if n.nodeName == 'linkfile':
1145 self._ParseLinkFile(project, n)
James W. Mills24c13082012-04-12 15:04:13 -05001146 if n.nodeName == 'annotation':
1147 self._ParseAnnotation(project, n)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001148 if n.nodeName == 'project':
David Pursehousee5913ae2020-02-12 13:56:59 +09001149 project.subprojects.append(self._ParseProject(n, parent=project))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001150
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001151 return project
1152
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001153 def GetProjectPaths(self, name, path):
Mike Frysingercebf2272020-05-26 01:02:29 -04001154 # The manifest entries might have trailing slashes. Normalize them to avoid
1155 # unexpected filesystem behavior since we do string concatenation below.
1156 path = path.rstrip('/')
1157 name = name.rstrip('/')
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001158 use_git_worktrees = False
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001159 relpath = path
1160 if self.IsMirror:
1161 worktree = None
1162 gitdir = os.path.join(self.topdir, '%s.git' % name)
David James8d201162013-10-11 17:03:19 -07001163 objdir = gitdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001164 else:
1165 worktree = os.path.join(self.topdir, path).replace('\\', '/')
1166 gitdir = os.path.join(self.repodir, 'projects', '%s.git' % path)
Mike Frysinger979d5bd2020-02-09 02:28:34 -05001167 # We allow people to mix git worktrees & non-git worktrees for now.
1168 # This allows for in situ migration of repo clients.
1169 if os.path.exists(gitdir) or not self.UseGitWorktrees:
1170 objdir = os.path.join(self.repodir, 'project-objects', '%s.git' % name)
1171 else:
1172 use_git_worktrees = True
1173 gitdir = os.path.join(self.repodir, 'worktrees', '%s.git' % name)
1174 objdir = gitdir
1175 return relpath, worktree, gitdir, objdir, use_git_worktrees
David James8d201162013-10-11 17:03:19 -07001176
1177 def GetProjectsWithName(self, name):
1178 return self._projects.get(name, [])
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001179
1180 def GetSubprojectName(self, parent, submodule_path):
1181 return os.path.join(parent.name, submodule_path)
1182
1183 def _JoinRelpath(self, parent_relpath, relpath):
1184 return os.path.join(parent_relpath, relpath)
1185
1186 def _UnjoinRelpath(self, parent_relpath, relpath):
1187 return os.path.relpath(relpath, parent_relpath)
1188
David James8d201162013-10-11 17:03:19 -07001189 def GetSubprojectPaths(self, parent, name, path):
Mike Frysingercebf2272020-05-26 01:02:29 -04001190 # The manifest entries might have trailing slashes. Normalize them to avoid
1191 # unexpected filesystem behavior since we do string concatenation below.
1192 path = path.rstrip('/')
1193 name = name.rstrip('/')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001194 relpath = self._JoinRelpath(parent.relpath, path)
1195 gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
David James8d201162013-10-11 17:03:19 -07001196 objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001197 if self.IsMirror:
1198 worktree = None
1199 else:
1200 worktree = os.path.join(parent.worktree, path).replace('\\', '/')
David James8d201162013-10-11 17:03:19 -07001201 return relpath, worktree, gitdir, objdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001202
Mike Frysinger04122b72019-07-31 23:32:58 -04001203 @staticmethod
Mike Frysingera00c5f42021-02-25 18:26:31 -05001204 def _CheckLocalPath(path, dir_ok=False, cwd_dot_ok=False):
1205 """Verify |path| is reasonable for use in filesystem paths.
1206
Mike Frysingera29424e2021-02-25 21:53:49 -05001207 Used with <copyfile> & <linkfile> & <project> elements.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001208
1209 This only validates the |path| in isolation: it does not check against the
1210 current filesystem state. Thus it is suitable as a first-past in a parser.
1211
1212 It enforces a number of constraints:
1213 * No empty paths.
1214 * No "~" in paths.
1215 * No Unicode codepoints that filesystems might elide when normalizing.
1216 * No relative path components like "." or "..".
1217 * No absolute paths.
1218 * No ".git" or ".repo*" path components.
1219
1220 Args:
1221 path: The path name to validate.
1222 dir_ok: Whether |path| may force a directory (e.g. end in a /).
1223 cwd_dot_ok: Whether |path| may be just ".".
1224
1225 Returns:
1226 None if |path| is OK, a failure message otherwise.
1227 """
1228 if not path:
1229 return 'empty paths not allowed'
1230
Mike Frysinger04122b72019-07-31 23:32:58 -04001231 if '~' in path:
1232 return '~ not allowed (due to 8.3 filenames on Windows filesystems)'
1233
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001234 path_codepoints = set(path)
1235
Mike Frysinger04122b72019-07-31 23:32:58 -04001236 # Some filesystems (like Apple's HFS+) try to normalize Unicode codepoints
1237 # which means there are alternative names for ".git". Reject paths with
1238 # these in it as there shouldn't be any reasonable need for them here.
1239 # The set of codepoints here was cribbed from jgit's implementation:
1240 # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
1241 BAD_CODEPOINTS = {
1242 u'\u200C', # ZERO WIDTH NON-JOINER
1243 u'\u200D', # ZERO WIDTH JOINER
1244 u'\u200E', # LEFT-TO-RIGHT MARK
1245 u'\u200F', # RIGHT-TO-LEFT MARK
1246 u'\u202A', # LEFT-TO-RIGHT EMBEDDING
1247 u'\u202B', # RIGHT-TO-LEFT EMBEDDING
1248 u'\u202C', # POP DIRECTIONAL FORMATTING
1249 u'\u202D', # LEFT-TO-RIGHT OVERRIDE
1250 u'\u202E', # RIGHT-TO-LEFT OVERRIDE
1251 u'\u206A', # INHIBIT SYMMETRIC SWAPPING
1252 u'\u206B', # ACTIVATE SYMMETRIC SWAPPING
1253 u'\u206C', # INHIBIT ARABIC FORM SHAPING
1254 u'\u206D', # ACTIVATE ARABIC FORM SHAPING
1255 u'\u206E', # NATIONAL DIGIT SHAPES
1256 u'\u206F', # NOMINAL DIGIT SHAPES
1257 u'\uFEFF', # ZERO WIDTH NO-BREAK SPACE
1258 }
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001259 if BAD_CODEPOINTS & path_codepoints:
Mike Frysinger04122b72019-07-31 23:32:58 -04001260 # This message is more expansive than reality, but should be fine.
1261 return 'Unicode combining characters not allowed'
1262
Mike Frysingerf69c7ee2021-04-29 23:15:31 -04001263 # Reject newlines as there shouldn't be any legitmate use for them, they'll
1264 # be confusing to users, and they can easily break tools that expect to be
1265 # able to iterate over newline delimited lists. This even applies to our
1266 # own code like .repo/project.list.
1267 if {'\r', '\n'} & path_codepoints:
1268 return 'Newlines not allowed'
1269
Mike Frysinger04122b72019-07-31 23:32:58 -04001270 # Assume paths might be used on case-insensitive filesystems.
1271 path = path.lower()
1272
Mike Frysingerd9254592020-02-19 22:36:26 -05001273 # Split up the path by its components. We can't use os.path.sep exclusively
1274 # as some platforms (like Windows) will convert / to \ and that bypasses all
1275 # our constructed logic here. Especially since manifest authors only use
1276 # / in their paths.
1277 resep = re.compile(r'[/%s]' % re.escape(os.path.sep))
Mike Frysinger0458faa2021-03-10 23:35:44 -05001278 # Strip off trailing slashes as those only produce '' elements, and we use
1279 # parts to look for individual bad components.
1280 parts = resep.split(path.rstrip('/'))
Mike Frysingerd9254592020-02-19 22:36:26 -05001281
Mike Frysingerae625412020-02-10 17:10:03 -05001282 # Some people use src="." to create stable links to projects. Lets allow
1283 # that but reject all other uses of "." to keep things simple.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001284 if not cwd_dot_ok or parts != ['.']:
Mike Frysingerae625412020-02-10 17:10:03 -05001285 for part in set(parts):
1286 if part in {'.', '..', '.git'} or part.startswith('.repo'):
1287 return 'bad component: %s' % (part,)
Mike Frysinger04122b72019-07-31 23:32:58 -04001288
Mike Frysingera00c5f42021-02-25 18:26:31 -05001289 if not dir_ok and resep.match(path[-1]):
Mike Frysinger04122b72019-07-31 23:32:58 -04001290 return 'dirs not allowed'
1291
Mike Frysingerd9254592020-02-19 22:36:26 -05001292 # NB: The two abspath checks here are to handle platforms with multiple
1293 # filesystem path styles (e.g. Windows).
Mike Frysinger04122b72019-07-31 23:32:58 -04001294 norm = os.path.normpath(path)
Mike Frysingerd9254592020-02-19 22:36:26 -05001295 if (norm == '..' or
1296 (len(norm) >= 3 and norm.startswith('..') and resep.match(norm[0])) or
1297 os.path.isabs(norm) or
1298 norm.startswith('/')):
Mike Frysinger04122b72019-07-31 23:32:58 -04001299 return 'path cannot be outside'
1300
1301 @classmethod
1302 def _ValidateFilePaths(cls, element, src, dest):
1303 """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
1304
1305 We verify the path independent of any filesystem state as we won't have a
1306 checkout available to compare to. i.e. This is for parsing validation
1307 purposes only.
1308
1309 We'll do full/live sanity checking before we do the actual filesystem
1310 modifications in _CopyFile/_LinkFile/etc...
1311 """
1312 # |dest| is the file we write to or symlink we create.
1313 # It is relative to the top of the repo client checkout.
1314 msg = cls._CheckLocalPath(dest)
1315 if msg:
1316 raise ManifestInvalidPathError(
1317 '<%s> invalid "dest": %s: %s' % (element, dest, msg))
1318
1319 # |src| is the file we read from or path we point to for symlinks.
1320 # It is relative to the top of the git project checkout.
Mike Frysingera00c5f42021-02-25 18:26:31 -05001321 is_linkfile = element == 'linkfile'
1322 msg = cls._CheckLocalPath(src, dir_ok=is_linkfile, cwd_dot_ok=is_linkfile)
Mike Frysinger04122b72019-07-31 23:32:58 -04001323 if msg:
1324 raise ManifestInvalidPathError(
1325 '<%s> invalid "src": %s: %s' % (element, src, msg))
1326
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001327 def _ParseCopyFile(self, project, node):
1328 src = self._reqatt(node, 'src')
1329 dest = self._reqatt(node, 'dest')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001330 if not self.IsMirror:
1331 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001332 # dest is relative to the top of the tree.
1333 # We only validate paths if we actually plan to process them.
1334 self._ValidateFilePaths('copyfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001335 project.AddCopyFile(src, dest, self.topdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001336
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001337 def _ParseLinkFile(self, project, node):
1338 src = self._reqatt(node, 'src')
1339 dest = self._reqatt(node, 'dest')
1340 if not self.IsMirror:
1341 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001342 # dest is relative to the top of the tree.
1343 # We only validate paths if we actually plan to process them.
1344 self._ValidateFilePaths('linkfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001345 project.AddLinkFile(src, dest, self.topdir)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001346
James W. Mills24c13082012-04-12 15:04:13 -05001347 def _ParseAnnotation(self, project, node):
1348 name = self._reqatt(node, 'name')
1349 value = self._reqatt(node, 'value')
1350 try:
1351 keep = self._reqatt(node, 'keep').lower()
1352 except ManifestParseError:
1353 keep = "true"
1354 if keep != "true" and keep != "false":
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301355 raise ManifestParseError('optional "keep" attribute must be '
David Pursehouseabdf7502020-02-12 14:58:39 +09001356 '"true" or "false"')
James W. Mills24c13082012-04-12 15:04:13 -05001357 project.AddAnnotation(name, value, keep)
1358
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001359 def _get_remote(self, node):
1360 name = node.getAttribute('remote')
1361 if not name:
1362 return None
1363
1364 v = self._remotes.get(name)
1365 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301366 raise ManifestParseError("remote %s not defined in %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001367 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001368 return v
1369
1370 def _reqatt(self, node, attname):
1371 """
1372 reads a required attribute from the node.
1373 """
1374 v = node.getAttribute(attname)
1375 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301376 raise ManifestParseError("no %s in <%s> within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001377 (attname, node.nodeName, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001378 return v
Julien Camperguedd654222014-01-09 16:21:37 +01001379
1380 def projectsDiff(self, manifest):
1381 """return the projects differences between two manifests.
1382
1383 The diff will be from self to given manifest.
1384
1385 """
1386 fromProjects = self.paths
1387 toProjects = manifest.paths
1388
Anthony King7446c592014-05-06 09:19:39 +01001389 fromKeys = sorted(fromProjects.keys())
1390 toKeys = sorted(toProjects.keys())
Julien Camperguedd654222014-01-09 16:21:37 +01001391
1392 diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
1393
1394 for proj in fromKeys:
David Pursehouseeeff3532020-02-12 11:24:10 +09001395 if proj not in toKeys:
Julien Camperguedd654222014-01-09 16:21:37 +01001396 diff['removed'].append(fromProjects[proj])
1397 else:
1398 fromProj = fromProjects[proj]
1399 toProj = toProjects[proj]
1400 try:
1401 fromRevId = fromProj.GetCommitRevisionId()
1402 toRevId = toProj.GetCommitRevisionId()
1403 except ManifestInvalidRevisionError:
1404 diff['unreachable'].append((fromProj, toProj))
1405 else:
1406 if fromRevId != toRevId:
1407 diff['changed'].append((fromProj, toProj))
1408 toKeys.remove(proj)
1409
1410 for proj in toKeys:
1411 diff['added'].append(toProjects[proj])
1412
1413 return diff
Simran Basib9a1b732015-08-20 12:19:28 -07001414
1415
1416class GitcManifest(XmlManifest):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001417 """Parser for GitC (git-in-the-cloud) manifests."""
Simran Basib9a1b732015-08-20 12:19:28 -07001418
David Pursehousee5913ae2020-02-12 13:56:59 +09001419 def _ParseProject(self, node, parent=None):
Simran Basib9a1b732015-08-20 12:19:28 -07001420 """Override _ParseProject and add support for GITC specific attributes."""
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001421 return super()._ParseProject(
Simran Basib9a1b732015-08-20 12:19:28 -07001422 node, parent=parent, old_revision=node.getAttribute('old-revision'))
1423
1424 def _output_manifest_project_extras(self, p, e):
1425 """Output GITC Specific Project attributes"""
1426 if p.old_revision:
Stefan Beller66851062016-06-17 16:40:08 -07001427 e.setAttribute('old-revision', str(p.old_revision))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001428
1429
1430class RepoClient(XmlManifest):
1431 """Manages a repo client checkout."""
1432
1433 def __init__(self, repodir, manifest_file=None):
1434 self.isGitcClient = False
1435
1436 if os.path.exists(os.path.join(repodir, LOCAL_MANIFEST_NAME)):
1437 print('error: %s is not supported; put local manifests in `%s` instead' %
1438 (LOCAL_MANIFEST_NAME, os.path.join(repodir, LOCAL_MANIFESTS_DIR_NAME)),
1439 file=sys.stderr)
1440 sys.exit(1)
1441
1442 if manifest_file is None:
1443 manifest_file = os.path.join(repodir, MANIFEST_FILE_NAME)
1444 local_manifests = os.path.abspath(os.path.join(repodir, LOCAL_MANIFESTS_DIR_NAME))
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001445 super().__init__(repodir, manifest_file, local_manifests)
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001446
1447 # TODO: Completely separate manifest logic out of the client.
1448 self.manifest = self
1449
1450
1451class GitcClient(RepoClient, GitcManifest):
1452 """Manages a GitC client checkout."""
1453
1454 def __init__(self, repodir, gitc_client_name):
1455 """Initialize the GitcManifest object."""
1456 self.gitc_client_name = gitc_client_name
1457 self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
1458 gitc_client_name)
1459
Mike Frysinger5d9c4972021-02-19 13:34:09 -05001460 super().__init__(repodir, os.path.join(self.gitc_client_dir, '.manifest'))
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -04001461 self.isGitcClient = True