blob: fe0735a844abc836c8aee27c69b3ecb370743d32 [file] [log] [blame]
Mike Frysingerf6013762019-06-13 02:30:51 -04001# -*- coding:utf-8 -*-
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002#
3# Copyright (C) 2008 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
Sarah Owenscecd1d82012-11-01 22:59:27 -070017from __future__ import print_function
Colin Cross23acdd32012-04-21 00:33:54 -070018import itertools
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070019import os
Conley Owensdb728cd2011-09-26 16:34:01 -070020import re
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070021import sys
David Pursehouse59bbb582013-05-17 10:49:33 +090022import xml.dom.minidom
23
24from pyversion import is_python3
25if is_python3():
Chirayu Desai217ea7d2013-03-01 19:14:38 +053026 import urllib.parse
David Pursehouse59bbb582013-05-17 10:49:33 +090027else:
Chirayu Desai217ea7d2013-03-01 19:14:38 +053028 import imp
29 import urlparse
30 urllib = imp.new_module('urllib')
Chirayu Desaidb2ad9d2013-06-11 13:42:25 +053031 urllib.parse = urlparse
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070032
Simran Basib9a1b732015-08-20 12:19:28 -070033import gitc_utils
David Pursehousee15c65a2012-08-22 10:46:11 +090034from git_config import GitConfig
David Pursehousee00aa6b2012-09-11 14:33:51 +090035from git_refs import R_HEADS, HEAD
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070036import platform_utils
David Pursehousee00aa6b2012-09-11 14:33:51 +090037from project import RemoteSpec, Project, MetaProject
Mike Frysinger04122b72019-07-31 23:32:58 -040038from error import (ManifestParseError, ManifestInvalidPathError,
39 ManifestInvalidRevisionError)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070040
41MANIFEST_FILE_NAME = 'manifest.xml'
Shawn O. Pearce5cc66792008-10-23 16:19:27 -070042LOCAL_MANIFEST_NAME = 'local_manifest.xml'
David Pursehouse2d5a0df2012-11-13 02:50:36 +090043LOCAL_MANIFESTS_DIR_NAME = 'local_manifests'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070044
Anthony Kingcb07ba72015-03-28 23:26:04 +000045# urljoin gets confused if the scheme is not known.
Joe Kilner6e310792016-10-27 15:53:53 -070046urllib.parse.uses_relative.extend([
47 'ssh',
48 'git',
49 'persistent-https',
50 'sso',
51 'rpc'])
52urllib.parse.uses_netloc.extend([
53 'ssh',
54 'git',
55 'persistent-https',
56 'sso',
57 'rpc'])
Conley Owensdb728cd2011-09-26 16:34:01 -070058
David Pursehouse819827a2020-02-12 15:20:19 +090059
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070060class _Default(object):
61 """Project defaults within the manifest."""
62
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -070063 revisionExpr = None
Conley Owensb6a16e62013-09-25 15:06:09 -070064 destBranchExpr = None
Nasser Grainawida403412018-05-04 12:53:29 -060065 upstreamExpr = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070066 remote = None
Shawn O. Pearce6392c872011-09-22 17:44:31 -070067 sync_j = 1
Anatol Pomazau79770d22012-04-20 14:41:59 -070068 sync_c = False
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +080069 sync_s = False
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +090070 sync_tags = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070071
Julien Campergue74879922013-10-09 14:38:46 +020072 def __eq__(self, other):
73 return self.__dict__ == other.__dict__
74
75 def __ne__(self, other):
76 return self.__dict__ != other.__dict__
77
David Pursehouse819827a2020-02-12 15:20:19 +090078
Shawn O. Pearced1f70d92009-05-19 14:58:02 -070079class _XmlRemote(object):
80 def __init__(self,
81 name,
Yestin Sunb292b982012-07-02 07:32:50 -070082 alias=None,
Shawn O. Pearced1f70d92009-05-19 14:58:02 -070083 fetch=None,
Steve Raed6480452016-08-10 15:00:00 -070084 pushUrl=None,
Conley Owensdb728cd2011-09-26 16:34:01 -070085 manifestUrl=None,
Anthony King36ea2fb2014-05-06 11:54:01 +010086 review=None,
Jonathan Nieder93719792015-03-17 11:29:58 -070087 revision=None):
Shawn O. Pearced1f70d92009-05-19 14:58:02 -070088 self.name = name
89 self.fetchUrl = fetch
Steve Raed6480452016-08-10 15:00:00 -070090 self.pushUrl = pushUrl
Conley Owensdb728cd2011-09-26 16:34:01 -070091 self.manifestUrl = manifestUrl
Yestin Sunb292b982012-07-02 07:32:50 -070092 self.remoteAlias = alias
Shawn O. Pearced1f70d92009-05-19 14:58:02 -070093 self.reviewUrl = review
Anthony King36ea2fb2014-05-06 11:54:01 +010094 self.revision = revision
Conley Owensceea3682011-10-20 10:45:47 -070095 self.resolvedFetchUrl = self._resolveFetchUrl()
Shawn O. Pearced1f70d92009-05-19 14:58:02 -070096
David Pursehouse717ece92012-11-13 08:49:16 +090097 def __eq__(self, other):
98 return self.__dict__ == other.__dict__
99
100 def __ne__(self, other):
101 return self.__dict__ != other.__dict__
102
Conley Owensceea3682011-10-20 10:45:47 -0700103 def _resolveFetchUrl(self):
104 url = self.fetchUrl.rstrip('/')
Conley Owensdb728cd2011-09-26 16:34:01 -0700105 manifestUrl = self.manifestUrl.rstrip('/')
Conley Owens2d0f5082014-01-31 15:03:51 -0800106 # urljoin will gets confused over quite a few things. The ones we care
107 # about here are:
108 # * no scheme in the base url, like <hostname:port>
Anthony Kingcb07ba72015-03-28 23:26:04 +0000109 # We handle no scheme by replacing it with an obscure protocol, gopher
110 # and then replacing it with the original when we are done.
111
Conley Owensdb728cd2011-09-26 16:34:01 -0700112 if manifestUrl.find(':') != manifestUrl.find('/') - 1:
Conley Owens4ccad752015-04-29 10:45:37 -0700113 url = urllib.parse.urljoin('gopher://' + manifestUrl, url)
114 url = re.sub(r'^gopher://', '', url)
Anthony Kingcb07ba72015-03-28 23:26:04 +0000115 else:
116 url = urllib.parse.urljoin(manifestUrl, url)
Shawn Pearcea9f11b32013-01-02 15:40:48 -0800117 return url
Conley Owensceea3682011-10-20 10:45:47 -0700118
119 def ToRemoteSpec(self, projectName):
David Rileye0684ad2017-04-05 00:02:59 -0700120 fetchUrl = self.resolvedFetchUrl.rstrip('/')
121 url = fetchUrl + '/' + projectName
Yestin Sunb292b982012-07-02 07:32:50 -0700122 remoteName = self.name
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700123 if self.remoteAlias:
David Pursehouse37128b62013-10-15 10:48:40 +0900124 remoteName = self.remoteAlias
Dan Willemsen96c2d652016-04-06 16:03:54 -0700125 return RemoteSpec(remoteName,
126 url=url,
Steve Raed6480452016-08-10 15:00:00 -0700127 pushUrl=self.pushUrl,
Dan Willemsen96c2d652016-04-06 16:03:54 -0700128 review=self.reviewUrl,
David Rileye0684ad2017-04-05 00:02:59 -0700129 orig_name=self.name,
130 fetchUrl=self.fetchUrl)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700131
David Pursehouse819827a2020-02-12 15:20:19 +0900132
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700133class XmlManifest(object):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700134 """manages the repo configuration file"""
135
136 def __init__(self, repodir):
137 self.repodir = os.path.abspath(repodir)
138 self.topdir = os.path.dirname(self.repodir)
139 self.manifestFile = os.path.join(self.repodir, MANIFEST_FILE_NAME)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700140 self.globalConfig = GitConfig.ForUser()
David Pursehouse4eb285c2013-02-14 16:28:44 +0900141 self.localManifestWarning = False
Simran Basib9a1b732015-08-20 12:19:28 -0700142 self.isGitcClient = False
Basil Gelloc7453502018-05-25 20:23:52 +0300143 self._load_local_manifests = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700144
145 self.repoProject = MetaProject(self, 'repo',
David Pursehouseabdf7502020-02-12 14:58:39 +0900146 gitdir=os.path.join(repodir, 'repo/.git'),
147 worktree=os.path.join(repodir, 'repo'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700148
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500149 mp = MetaProject(self, 'manifests',
150 gitdir=os.path.join(repodir, 'manifests.git'),
151 worktree=os.path.join(repodir, 'manifests'))
152 self.manifestProject = mp
153
154 # This is a bit hacky, but we're in a chicken & egg situation: all the
155 # normal repo settings live in the manifestProject which we just setup
156 # above, so we couldn't easily query before that. We assume Project()
157 # init doesn't care if this changes afterwards.
158 if mp.config.GetBoolean('repo.worktree'):
159 mp.use_git_worktrees = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700160
161 self._Unload()
162
Basil Gelloc7453502018-05-25 20:23:52 +0300163 def Override(self, name, load_local_manifests=True):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700164 """Use a different manifest, just for the current instantiation.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700165 """
Basil Gelloc7453502018-05-25 20:23:52 +0300166 path = None
167
168 # Look for a manifest by path in the filesystem (including the cwd).
169 if not load_local_manifests:
170 local_path = os.path.abspath(name)
171 if os.path.isfile(local_path):
172 path = local_path
173
174 # Look for manifests by name from the manifests repo.
175 if path is None:
176 path = os.path.join(self.manifestProject.worktree, name)
177 if not os.path.isfile(path):
178 raise ManifestParseError('manifest %s not found' % name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700179
180 old = self.manifestFile
181 try:
Basil Gelloc7453502018-05-25 20:23:52 +0300182 self._load_local_manifests = load_local_manifests
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700183 self.manifestFile = path
184 self._Unload()
185 self._Load()
186 finally:
187 self.manifestFile = old
188
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700189 def Link(self, name):
190 """Update the repo metadata to use a different manifest.
191 """
192 self.Override(name)
193
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700194 try:
Sebastian Frias223bf962012-11-21 19:09:25 +0100195 if os.path.lexists(self.manifestFile):
Renaud Paquay010fed72016-11-11 14:25:29 -0800196 platform_utils.remove(self.manifestFile)
Renaud Paquayd5cec5e2016-11-01 11:24:03 -0700197 platform_utils.symlink(os.path.join('manifests', name), self.manifestFile)
Sebastian Frias223bf962012-11-21 19:09:25 +0100198 except OSError as e:
199 raise ManifestParseError('cannot link manifest %s: %s' % (name, str(e)))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700200
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800201 def _RemoteToXml(self, r, doc, root):
202 e = doc.createElement('remote')
203 root.appendChild(e)
204 e.setAttribute('name', r.name)
205 e.setAttribute('fetch', r.fetchUrl)
Steve Raed6480452016-08-10 15:00:00 -0700206 if r.pushUrl is not None:
207 e.setAttribute('pushurl', r.pushUrl)
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700208 if r.remoteAlias is not None:
209 e.setAttribute('alias', r.remoteAlias)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800210 if r.reviewUrl is not None:
211 e.setAttribute('review', r.reviewUrl)
Anthony King36ea2fb2014-05-06 11:54:01 +0100212 if r.revision is not None:
213 e.setAttribute('revision', r.revision)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800214
Josh Triplett884a3872014-06-12 14:57:29 -0700215 def _ParseGroups(self, groups):
216 return [x for x in re.split(r'[,\s]+', groups) if x]
217
Dan Willemsen5ea32d12015-09-08 13:27:20 -0700218 def Save(self, fd, peg_rev=False, peg_rev_upstream=True, groups=None):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800219 """Write the current manifest out to the given file descriptor.
220 """
Colin Cross5acde752012-03-28 20:15:45 -0700221 mp = self.manifestProject
222
Dan Willemsen5ea32d12015-09-08 13:27:20 -0700223 if groups is None:
224 groups = mp.config.GetString('manifest.groups')
Matt Gumbel0c635bb2012-12-21 10:14:53 -0800225 if groups:
Josh Triplett884a3872014-06-12 14:57:29 -0700226 groups = self._ParseGroups(groups)
Colin Cross5acde752012-03-28 20:15:45 -0700227
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800228 doc = xml.dom.minidom.Document()
229 root = doc.createElement('manifest')
230 doc.appendChild(root)
231
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700232 # Save out the notice. There's a little bit of work here to give it the
233 # right whitespace, which assumes that the notice is automatically indented
234 # by 4 by minidom.
235 if self.notice:
236 notice_element = root.appendChild(doc.createElement('notice'))
237 notice_lines = self.notice.splitlines()
David Pursehouse54a4e602020-02-12 14:31:05 +0900238 indented_notice = ('\n'.join(" " * 4 + line for line in notice_lines))[4:]
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700239 notice_element.appendChild(doc.createTextNode(indented_notice))
240
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800241 d = self.default
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800242
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530243 for r in sorted(self.remotes):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800244 self._RemoteToXml(self.remotes[r], doc, root)
245 if self.remotes:
246 root.appendChild(doc.createTextNode(''))
247
248 have_default = False
249 e = doc.createElement('default')
250 if d.remote:
251 have_default = True
252 e.setAttribute('remote', d.remote.name)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700253 if d.revisionExpr:
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800254 have_default = True
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700255 e.setAttribute('revision', d.revisionExpr)
Simon Ruggier7e59de22015-07-24 12:50:06 +0200256 if d.destBranchExpr:
257 have_default = True
258 e.setAttribute('dest-branch', d.destBranchExpr)
Nasser Grainawida403412018-05-04 12:53:29 -0600259 if d.upstreamExpr:
260 have_default = True
261 e.setAttribute('upstream', d.upstreamExpr)
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700262 if d.sync_j > 1:
263 have_default = True
264 e.setAttribute('sync-j', '%d' % d.sync_j)
Anatol Pomazau79770d22012-04-20 14:41:59 -0700265 if d.sync_c:
266 have_default = True
267 e.setAttribute('sync-c', 'true')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800268 if d.sync_s:
269 have_default = True
270 e.setAttribute('sync-s', 'true')
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900271 if not d.sync_tags:
272 have_default = True
273 e.setAttribute('sync-tags', 'false')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800274 if have_default:
275 root.appendChild(e)
276 root.appendChild(doc.createTextNode(''))
277
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700278 if self._manifest_server:
279 e = doc.createElement('manifest-server')
280 e.setAttribute('url', self._manifest_server)
281 root.appendChild(e)
282 root.appendChild(doc.createTextNode(''))
283
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800284 def output_projects(parent, parent_node, projects):
David James8d201162013-10-11 17:03:19 -0700285 for project_name in projects:
286 for project in self._projects[project_name]:
287 output_project(parent, parent_node, project)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800288
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800289 def output_project(parent, parent_node, p):
Colin Cross5acde752012-03-28 20:15:45 -0700290 if not p.MatchesGroups(groups):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800291 return
292
293 name = p.name
294 relpath = p.relpath
295 if parent:
296 name = self._UnjoinName(parent.name, name)
297 relpath = self._UnjoinRelpath(parent.relpath, relpath)
Colin Cross5acde752012-03-28 20:15:45 -0700298
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800299 e = doc.createElement('project')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800300 parent_node.appendChild(e)
301 e.setAttribute('name', name)
302 if relpath != name:
303 e.setAttribute('path', relpath)
Conley Owensa17d7af2013-10-16 14:38:09 -0700304 remoteName = None
305 if d.remote:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700306 remoteName = d.remote.name
307 if not d.remote or p.remote.orig_name != remoteName:
308 remoteName = p.remote.orig_name
Anthony King36ea2fb2014-05-06 11:54:01 +0100309 e.setAttribute('remote', remoteName)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800310 if peg_rev:
311 if self.IsMirror:
Brian Harring14a66742012-09-28 20:21:57 -0700312 value = p.bare_git.rev_parse(p.revisionExpr + '^0')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800313 else:
Brian Harring14a66742012-09-28 20:21:57 -0700314 value = p.work_git.rev_parse(HEAD + '^0')
315 e.setAttribute('revision', value)
Conley Owens551dfec2015-07-10 14:54:54 -0700316 if peg_rev_upstream:
317 if p.upstream:
318 e.setAttribute('upstream', p.upstream)
319 elif value != p.revisionExpr:
320 # Only save the origin if the origin is not a sha1, and the default
321 # isn't our value
322 e.setAttribute('upstream', p.revisionExpr)
Anthony King36ea2fb2014-05-06 11:54:01 +0100323 else:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700324 revision = self.remotes[p.remote.orig_name].revision or d.revisionExpr
Anthony King36ea2fb2014-05-06 11:54:01 +0100325 if not revision or revision != p.revisionExpr:
326 e.setAttribute('revision', p.revisionExpr)
Nasser Grainawida403412018-05-04 12:53:29 -0600327 if (p.upstream and (p.upstream != p.revisionExpr or
328 p.upstream != d.upstreamExpr)):
Mani Chandel7a91d512014-07-24 16:27:08 +0530329 e.setAttribute('upstream', p.upstream)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800330
Simon Ruggier7e59de22015-07-24 12:50:06 +0200331 if p.dest_branch and p.dest_branch != d.destBranchExpr:
332 e.setAttribute('dest-branch', p.dest_branch)
333
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800334 for c in p.copyfiles:
335 ce = doc.createElement('copyfile')
336 ce.setAttribute('src', c.src)
337 ce.setAttribute('dest', c.dest)
338 e.appendChild(ce)
339
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500340 for l in p.linkfiles:
341 le = doc.createElement('linkfile')
342 le.setAttribute('src', l.src)
343 le.setAttribute('dest', l.dest)
344 e.appendChild(le)
345
Conley Owensbb1b5f52012-08-13 13:11:18 -0700346 default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
Dmitry Fink17f85ea2012-08-06 14:52:29 -0700347 egroups = [g for g in p.groups if g not in default_groups]
Conley Owens971de8e2012-04-16 10:36:08 -0700348 if egroups:
349 e.setAttribute('groups', ','.join(egroups))
Colin Cross5acde752012-03-28 20:15:45 -0700350
James W. Mills24c13082012-04-12 15:04:13 -0500351 for a in p.annotations:
352 if a.keep == "true":
353 ae = doc.createElement('annotation')
354 ae.setAttribute('name', a.name)
355 ae.setAttribute('value', a.value)
356 e.appendChild(ae)
357
Anatol Pomazau79770d22012-04-20 14:41:59 -0700358 if p.sync_c:
359 e.setAttribute('sync-c', 'true')
360
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800361 if p.sync_s:
362 e.setAttribute('sync-s', 'true')
363
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900364 if not p.sync_tags:
365 e.setAttribute('sync-tags', 'false')
366
Dan Willemsen88409222015-08-17 15:29:10 -0700367 if p.clone_depth:
368 e.setAttribute('clone-depth', str(p.clone_depth))
369
Simran Basib9a1b732015-08-20 12:19:28 -0700370 self._output_manifest_project_extras(p, e)
371
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800372 if p.subprojects:
David James8d201162013-10-11 17:03:19 -0700373 subprojects = set(subp.name for subp in p.subprojects)
374 output_projects(p, e, list(sorted(subprojects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800375
David James8d201162013-10-11 17:03:19 -0700376 projects = set(p.name for p in self._paths.values() if not p.parent)
377 output_projects(None, root, list(sorted(projects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800378
Doug Anderson37282b42011-03-04 11:54:18 -0800379 if self._repo_hooks_project:
380 root.appendChild(doc.createTextNode(''))
381 e = doc.createElement('repo-hooks')
382 e.setAttribute('in-project', self._repo_hooks_project.name)
383 e.setAttribute('enabled-list',
384 ' '.join(self._repo_hooks_project.enabled_repo_hooks))
385 root.appendChild(e)
386
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800387 doc.writexml(fd, '', ' ', '\n', 'UTF-8')
388
Simran Basib9a1b732015-08-20 12:19:28 -0700389 def _output_manifest_project_extras(self, p, e):
390 """Manifests can modify e if they support extra project attributes."""
391 pass
392
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700393 @property
David James8d201162013-10-11 17:03:19 -0700394 def paths(self):
395 self._Load()
396 return self._paths
397
398 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700399 def projects(self):
400 self._Load()
Anthony Kingd58bfe52014-05-05 23:30:49 +0100401 return list(self._paths.values())
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700402
403 @property
404 def remotes(self):
405 self._Load()
406 return self._remotes
407
408 @property
409 def default(self):
410 self._Load()
411 return self._default
412
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800413 @property
Doug Anderson37282b42011-03-04 11:54:18 -0800414 def repo_hooks_project(self):
415 self._Load()
416 return self._repo_hooks_project
417
418 @property
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700419 def notice(self):
420 self._Load()
421 return self._notice
422
423 @property
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700424 def manifest_server(self):
425 self._Load()
Shawn O. Pearce34fb20f2011-11-30 13:41:02 -0800426 return self._manifest_server
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700427
428 @property
Xin Li745be2e2019-06-03 11:24:30 -0700429 def CloneFilter(self):
430 if self.manifestProject.config.GetBoolean('repo.partialclone'):
431 return self.manifestProject.config.GetString('repo.clonefilter')
432 return None
433
434 @property
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800435 def IsMirror(self):
436 return self.manifestProject.config.GetBoolean('repo.mirror')
437
Julien Campergue335f5ef2013-10-16 11:02:35 +0200438 @property
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500439 def UseGitWorktrees(self):
440 return self.manifestProject.config.GetBoolean('repo.worktree')
441
442 @property
Julien Campergue335f5ef2013-10-16 11:02:35 +0200443 def IsArchive(self):
444 return self.manifestProject.config.GetBoolean('repo.archive')
445
Martin Kellye4e94d22017-03-21 16:05:12 -0700446 @property
447 def HasSubmodules(self):
448 return self.manifestProject.config.GetBoolean('repo.submodules')
449
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700450 def _Unload(self):
451 self._loaded = False
452 self._projects = {}
David James8d201162013-10-11 17:03:19 -0700453 self._paths = {}
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700454 self._remotes = {}
455 self._default = None
Doug Anderson37282b42011-03-04 11:54:18 -0800456 self._repo_hooks_project = None
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700457 self._notice = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700458 self.branch = None
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700459 self._manifest_server = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700460
461 def _Load(self):
462 if not self._loaded:
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800463 m = self.manifestProject
464 b = m.GetBranch(m.CurrentBranch).merge
Shawn O. Pearce21c5c342009-06-25 16:47:30 -0700465 if b is not None and b.startswith(R_HEADS):
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800466 b = b[len(R_HEADS):]
467 self.branch = b
468
Colin Cross23acdd32012-04-21 00:33:54 -0700469 nodes = []
Brian Harring475a47d2012-06-07 20:05:35 -0700470 nodes.append(self._ParseManifestXml(self.manifestFile,
471 self.manifestProject.worktree))
Shawn O. Pearce5cc66792008-10-23 16:19:27 -0700472
Basil Gelloc7453502018-05-25 20:23:52 +0300473 if self._load_local_manifests:
474 local = os.path.join(self.repodir, LOCAL_MANIFEST_NAME)
475 if os.path.exists(local):
476 if not self.localManifestWarning:
477 self.localManifestWarning = True
478 print('warning: %s is deprecated; put local manifests '
479 'in `%s` instead' % (LOCAL_MANIFEST_NAME,
David Pursehouseabdf7502020-02-12 14:58:39 +0900480 os.path.join(self.repodir, LOCAL_MANIFESTS_DIR_NAME)),
Basil Gelloc7453502018-05-25 20:23:52 +0300481 file=sys.stderr)
482 nodes.append(self._ParseManifestXml(local, self.repodir))
Colin Cross23acdd32012-04-21 00:33:54 -0700483
Basil Gelloc7453502018-05-25 20:23:52 +0300484 local_dir = os.path.abspath(os.path.join(self.repodir,
David Pursehouseabdf7502020-02-12 14:58:39 +0900485 LOCAL_MANIFESTS_DIR_NAME))
Basil Gelloc7453502018-05-25 20:23:52 +0300486 try:
487 for local_file in sorted(platform_utils.listdir(local_dir)):
488 if local_file.endswith('.xml'):
489 local = os.path.join(local_dir, local_file)
490 nodes.append(self._ParseManifestXml(local, self.repodir))
491 except OSError:
492 pass
David Pursehouse2d5a0df2012-11-13 02:50:36 +0900493
Joe Onorato26e24752013-01-11 12:35:53 -0800494 try:
495 self._ParseManifest(nodes)
496 except ManifestParseError as e:
497 # There was a problem parsing, unload ourselves in case they catch
498 # this error and try again later, we will show the correct error
499 self._Unload()
500 raise e
Shawn O. Pearce5cc66792008-10-23 16:19:27 -0700501
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800502 if self.IsMirror:
503 self._AddMetaProjectMirror(self.repoProject)
504 self._AddMetaProjectMirror(self.manifestProject)
505
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700506 self._loaded = True
507
Brian Harring475a47d2012-06-07 20:05:35 -0700508 def _ParseManifestXml(self, path, include_root):
David Pursehousef7fc8a92012-11-13 04:00:28 +0900509 try:
510 root = xml.dom.minidom.parse(path)
David Pursehouse2d5a0df2012-11-13 02:50:36 +0900511 except (OSError, xml.parsers.expat.ExpatError) as e:
David Pursehousef7fc8a92012-11-13 04:00:28 +0900512 raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
513
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700514 if not root or not root.childNodes:
Brian Harring26448742011-04-28 05:04:41 -0700515 raise ManifestParseError("no root node in %s" % (path,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700516
Jooncheol Park34acdd22012-08-27 02:25:59 +0900517 for manifest in root.childNodes:
518 if manifest.nodeName == 'manifest':
519 break
520 else:
Brian Harring26448742011-04-28 05:04:41 -0700521 raise ManifestParseError("no <manifest> in %s" % (path,))
522
Colin Cross23acdd32012-04-21 00:33:54 -0700523 nodes = []
David Pursehouse65b0ba52018-06-24 16:21:51 +0900524 for node in manifest.childNodes:
David Pursehousec1b86a22012-11-14 11:36:51 +0900525 if node.nodeName == 'include':
526 name = self._reqatt(node, 'name')
527 fp = os.path.join(include_root, name)
528 if not os.path.isfile(fp):
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530529 raise ManifestParseError("include %s doesn't exist or isn't a file"
David Pursehouseabdf7502020-02-12 14:58:39 +0900530 % (name,))
David Pursehousec1b86a22012-11-14 11:36:51 +0900531 try:
532 nodes.extend(self._ParseManifestXml(fp, include_root))
533 # should isolate this to the exact exception, but that's
534 # tricky. actual parsing implementation may vary.
535 except (KeyboardInterrupt, RuntimeError, SystemExit):
536 raise
537 except Exception as e:
538 raise ManifestParseError(
Mike Frysingerec558df2019-07-05 01:38:05 -0400539 "failed parsing included manifest %s: %s" % (name, e))
David Pursehousec1b86a22012-11-14 11:36:51 +0900540 else:
541 nodes.append(node)
Colin Cross23acdd32012-04-21 00:33:54 -0700542 return nodes
Brian Harring26448742011-04-28 05:04:41 -0700543
Colin Cross23acdd32012-04-21 00:33:54 -0700544 def _ParseManifest(self, node_list):
545 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700546 if node.nodeName == 'remote':
547 remote = self._ParseRemote(node)
David Pursehouse717ece92012-11-13 08:49:16 +0900548 if remote:
549 if remote.name in self._remotes:
550 if remote != self._remotes[remote.name]:
551 raise ManifestParseError(
552 'remote %s already exists with different attributes' %
553 (remote.name))
554 else:
555 self._remotes[remote.name] = remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700556
Colin Cross23acdd32012-04-21 00:33:54 -0700557 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700558 if node.nodeName == 'default':
Julien Campergue74879922013-10-09 14:38:46 +0200559 new_default = self._ParseDefault(node)
560 if self._default is None:
561 self._default = new_default
562 elif new_default != self._default:
David Pursehouse37128b62013-10-15 10:48:40 +0900563 raise ManifestParseError('duplicate default in %s' %
564 (self.manifestFile))
Julien Campergue74879922013-10-09 14:38:46 +0200565
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700566 if self._default is None:
567 self._default = _Default()
568
Colin Cross23acdd32012-04-21 00:33:54 -0700569 for node in itertools.chain(*node_list):
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700570 if node.nodeName == 'notice':
571 if self._notice is not None:
Doug Anderson37282b42011-03-04 11:54:18 -0800572 raise ManifestParseError(
573 'duplicate notice in %s' %
574 (self.manifestFile))
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700575 self._notice = self._ParseNotice(node)
576
Colin Cross23acdd32012-04-21 00:33:54 -0700577 for node in itertools.chain(*node_list):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700578 if node.nodeName == 'manifest-server':
579 url = self._reqatt(node, 'url')
580 if self._manifest_server is not None:
David Pursehousec1b86a22012-11-14 11:36:51 +0900581 raise ManifestParseError(
582 'duplicate manifest-server in %s' %
583 (self.manifestFile))
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700584 self._manifest_server = url
585
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800586 def recursively_add_projects(project):
David James8d201162013-10-11 17:03:19 -0700587 projects = self._projects.setdefault(project.name, [])
588 if project.relpath is None:
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800589 raise ManifestParseError(
David James8d201162013-10-11 17:03:19 -0700590 'missing path for %s in %s' %
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800591 (project.name, self.manifestFile))
David James8d201162013-10-11 17:03:19 -0700592 if project.relpath in self._paths:
593 raise ManifestParseError(
594 'duplicate path %s in %s' %
595 (project.relpath, self.manifestFile))
596 self._paths[project.relpath] = project
597 projects.append(project)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800598 for subproject in project.subprojects:
599 recursively_add_projects(subproject)
600
Colin Cross23acdd32012-04-21 00:33:54 -0700601 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700602 if node.nodeName == 'project':
603 project = self._ParseProject(node)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800604 recursively_add_projects(project)
Josh Triplett884a3872014-06-12 14:57:29 -0700605 if node.nodeName == 'extend-project':
606 name = self._reqatt(node, 'name')
607
608 if name not in self._projects:
609 raise ManifestParseError('extend-project element specifies non-existent '
610 'project: %s' % name)
611
612 path = node.getAttribute('path')
613 groups = node.getAttribute('groups')
614 if groups:
615 groups = self._ParseGroups(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -0700616 revision = node.getAttribute('revision')
Kyunam Jobd0aae92020-02-04 11:38:53 +0900617 remote = node.getAttribute('remote')
618 if remote:
619 remote = self._get_remote(node)
Josh Triplett884a3872014-06-12 14:57:29 -0700620
621 for p in self._projects[name]:
622 if path and p.relpath != path:
623 continue
624 if groups:
625 p.groups.extend(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -0700626 if revision:
627 p.revisionExpr = revision
Kyunam Jobd0aae92020-02-04 11:38:53 +0900628 if remote:
629 p.remote = remote.ToRemoteSpec(name)
Doug Anderson37282b42011-03-04 11:54:18 -0800630 if node.nodeName == 'repo-hooks':
631 # Get the name of the project and the (space-separated) list of enabled.
632 repo_hooks_project = self._reqatt(node, 'in-project')
633 enabled_repo_hooks = self._reqatt(node, 'enabled-list').split()
634
635 # Only one project can be the hooks project
636 if self._repo_hooks_project is not None:
637 raise ManifestParseError(
638 'duplicate repo-hooks in %s' %
639 (self.manifestFile))
640
641 # Store a reference to the Project.
642 try:
David James8d201162013-10-11 17:03:19 -0700643 repo_hooks_projects = self._projects[repo_hooks_project]
Doug Anderson37282b42011-03-04 11:54:18 -0800644 except KeyError:
645 raise ManifestParseError(
646 'project %s not found for repo-hooks' %
647 (repo_hooks_project))
648
David James8d201162013-10-11 17:03:19 -0700649 if len(repo_hooks_projects) != 1:
650 raise ManifestParseError(
651 'internal error parsing repo-hooks in %s' %
652 (self.manifestFile))
653 self._repo_hooks_project = repo_hooks_projects[0]
654
Doug Anderson37282b42011-03-04 11:54:18 -0800655 # Store the enabled hooks in the Project object.
656 self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
Colin Cross23acdd32012-04-21 00:33:54 -0700657 if node.nodeName == 'remove-project':
658 name = self._reqatt(node, 'name')
David Jamesb8433df2014-01-30 10:11:17 -0800659
660 if name not in self._projects:
David Pursehousef9107482012-11-16 19:12:32 +0900661 raise ManifestParseError('remove-project element specifies non-existent '
662 'project: %s' % name)
Colin Cross23acdd32012-04-21 00:33:54 -0700663
David Jamesb8433df2014-01-30 10:11:17 -0800664 for p in self._projects[name]:
665 del self._paths[p.relpath]
666 del self._projects[name]
667
Colin Cross23acdd32012-04-21 00:33:54 -0700668 # If the manifest removes the hooks project, treat it as if it deleted
669 # the repo-hooks element too.
670 if self._repo_hooks_project and (self._repo_hooks_project.name == name):
671 self._repo_hooks_project = None
672
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800673 def _AddMetaProjectMirror(self, m):
674 name = None
675 m_url = m.GetRemote(m.remote.name).url
676 if m_url.endswith('/.git'):
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530677 raise ManifestParseError('refusing to mirror %s' % m_url)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800678
679 if self._default and self._default.remote:
Conley Owensceea3682011-10-20 10:45:47 -0700680 url = self._default.remote.resolvedFetchUrl
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800681 if not url.endswith('/'):
682 url += '/'
683 if m_url.startswith(url):
684 remote = self._default.remote
685 name = m_url[len(url):]
686
687 if name is None:
688 s = m_url.rindex('/') + 1
Conley Owensdb728cd2011-09-26 16:34:01 -0700689 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Shawn O. Pearcef35b2d92012-08-02 11:46:22 -0700690 remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800691 name = m_url[s:]
692
693 if name.endswith('.git'):
694 name = name[:-4]
695
696 if name not in self._projects:
697 m.PreSync()
698 gitdir = os.path.join(self.topdir, '%s.git' % name)
David Pursehousee5913ae2020-02-12 13:56:59 +0900699 project = Project(manifest=self,
700 name=name,
701 remote=remote.ToRemoteSpec(name),
702 gitdir=gitdir,
703 objdir=gitdir,
704 worktree=None,
705 relpath=name or None,
706 revisionExpr=m.revisionExpr,
707 revisionId=None)
David James8d201162013-10-11 17:03:19 -0700708 self._projects[project.name] = [project]
Kwanhong Leeccd218c2014-02-17 13:07:32 +0900709 self._paths[project.relpath] = project
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800710
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700711 def _ParseRemote(self, node):
712 """
713 reads a <remote> element from the manifest file
714 """
715 name = self._reqatt(node, 'name')
Yestin Sunb292b982012-07-02 07:32:50 -0700716 alias = node.getAttribute('alias')
717 if alias == '':
718 alias = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700719 fetch = self._reqatt(node, 'fetch')
Steve Raed6480452016-08-10 15:00:00 -0700720 pushUrl = node.getAttribute('pushurl')
721 if pushUrl == '':
722 pushUrl = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700723 review = node.getAttribute('review')
Shawn O. Pearceae6e0942008-11-06 10:25:35 -0800724 if review == '':
725 review = None
Anthony King36ea2fb2014-05-06 11:54:01 +0100726 revision = node.getAttribute('revision')
727 if revision == '':
728 revision = None
Conley Owensdb728cd2011-09-26 16:34:01 -0700729 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Steve Raed6480452016-08-10 15:00:00 -0700730 return _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700731
732 def _ParseDefault(self, node):
733 """
734 reads a <default> element from the manifest file
735 """
736 d = _Default()
737 d.remote = self._get_remote(node)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700738 d.revisionExpr = node.getAttribute('revision')
739 if d.revisionExpr == '':
740 d.revisionExpr = None
Anatol Pomazau79770d22012-04-20 14:41:59 -0700741
Bryan Jacobsf609f912013-05-06 13:36:24 -0400742 d.destBranchExpr = node.getAttribute('dest-branch') or None
Nasser Grainawida403412018-05-04 12:53:29 -0600743 d.upstreamExpr = node.getAttribute('upstream') or None
Bryan Jacobsf609f912013-05-06 13:36:24 -0400744
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700745 sync_j = node.getAttribute('sync-j')
746 if sync_j == '' or sync_j is None:
747 d.sync_j = 1
748 else:
749 d.sync_j = int(sync_j)
Anatol Pomazau79770d22012-04-20 14:41:59 -0700750
751 sync_c = node.getAttribute('sync-c')
752 if not sync_c:
753 d.sync_c = False
754 else:
755 d.sync_c = sync_c.lower() in ("yes", "true", "1")
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800756
757 sync_s = node.getAttribute('sync-s')
758 if not sync_s:
759 d.sync_s = False
760 else:
761 d.sync_s = sync_s.lower() in ("yes", "true", "1")
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900762
763 sync_tags = node.getAttribute('sync-tags')
764 if not sync_tags:
765 d.sync_tags = True
766 else:
767 d.sync_tags = sync_tags.lower() in ("yes", "true", "1")
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700768 return d
769
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700770 def _ParseNotice(self, node):
771 """
772 reads a <notice> element from the manifest file
773
774 The <notice> element is distinct from other tags in the XML in that the
775 data is conveyed between the start and end tag (it's not an empty-element
776 tag).
777
778 The white space (carriage returns, indentation) for the notice element is
779 relevant and is parsed in a way that is based on how python docstrings work.
780 In fact, the code is remarkably similar to here:
781 http://www.python.org/dev/peps/pep-0257/
782 """
783 # Get the data out of the node...
784 notice = node.childNodes[0].data
785
786 # Figure out minimum indentation, skipping the first line (the same line
787 # as the <notice> tag)...
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530788 minIndent = sys.maxsize
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700789 lines = notice.splitlines()
790 for line in lines[1:]:
791 lstrippedLine = line.lstrip()
792 if lstrippedLine:
793 indent = len(line) - len(lstrippedLine)
794 minIndent = min(indent, minIndent)
795
796 # Strip leading / trailing blank lines and also indentation.
797 cleanLines = [lines[0].strip()]
798 for line in lines[1:]:
799 cleanLines.append(line[minIndent:].rstrip())
800
801 # Clear completely blank lines from front and back...
802 while cleanLines and not cleanLines[0]:
803 del cleanLines[0]
804 while cleanLines and not cleanLines[-1]:
805 del cleanLines[-1]
806
807 return '\n'.join(cleanLines)
808
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800809 def _JoinName(self, parent_name, name):
810 return os.path.join(parent_name, name)
811
812 def _UnjoinName(self, parent_name, name):
813 return os.path.relpath(name, parent_name)
814
David Pursehousee5913ae2020-02-12 13:56:59 +0900815 def _ParseProject(self, node, parent=None, **extra_proj_attrs):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700816 """
817 reads a <project> element from the manifest file
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700818 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700819 name = self._reqatt(node, 'name')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800820 if parent:
821 name = self._JoinName(parent.name, name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700822
823 remote = self._get_remote(node)
824 if remote is None:
825 remote = self._default.remote
826 if remote is None:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530827 raise ManifestParseError("no remote for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +0900828 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700829
Anthony King36ea2fb2014-05-06 11:54:01 +0100830 revisionExpr = node.getAttribute('revision') or remote.revision
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700831 if not revisionExpr:
832 revisionExpr = self._default.revisionExpr
833 if not revisionExpr:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530834 raise ManifestParseError("no revision for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +0900835 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700836
837 path = node.getAttribute('path')
838 if not path:
839 path = name
840 if path.startswith('/'):
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530841 raise ManifestParseError("project %s path cannot be absolute in %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +0900842 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700843
Mike Pontillod3153822012-02-28 11:53:24 -0800844 rebase = node.getAttribute('rebase')
845 if not rebase:
846 rebase = True
847 else:
848 rebase = rebase.lower() in ("yes", "true", "1")
849
Anatol Pomazau79770d22012-04-20 14:41:59 -0700850 sync_c = node.getAttribute('sync-c')
851 if not sync_c:
852 sync_c = False
853 else:
854 sync_c = sync_c.lower() in ("yes", "true", "1")
855
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800856 sync_s = node.getAttribute('sync-s')
857 if not sync_s:
858 sync_s = self._default.sync_s
859 else:
860 sync_s = sync_s.lower() in ("yes", "true", "1")
861
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900862 sync_tags = node.getAttribute('sync-tags')
863 if not sync_tags:
864 sync_tags = self._default.sync_tags
865 else:
866 sync_tags = sync_tags.lower() in ("yes", "true", "1")
867
David Pursehouseede7f122012-11-27 22:25:30 +0900868 clone_depth = node.getAttribute('clone-depth')
869 if clone_depth:
870 try:
871 clone_depth = int(clone_depth)
David Pursehouse54a4e602020-02-12 14:31:05 +0900872 if clone_depth <= 0:
David Pursehouseede7f122012-11-27 22:25:30 +0900873 raise ValueError()
874 except ValueError:
875 raise ManifestParseError('invalid clone-depth %s in %s' %
876 (clone_depth, self.manifestFile))
877
Bryan Jacobsf609f912013-05-06 13:36:24 -0400878 dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
879
Nasser Grainawida403412018-05-04 12:53:29 -0600880 upstream = node.getAttribute('upstream') or self._default.upstreamExpr
Brian Harring14a66742012-09-28 20:21:57 -0700881
Conley Owens971de8e2012-04-16 10:36:08 -0700882 groups = ''
883 if node.hasAttribute('groups'):
884 groups = node.getAttribute('groups')
Josh Triplett884a3872014-06-12 14:57:29 -0700885 groups = self._ParseGroups(groups)
Brian Harring7da13142012-06-15 02:24:20 -0700886
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800887 if parent is None:
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500888 relpath, worktree, gitdir, objdir, use_git_worktrees = \
889 self.GetProjectPaths(name, path)
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -0700890 else:
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500891 use_git_worktrees = False
David James8d201162013-10-11 17:03:19 -0700892 relpath, worktree, gitdir, objdir = \
893 self.GetSubprojectPaths(parent, name, path)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800894
895 default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
896 groups.extend(set(default_groups).difference(groups))
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -0700897
Scott Fandb83b1b2013-02-28 09:34:14 +0800898 if self.IsMirror and node.hasAttribute('force-path'):
899 if node.getAttribute('force-path').lower() in ("yes", "true", "1"):
900 gitdir = os.path.join(self.topdir, '%s.git' % path)
901
David Pursehousee5913ae2020-02-12 13:56:59 +0900902 project = Project(manifest=self,
903 name=name,
904 remote=remote.ToRemoteSpec(name),
905 gitdir=gitdir,
906 objdir=objdir,
907 worktree=worktree,
908 relpath=relpath,
909 revisionExpr=revisionExpr,
910 revisionId=None,
911 rebase=rebase,
912 groups=groups,
913 sync_c=sync_c,
914 sync_s=sync_s,
915 sync_tags=sync_tags,
916 clone_depth=clone_depth,
917 upstream=upstream,
918 parent=parent,
919 dest_branch=dest_branch,
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500920 use_git_worktrees=use_git_worktrees,
Simran Basib9a1b732015-08-20 12:19:28 -0700921 **extra_proj_attrs)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700922
923 for n in node.childNodes:
Shawn O. Pearce242b5262009-05-19 13:00:29 -0700924 if n.nodeName == 'copyfile':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700925 self._ParseCopyFile(project, n)
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500926 if n.nodeName == 'linkfile':
927 self._ParseLinkFile(project, n)
James W. Mills24c13082012-04-12 15:04:13 -0500928 if n.nodeName == 'annotation':
929 self._ParseAnnotation(project, n)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800930 if n.nodeName == 'project':
David Pursehousee5913ae2020-02-12 13:56:59 +0900931 project.subprojects.append(self._ParseProject(n, parent=project))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700932
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700933 return project
934
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800935 def GetProjectPaths(self, name, path):
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500936 use_git_worktrees = False
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800937 relpath = path
938 if self.IsMirror:
939 worktree = None
940 gitdir = os.path.join(self.topdir, '%s.git' % name)
David James8d201162013-10-11 17:03:19 -0700941 objdir = gitdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800942 else:
943 worktree = os.path.join(self.topdir, path).replace('\\', '/')
944 gitdir = os.path.join(self.repodir, 'projects', '%s.git' % path)
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500945 # We allow people to mix git worktrees & non-git worktrees for now.
946 # This allows for in situ migration of repo clients.
947 if os.path.exists(gitdir) or not self.UseGitWorktrees:
948 objdir = os.path.join(self.repodir, 'project-objects', '%s.git' % name)
949 else:
950 use_git_worktrees = True
951 gitdir = os.path.join(self.repodir, 'worktrees', '%s.git' % name)
952 objdir = gitdir
953 return relpath, worktree, gitdir, objdir, use_git_worktrees
David James8d201162013-10-11 17:03:19 -0700954
955 def GetProjectsWithName(self, name):
956 return self._projects.get(name, [])
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800957
958 def GetSubprojectName(self, parent, submodule_path):
959 return os.path.join(parent.name, submodule_path)
960
961 def _JoinRelpath(self, parent_relpath, relpath):
962 return os.path.join(parent_relpath, relpath)
963
964 def _UnjoinRelpath(self, parent_relpath, relpath):
965 return os.path.relpath(relpath, parent_relpath)
966
David James8d201162013-10-11 17:03:19 -0700967 def GetSubprojectPaths(self, parent, name, path):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800968 relpath = self._JoinRelpath(parent.relpath, path)
969 gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
David James8d201162013-10-11 17:03:19 -0700970 objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800971 if self.IsMirror:
972 worktree = None
973 else:
974 worktree = os.path.join(parent.worktree, path).replace('\\', '/')
David James8d201162013-10-11 17:03:19 -0700975 return relpath, worktree, gitdir, objdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800976
Mike Frysinger04122b72019-07-31 23:32:58 -0400977 @staticmethod
978 def _CheckLocalPath(path, symlink=False):
979 """Verify |path| is reasonable for use in <copyfile> & <linkfile>."""
980 if '~' in path:
981 return '~ not allowed (due to 8.3 filenames on Windows filesystems)'
982
983 # Some filesystems (like Apple's HFS+) try to normalize Unicode codepoints
984 # which means there are alternative names for ".git". Reject paths with
985 # these in it as there shouldn't be any reasonable need for them here.
986 # The set of codepoints here was cribbed from jgit's implementation:
987 # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
988 BAD_CODEPOINTS = {
989 u'\u200C', # ZERO WIDTH NON-JOINER
990 u'\u200D', # ZERO WIDTH JOINER
991 u'\u200E', # LEFT-TO-RIGHT MARK
992 u'\u200F', # RIGHT-TO-LEFT MARK
993 u'\u202A', # LEFT-TO-RIGHT EMBEDDING
994 u'\u202B', # RIGHT-TO-LEFT EMBEDDING
995 u'\u202C', # POP DIRECTIONAL FORMATTING
996 u'\u202D', # LEFT-TO-RIGHT OVERRIDE
997 u'\u202E', # RIGHT-TO-LEFT OVERRIDE
998 u'\u206A', # INHIBIT SYMMETRIC SWAPPING
999 u'\u206B', # ACTIVATE SYMMETRIC SWAPPING
1000 u'\u206C', # INHIBIT ARABIC FORM SHAPING
1001 u'\u206D', # ACTIVATE ARABIC FORM SHAPING
1002 u'\u206E', # NATIONAL DIGIT SHAPES
1003 u'\u206F', # NOMINAL DIGIT SHAPES
1004 u'\uFEFF', # ZERO WIDTH NO-BREAK SPACE
1005 }
1006 if BAD_CODEPOINTS & set(path):
1007 # This message is more expansive than reality, but should be fine.
1008 return 'Unicode combining characters not allowed'
1009
1010 # Assume paths might be used on case-insensitive filesystems.
1011 path = path.lower()
1012
Mike Frysingerd9254592020-02-19 22:36:26 -05001013 # Split up the path by its components. We can't use os.path.sep exclusively
1014 # as some platforms (like Windows) will convert / to \ and that bypasses all
1015 # our constructed logic here. Especially since manifest authors only use
1016 # / in their paths.
1017 resep = re.compile(r'[/%s]' % re.escape(os.path.sep))
1018 parts = resep.split(path)
1019
Mike Frysingerae625412020-02-10 17:10:03 -05001020 # Some people use src="." to create stable links to projects. Lets allow
1021 # that but reject all other uses of "." to keep things simple.
Mike Frysingerae625412020-02-10 17:10:03 -05001022 if parts != ['.']:
1023 for part in set(parts):
1024 if part in {'.', '..', '.git'} or part.startswith('.repo'):
1025 return 'bad component: %s' % (part,)
Mike Frysinger04122b72019-07-31 23:32:58 -04001026
Mike Frysingerd9254592020-02-19 22:36:26 -05001027 if not symlink and resep.match(path[-1]):
Mike Frysinger04122b72019-07-31 23:32:58 -04001028 return 'dirs not allowed'
1029
Mike Frysingerd9254592020-02-19 22:36:26 -05001030 # NB: The two abspath checks here are to handle platforms with multiple
1031 # filesystem path styles (e.g. Windows).
Mike Frysinger04122b72019-07-31 23:32:58 -04001032 norm = os.path.normpath(path)
Mike Frysingerd9254592020-02-19 22:36:26 -05001033 if (norm == '..' or
1034 (len(norm) >= 3 and norm.startswith('..') and resep.match(norm[0])) or
1035 os.path.isabs(norm) or
1036 norm.startswith('/')):
Mike Frysinger04122b72019-07-31 23:32:58 -04001037 return 'path cannot be outside'
1038
1039 @classmethod
1040 def _ValidateFilePaths(cls, element, src, dest):
1041 """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
1042
1043 We verify the path independent of any filesystem state as we won't have a
1044 checkout available to compare to. i.e. This is for parsing validation
1045 purposes only.
1046
1047 We'll do full/live sanity checking before we do the actual filesystem
1048 modifications in _CopyFile/_LinkFile/etc...
1049 """
1050 # |dest| is the file we write to or symlink we create.
1051 # It is relative to the top of the repo client checkout.
1052 msg = cls._CheckLocalPath(dest)
1053 if msg:
1054 raise ManifestInvalidPathError(
1055 '<%s> invalid "dest": %s: %s' % (element, dest, msg))
1056
1057 # |src| is the file we read from or path we point to for symlinks.
1058 # It is relative to the top of the git project checkout.
1059 msg = cls._CheckLocalPath(src, symlink=element == 'linkfile')
1060 if msg:
1061 raise ManifestInvalidPathError(
1062 '<%s> invalid "src": %s: %s' % (element, src, msg))
1063
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001064 def _ParseCopyFile(self, project, node):
1065 src = self._reqatt(node, 'src')
1066 dest = self._reqatt(node, 'dest')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001067 if not self.IsMirror:
1068 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001069 # dest is relative to the top of the tree.
1070 # We only validate paths if we actually plan to process them.
1071 self._ValidateFilePaths('copyfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001072 project.AddCopyFile(src, dest, self.topdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001073
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001074 def _ParseLinkFile(self, project, node):
1075 src = self._reqatt(node, 'src')
1076 dest = self._reqatt(node, 'dest')
1077 if not self.IsMirror:
1078 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001079 # dest is relative to the top of the tree.
1080 # We only validate paths if we actually plan to process them.
1081 self._ValidateFilePaths('linkfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001082 project.AddLinkFile(src, dest, self.topdir)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001083
James W. Mills24c13082012-04-12 15:04:13 -05001084 def _ParseAnnotation(self, project, node):
1085 name = self._reqatt(node, 'name')
1086 value = self._reqatt(node, 'value')
1087 try:
1088 keep = self._reqatt(node, 'keep').lower()
1089 except ManifestParseError:
1090 keep = "true"
1091 if keep != "true" and keep != "false":
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301092 raise ManifestParseError('optional "keep" attribute must be '
David Pursehouseabdf7502020-02-12 14:58:39 +09001093 '"true" or "false"')
James W. Mills24c13082012-04-12 15:04:13 -05001094 project.AddAnnotation(name, value, keep)
1095
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001096 def _get_remote(self, node):
1097 name = node.getAttribute('remote')
1098 if not name:
1099 return None
1100
1101 v = self._remotes.get(name)
1102 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301103 raise ManifestParseError("remote %s not defined in %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001104 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001105 return v
1106
1107 def _reqatt(self, node, attname):
1108 """
1109 reads a required attribute from the node.
1110 """
1111 v = node.getAttribute(attname)
1112 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301113 raise ManifestParseError("no %s in <%s> within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001114 (attname, node.nodeName, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001115 return v
Julien Camperguedd654222014-01-09 16:21:37 +01001116
1117 def projectsDiff(self, manifest):
1118 """return the projects differences between two manifests.
1119
1120 The diff will be from self to given manifest.
1121
1122 """
1123 fromProjects = self.paths
1124 toProjects = manifest.paths
1125
Anthony King7446c592014-05-06 09:19:39 +01001126 fromKeys = sorted(fromProjects.keys())
1127 toKeys = sorted(toProjects.keys())
Julien Camperguedd654222014-01-09 16:21:37 +01001128
1129 diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
1130
1131 for proj in fromKeys:
David Pursehouseeeff3532020-02-12 11:24:10 +09001132 if proj not in toKeys:
Julien Camperguedd654222014-01-09 16:21:37 +01001133 diff['removed'].append(fromProjects[proj])
1134 else:
1135 fromProj = fromProjects[proj]
1136 toProj = toProjects[proj]
1137 try:
1138 fromRevId = fromProj.GetCommitRevisionId()
1139 toRevId = toProj.GetCommitRevisionId()
1140 except ManifestInvalidRevisionError:
1141 diff['unreachable'].append((fromProj, toProj))
1142 else:
1143 if fromRevId != toRevId:
1144 diff['changed'].append((fromProj, toProj))
1145 toKeys.remove(proj)
1146
1147 for proj in toKeys:
1148 diff['added'].append(toProjects[proj])
1149
1150 return diff
Simran Basib9a1b732015-08-20 12:19:28 -07001151
1152
1153class GitcManifest(XmlManifest):
1154
1155 def __init__(self, repodir, gitc_client_name):
1156 """Initialize the GitcManifest object."""
1157 super(GitcManifest, self).__init__(repodir)
1158 self.isGitcClient = True
1159 self.gitc_client_name = gitc_client_name
Simran Basi8ce50412015-08-28 14:25:44 -07001160 self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
Simran Basib9a1b732015-08-20 12:19:28 -07001161 gitc_client_name)
1162 self.manifestFile = os.path.join(self.gitc_client_dir, '.manifest')
1163
David Pursehousee5913ae2020-02-12 13:56:59 +09001164 def _ParseProject(self, node, parent=None):
Simran Basib9a1b732015-08-20 12:19:28 -07001165 """Override _ParseProject and add support for GITC specific attributes."""
1166 return super(GitcManifest, self)._ParseProject(
1167 node, parent=parent, old_revision=node.getAttribute('old-revision'))
1168
1169 def _output_manifest_project_extras(self, p, e):
1170 """Output GITC Specific Project attributes"""
1171 if p.old_revision:
Stefan Beller66851062016-06-17 16:40:08 -07001172 e.setAttribute('old-revision', str(p.old_revision))