blob: edcbadaee5ef065df60bf6a58c696efb4bb87864 [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
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -050060def XmlBool(node, attr, default=None):
61 """Determine boolean value of |node|'s |attr|.
62
63 Invalid values will issue a non-fatal warning.
64
65 Args:
66 node: XML node whose attributes we access.
67 attr: The attribute to access.
68 default: If the attribute is not set (value is empty), then use this.
69
70 Returns:
71 True if the attribute is a valid string representing true.
72 False if the attribute is a valid string representing false.
73 |default| otherwise.
74 """
75 value = node.getAttribute(attr)
76 s = value.lower()
77 if s == '':
78 return default
79 elif s in {'yes', 'true', '1'}:
80 return True
81 elif s in {'no', 'false', '0'}:
82 return False
83 else:
84 print('warning: manifest: %s="%s": ignoring invalid XML boolean' %
85 (attr, value), file=sys.stderr)
86 return default
87
88
89def XmlInt(node, attr, default=None):
90 """Determine integer value of |node|'s |attr|.
91
92 Args:
93 node: XML node whose attributes we access.
94 attr: The attribute to access.
95 default: If the attribute is not set (value is empty), then use this.
96
97 Returns:
98 The number if the attribute is a valid number.
99
100 Raises:
101 ManifestParseError: The number is invalid.
102 """
103 value = node.getAttribute(attr)
104 if not value:
105 return default
106
107 try:
108 return int(value)
109 except ValueError:
110 raise ManifestParseError('manifest: invalid %s="%s" integer' %
111 (attr, value))
112
113
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700114class _Default(object):
115 """Project defaults within the manifest."""
116
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700117 revisionExpr = None
Conley Owensb6a16e62013-09-25 15:06:09 -0700118 destBranchExpr = None
Nasser Grainawida403412018-05-04 12:53:29 -0600119 upstreamExpr = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700120 remote = None
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700121 sync_j = 1
Anatol Pomazau79770d22012-04-20 14:41:59 -0700122 sync_c = False
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800123 sync_s = False
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900124 sync_tags = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700125
Julien Campergue74879922013-10-09 14:38:46 +0200126 def __eq__(self, other):
127 return self.__dict__ == other.__dict__
128
129 def __ne__(self, other):
130 return self.__dict__ != other.__dict__
131
David Pursehouse819827a2020-02-12 15:20:19 +0900132
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700133class _XmlRemote(object):
134 def __init__(self,
135 name,
Yestin Sunb292b982012-07-02 07:32:50 -0700136 alias=None,
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700137 fetch=None,
Steve Raed6480452016-08-10 15:00:00 -0700138 pushUrl=None,
Conley Owensdb728cd2011-09-26 16:34:01 -0700139 manifestUrl=None,
Anthony King36ea2fb2014-05-06 11:54:01 +0100140 review=None,
Jonathan Nieder93719792015-03-17 11:29:58 -0700141 revision=None):
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700142 self.name = name
143 self.fetchUrl = fetch
Steve Raed6480452016-08-10 15:00:00 -0700144 self.pushUrl = pushUrl
Conley Owensdb728cd2011-09-26 16:34:01 -0700145 self.manifestUrl = manifestUrl
Yestin Sunb292b982012-07-02 07:32:50 -0700146 self.remoteAlias = alias
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700147 self.reviewUrl = review
Anthony King36ea2fb2014-05-06 11:54:01 +0100148 self.revision = revision
Conley Owensceea3682011-10-20 10:45:47 -0700149 self.resolvedFetchUrl = self._resolveFetchUrl()
Shawn O. Pearced1f70d92009-05-19 14:58:02 -0700150
David Pursehouse717ece92012-11-13 08:49:16 +0900151 def __eq__(self, other):
152 return self.__dict__ == other.__dict__
153
154 def __ne__(self, other):
155 return self.__dict__ != other.__dict__
156
Conley Owensceea3682011-10-20 10:45:47 -0700157 def _resolveFetchUrl(self):
158 url = self.fetchUrl.rstrip('/')
Conley Owensdb728cd2011-09-26 16:34:01 -0700159 manifestUrl = self.manifestUrl.rstrip('/')
Conley Owens2d0f5082014-01-31 15:03:51 -0800160 # urljoin will gets confused over quite a few things. The ones we care
161 # about here are:
162 # * no scheme in the base url, like <hostname:port>
Anthony Kingcb07ba72015-03-28 23:26:04 +0000163 # We handle no scheme by replacing it with an obscure protocol, gopher
164 # and then replacing it with the original when we are done.
165
Conley Owensdb728cd2011-09-26 16:34:01 -0700166 if manifestUrl.find(':') != manifestUrl.find('/') - 1:
Conley Owens4ccad752015-04-29 10:45:37 -0700167 url = urllib.parse.urljoin('gopher://' + manifestUrl, url)
168 url = re.sub(r'^gopher://', '', url)
Anthony Kingcb07ba72015-03-28 23:26:04 +0000169 else:
170 url = urllib.parse.urljoin(manifestUrl, url)
Shawn Pearcea9f11b32013-01-02 15:40:48 -0800171 return url
Conley Owensceea3682011-10-20 10:45:47 -0700172
173 def ToRemoteSpec(self, projectName):
David Rileye0684ad2017-04-05 00:02:59 -0700174 fetchUrl = self.resolvedFetchUrl.rstrip('/')
175 url = fetchUrl + '/' + projectName
Yestin Sunb292b982012-07-02 07:32:50 -0700176 remoteName = self.name
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700177 if self.remoteAlias:
David Pursehouse37128b62013-10-15 10:48:40 +0900178 remoteName = self.remoteAlias
Dan Willemsen96c2d652016-04-06 16:03:54 -0700179 return RemoteSpec(remoteName,
180 url=url,
Steve Raed6480452016-08-10 15:00:00 -0700181 pushUrl=self.pushUrl,
Dan Willemsen96c2d652016-04-06 16:03:54 -0700182 review=self.reviewUrl,
David Rileye0684ad2017-04-05 00:02:59 -0700183 orig_name=self.name,
184 fetchUrl=self.fetchUrl)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700185
David Pursehouse819827a2020-02-12 15:20:19 +0900186
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700187class XmlManifest(object):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700188 """manages the repo configuration file"""
189
190 def __init__(self, repodir):
191 self.repodir = os.path.abspath(repodir)
192 self.topdir = os.path.dirname(self.repodir)
193 self.manifestFile = os.path.join(self.repodir, MANIFEST_FILE_NAME)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700194 self.globalConfig = GitConfig.ForUser()
David Pursehouse4eb285c2013-02-14 16:28:44 +0900195 self.localManifestWarning = False
Simran Basib9a1b732015-08-20 12:19:28 -0700196 self.isGitcClient = False
Basil Gelloc7453502018-05-25 20:23:52 +0300197 self._load_local_manifests = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700198
199 self.repoProject = MetaProject(self, 'repo',
David Pursehouseabdf7502020-02-12 14:58:39 +0900200 gitdir=os.path.join(repodir, 'repo/.git'),
201 worktree=os.path.join(repodir, 'repo'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700202
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500203 mp = MetaProject(self, 'manifests',
204 gitdir=os.path.join(repodir, 'manifests.git'),
205 worktree=os.path.join(repodir, 'manifests'))
206 self.manifestProject = mp
207
208 # This is a bit hacky, but we're in a chicken & egg situation: all the
209 # normal repo settings live in the manifestProject which we just setup
210 # above, so we couldn't easily query before that. We assume Project()
211 # init doesn't care if this changes afterwards.
Mike Frysingerd957ec62020-02-24 14:40:25 -0500212 if os.path.exists(mp.gitdir) and mp.config.GetBoolean('repo.worktree'):
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500213 mp.use_git_worktrees = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700214
215 self._Unload()
216
Basil Gelloc7453502018-05-25 20:23:52 +0300217 def Override(self, name, load_local_manifests=True):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700218 """Use a different manifest, just for the current instantiation.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700219 """
Basil Gelloc7453502018-05-25 20:23:52 +0300220 path = None
221
222 # Look for a manifest by path in the filesystem (including the cwd).
223 if not load_local_manifests:
224 local_path = os.path.abspath(name)
225 if os.path.isfile(local_path):
226 path = local_path
227
228 # Look for manifests by name from the manifests repo.
229 if path is None:
230 path = os.path.join(self.manifestProject.worktree, name)
231 if not os.path.isfile(path):
232 raise ManifestParseError('manifest %s not found' % name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700233
234 old = self.manifestFile
235 try:
Basil Gelloc7453502018-05-25 20:23:52 +0300236 self._load_local_manifests = load_local_manifests
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700237 self.manifestFile = path
238 self._Unload()
239 self._Load()
240 finally:
241 self.manifestFile = old
242
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700243 def Link(self, name):
244 """Update the repo metadata to use a different manifest.
245 """
246 self.Override(name)
247
Mike Frysingera269b1c2020-02-21 00:49:41 -0500248 # Old versions of repo would generate symlinks we need to clean up.
249 if os.path.lexists(self.manifestFile):
250 platform_utils.remove(self.manifestFile)
251 # This file is interpreted as if it existed inside the manifest repo.
252 # That allows us to use <include> with the relative file name.
253 with open(self.manifestFile, 'w') as fp:
254 fp.write("""<?xml version="1.0" encoding="UTF-8"?>
255<!--
256DO NOT EDIT THIS FILE! It is generated by repo and changes will be discarded.
257If you want to use a different manifest, use `repo init -m <file>` instead.
258
259If you want to customize your checkout by overriding manifest settings, use
260the local_manifests/ directory instead.
261
262For more information on repo manifests, check out:
263https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
264-->
265<manifest>
266 <include name="%s" />
267</manifest>
268""" % (name,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700269
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800270 def _RemoteToXml(self, r, doc, root):
271 e = doc.createElement('remote')
272 root.appendChild(e)
273 e.setAttribute('name', r.name)
274 e.setAttribute('fetch', r.fetchUrl)
Steve Raed6480452016-08-10 15:00:00 -0700275 if r.pushUrl is not None:
276 e.setAttribute('pushurl', r.pushUrl)
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700277 if r.remoteAlias is not None:
278 e.setAttribute('alias', r.remoteAlias)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800279 if r.reviewUrl is not None:
280 e.setAttribute('review', r.reviewUrl)
Anthony King36ea2fb2014-05-06 11:54:01 +0100281 if r.revision is not None:
282 e.setAttribute('revision', r.revision)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800283
Josh Triplett884a3872014-06-12 14:57:29 -0700284 def _ParseGroups(self, groups):
285 return [x for x in re.split(r'[,\s]+', groups) if x]
286
Dan Willemsen5ea32d12015-09-08 13:27:20 -0700287 def Save(self, fd, peg_rev=False, peg_rev_upstream=True, groups=None):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800288 """Write the current manifest out to the given file descriptor.
289 """
Colin Cross5acde752012-03-28 20:15:45 -0700290 mp = self.manifestProject
291
Dan Willemsen5ea32d12015-09-08 13:27:20 -0700292 if groups is None:
293 groups = mp.config.GetString('manifest.groups')
Matt Gumbel0c635bb2012-12-21 10:14:53 -0800294 if groups:
Josh Triplett884a3872014-06-12 14:57:29 -0700295 groups = self._ParseGroups(groups)
Colin Cross5acde752012-03-28 20:15:45 -0700296
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800297 doc = xml.dom.minidom.Document()
298 root = doc.createElement('manifest')
299 doc.appendChild(root)
300
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700301 # Save out the notice. There's a little bit of work here to give it the
302 # right whitespace, which assumes that the notice is automatically indented
303 # by 4 by minidom.
304 if self.notice:
305 notice_element = root.appendChild(doc.createElement('notice'))
306 notice_lines = self.notice.splitlines()
David Pursehouse54a4e602020-02-12 14:31:05 +0900307 indented_notice = ('\n'.join(" " * 4 + line for line in notice_lines))[4:]
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700308 notice_element.appendChild(doc.createTextNode(indented_notice))
309
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800310 d = self.default
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800311
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530312 for r in sorted(self.remotes):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800313 self._RemoteToXml(self.remotes[r], doc, root)
314 if self.remotes:
315 root.appendChild(doc.createTextNode(''))
316
317 have_default = False
318 e = doc.createElement('default')
319 if d.remote:
320 have_default = True
321 e.setAttribute('remote', d.remote.name)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700322 if d.revisionExpr:
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800323 have_default = True
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700324 e.setAttribute('revision', d.revisionExpr)
Simon Ruggier7e59de22015-07-24 12:50:06 +0200325 if d.destBranchExpr:
326 have_default = True
327 e.setAttribute('dest-branch', d.destBranchExpr)
Nasser Grainawida403412018-05-04 12:53:29 -0600328 if d.upstreamExpr:
329 have_default = True
330 e.setAttribute('upstream', d.upstreamExpr)
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700331 if d.sync_j > 1:
332 have_default = True
333 e.setAttribute('sync-j', '%d' % d.sync_j)
Anatol Pomazau79770d22012-04-20 14:41:59 -0700334 if d.sync_c:
335 have_default = True
336 e.setAttribute('sync-c', 'true')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800337 if d.sync_s:
338 have_default = True
339 e.setAttribute('sync-s', 'true')
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900340 if not d.sync_tags:
341 have_default = True
342 e.setAttribute('sync-tags', 'false')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800343 if have_default:
344 root.appendChild(e)
345 root.appendChild(doc.createTextNode(''))
346
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700347 if self._manifest_server:
348 e = doc.createElement('manifest-server')
349 e.setAttribute('url', self._manifest_server)
350 root.appendChild(e)
351 root.appendChild(doc.createTextNode(''))
352
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800353 def output_projects(parent, parent_node, projects):
David James8d201162013-10-11 17:03:19 -0700354 for project_name in projects:
355 for project in self._projects[project_name]:
356 output_project(parent, parent_node, project)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800357
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800358 def output_project(parent, parent_node, p):
Colin Cross5acde752012-03-28 20:15:45 -0700359 if not p.MatchesGroups(groups):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800360 return
361
362 name = p.name
363 relpath = p.relpath
364 if parent:
365 name = self._UnjoinName(parent.name, name)
366 relpath = self._UnjoinRelpath(parent.relpath, relpath)
Colin Cross5acde752012-03-28 20:15:45 -0700367
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800368 e = doc.createElement('project')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800369 parent_node.appendChild(e)
370 e.setAttribute('name', name)
371 if relpath != name:
372 e.setAttribute('path', relpath)
Conley Owensa17d7af2013-10-16 14:38:09 -0700373 remoteName = None
374 if d.remote:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700375 remoteName = d.remote.name
376 if not d.remote or p.remote.orig_name != remoteName:
377 remoteName = p.remote.orig_name
Anthony King36ea2fb2014-05-06 11:54:01 +0100378 e.setAttribute('remote', remoteName)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800379 if peg_rev:
380 if self.IsMirror:
Brian Harring14a66742012-09-28 20:21:57 -0700381 value = p.bare_git.rev_parse(p.revisionExpr + '^0')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800382 else:
Brian Harring14a66742012-09-28 20:21:57 -0700383 value = p.work_git.rev_parse(HEAD + '^0')
384 e.setAttribute('revision', value)
Conley Owens551dfec2015-07-10 14:54:54 -0700385 if peg_rev_upstream:
386 if p.upstream:
387 e.setAttribute('upstream', p.upstream)
388 elif value != p.revisionExpr:
389 # Only save the origin if the origin is not a sha1, and the default
390 # isn't our value
391 e.setAttribute('upstream', p.revisionExpr)
Anthony King36ea2fb2014-05-06 11:54:01 +0100392 else:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700393 revision = self.remotes[p.remote.orig_name].revision or d.revisionExpr
Anthony King36ea2fb2014-05-06 11:54:01 +0100394 if not revision or revision != p.revisionExpr:
395 e.setAttribute('revision', p.revisionExpr)
Nasser Grainawida403412018-05-04 12:53:29 -0600396 if (p.upstream and (p.upstream != p.revisionExpr or
397 p.upstream != d.upstreamExpr)):
Mani Chandel7a91d512014-07-24 16:27:08 +0530398 e.setAttribute('upstream', p.upstream)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800399
Simon Ruggier7e59de22015-07-24 12:50:06 +0200400 if p.dest_branch and p.dest_branch != d.destBranchExpr:
401 e.setAttribute('dest-branch', p.dest_branch)
402
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800403 for c in p.copyfiles:
404 ce = doc.createElement('copyfile')
405 ce.setAttribute('src', c.src)
406 ce.setAttribute('dest', c.dest)
407 e.appendChild(ce)
408
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500409 for l in p.linkfiles:
410 le = doc.createElement('linkfile')
411 le.setAttribute('src', l.src)
412 le.setAttribute('dest', l.dest)
413 e.appendChild(le)
414
Conley Owensbb1b5f52012-08-13 13:11:18 -0700415 default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
Dmitry Fink17f85ea2012-08-06 14:52:29 -0700416 egroups = [g for g in p.groups if g not in default_groups]
Conley Owens971de8e2012-04-16 10:36:08 -0700417 if egroups:
418 e.setAttribute('groups', ','.join(egroups))
Colin Cross5acde752012-03-28 20:15:45 -0700419
James W. Mills24c13082012-04-12 15:04:13 -0500420 for a in p.annotations:
421 if a.keep == "true":
422 ae = doc.createElement('annotation')
423 ae.setAttribute('name', a.name)
424 ae.setAttribute('value', a.value)
425 e.appendChild(ae)
426
Anatol Pomazau79770d22012-04-20 14:41:59 -0700427 if p.sync_c:
428 e.setAttribute('sync-c', 'true')
429
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800430 if p.sync_s:
431 e.setAttribute('sync-s', 'true')
432
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900433 if not p.sync_tags:
434 e.setAttribute('sync-tags', 'false')
435
Dan Willemsen88409222015-08-17 15:29:10 -0700436 if p.clone_depth:
437 e.setAttribute('clone-depth', str(p.clone_depth))
438
Simran Basib9a1b732015-08-20 12:19:28 -0700439 self._output_manifest_project_extras(p, e)
440
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800441 if p.subprojects:
David James8d201162013-10-11 17:03:19 -0700442 subprojects = set(subp.name for subp in p.subprojects)
443 output_projects(p, e, list(sorted(subprojects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800444
David James8d201162013-10-11 17:03:19 -0700445 projects = set(p.name for p in self._paths.values() if not p.parent)
446 output_projects(None, root, list(sorted(projects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800447
Doug Anderson37282b42011-03-04 11:54:18 -0800448 if self._repo_hooks_project:
449 root.appendChild(doc.createTextNode(''))
450 e = doc.createElement('repo-hooks')
451 e.setAttribute('in-project', self._repo_hooks_project.name)
452 e.setAttribute('enabled-list',
453 ' '.join(self._repo_hooks_project.enabled_repo_hooks))
454 root.appendChild(e)
455
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800456 doc.writexml(fd, '', ' ', '\n', 'UTF-8')
457
Simran Basib9a1b732015-08-20 12:19:28 -0700458 def _output_manifest_project_extras(self, p, e):
459 """Manifests can modify e if they support extra project attributes."""
460 pass
461
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700462 @property
David James8d201162013-10-11 17:03:19 -0700463 def paths(self):
464 self._Load()
465 return self._paths
466
467 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700468 def projects(self):
469 self._Load()
Anthony Kingd58bfe52014-05-05 23:30:49 +0100470 return list(self._paths.values())
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700471
472 @property
473 def remotes(self):
474 self._Load()
475 return self._remotes
476
477 @property
478 def default(self):
479 self._Load()
480 return self._default
481
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800482 @property
Doug Anderson37282b42011-03-04 11:54:18 -0800483 def repo_hooks_project(self):
484 self._Load()
485 return self._repo_hooks_project
486
487 @property
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700488 def notice(self):
489 self._Load()
490 return self._notice
491
492 @property
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700493 def manifest_server(self):
494 self._Load()
Shawn O. Pearce34fb20f2011-11-30 13:41:02 -0800495 return self._manifest_server
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700496
497 @property
Xin Li745be2e2019-06-03 11:24:30 -0700498 def CloneFilter(self):
499 if self.manifestProject.config.GetBoolean('repo.partialclone'):
500 return self.manifestProject.config.GetString('repo.clonefilter')
501 return None
502
503 @property
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800504 def IsMirror(self):
505 return self.manifestProject.config.GetBoolean('repo.mirror')
506
Julien Campergue335f5ef2013-10-16 11:02:35 +0200507 @property
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500508 def UseGitWorktrees(self):
509 return self.manifestProject.config.GetBoolean('repo.worktree')
510
511 @property
Julien Campergue335f5ef2013-10-16 11:02:35 +0200512 def IsArchive(self):
513 return self.manifestProject.config.GetBoolean('repo.archive')
514
Martin Kellye4e94d22017-03-21 16:05:12 -0700515 @property
516 def HasSubmodules(self):
517 return self.manifestProject.config.GetBoolean('repo.submodules')
518
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700519 def _Unload(self):
520 self._loaded = False
521 self._projects = {}
David James8d201162013-10-11 17:03:19 -0700522 self._paths = {}
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700523 self._remotes = {}
524 self._default = None
Doug Anderson37282b42011-03-04 11:54:18 -0800525 self._repo_hooks_project = None
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700526 self._notice = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700527 self.branch = None
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700528 self._manifest_server = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700529
530 def _Load(self):
531 if not self._loaded:
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800532 m = self.manifestProject
533 b = m.GetBranch(m.CurrentBranch).merge
Shawn O. Pearce21c5c342009-06-25 16:47:30 -0700534 if b is not None and b.startswith(R_HEADS):
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800535 b = b[len(R_HEADS):]
536 self.branch = b
537
Colin Cross23acdd32012-04-21 00:33:54 -0700538 nodes = []
Brian Harring475a47d2012-06-07 20:05:35 -0700539 nodes.append(self._ParseManifestXml(self.manifestFile,
540 self.manifestProject.worktree))
Shawn O. Pearce5cc66792008-10-23 16:19:27 -0700541
Basil Gelloc7453502018-05-25 20:23:52 +0300542 if self._load_local_manifests:
543 local = os.path.join(self.repodir, LOCAL_MANIFEST_NAME)
544 if os.path.exists(local):
545 if not self.localManifestWarning:
546 self.localManifestWarning = True
547 print('warning: %s is deprecated; put local manifests '
548 'in `%s` instead' % (LOCAL_MANIFEST_NAME,
David Pursehouseabdf7502020-02-12 14:58:39 +0900549 os.path.join(self.repodir, LOCAL_MANIFESTS_DIR_NAME)),
Basil Gelloc7453502018-05-25 20:23:52 +0300550 file=sys.stderr)
551 nodes.append(self._ParseManifestXml(local, self.repodir))
Colin Cross23acdd32012-04-21 00:33:54 -0700552
Basil Gelloc7453502018-05-25 20:23:52 +0300553 local_dir = os.path.abspath(os.path.join(self.repodir,
David Pursehouseabdf7502020-02-12 14:58:39 +0900554 LOCAL_MANIFESTS_DIR_NAME))
Basil Gelloc7453502018-05-25 20:23:52 +0300555 try:
556 for local_file in sorted(platform_utils.listdir(local_dir)):
557 if local_file.endswith('.xml'):
558 local = os.path.join(local_dir, local_file)
559 nodes.append(self._ParseManifestXml(local, self.repodir))
560 except OSError:
561 pass
David Pursehouse2d5a0df2012-11-13 02:50:36 +0900562
Joe Onorato26e24752013-01-11 12:35:53 -0800563 try:
564 self._ParseManifest(nodes)
565 except ManifestParseError as e:
566 # There was a problem parsing, unload ourselves in case they catch
567 # this error and try again later, we will show the correct error
568 self._Unload()
569 raise e
Shawn O. Pearce5cc66792008-10-23 16:19:27 -0700570
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800571 if self.IsMirror:
572 self._AddMetaProjectMirror(self.repoProject)
573 self._AddMetaProjectMirror(self.manifestProject)
574
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700575 self._loaded = True
576
Brian Harring475a47d2012-06-07 20:05:35 -0700577 def _ParseManifestXml(self, path, include_root):
David Pursehousef7fc8a92012-11-13 04:00:28 +0900578 try:
579 root = xml.dom.minidom.parse(path)
David Pursehouse2d5a0df2012-11-13 02:50:36 +0900580 except (OSError, xml.parsers.expat.ExpatError) as e:
David Pursehousef7fc8a92012-11-13 04:00:28 +0900581 raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
582
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700583 if not root or not root.childNodes:
Brian Harring26448742011-04-28 05:04:41 -0700584 raise ManifestParseError("no root node in %s" % (path,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700585
Jooncheol Park34acdd22012-08-27 02:25:59 +0900586 for manifest in root.childNodes:
587 if manifest.nodeName == 'manifest':
588 break
589 else:
Brian Harring26448742011-04-28 05:04:41 -0700590 raise ManifestParseError("no <manifest> in %s" % (path,))
591
Colin Cross23acdd32012-04-21 00:33:54 -0700592 nodes = []
David Pursehouse65b0ba52018-06-24 16:21:51 +0900593 for node in manifest.childNodes:
David Pursehousec1b86a22012-11-14 11:36:51 +0900594 if node.nodeName == 'include':
595 name = self._reqatt(node, 'name')
596 fp = os.path.join(include_root, name)
597 if not os.path.isfile(fp):
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530598 raise ManifestParseError("include %s doesn't exist or isn't a file"
David Pursehouseabdf7502020-02-12 14:58:39 +0900599 % (name,))
David Pursehousec1b86a22012-11-14 11:36:51 +0900600 try:
601 nodes.extend(self._ParseManifestXml(fp, include_root))
602 # should isolate this to the exact exception, but that's
603 # tricky. actual parsing implementation may vary.
604 except (KeyboardInterrupt, RuntimeError, SystemExit):
605 raise
606 except Exception as e:
607 raise ManifestParseError(
Mike Frysingerec558df2019-07-05 01:38:05 -0400608 "failed parsing included manifest %s: %s" % (name, e))
David Pursehousec1b86a22012-11-14 11:36:51 +0900609 else:
610 nodes.append(node)
Colin Cross23acdd32012-04-21 00:33:54 -0700611 return nodes
Brian Harring26448742011-04-28 05:04:41 -0700612
Colin Cross23acdd32012-04-21 00:33:54 -0700613 def _ParseManifest(self, node_list):
614 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700615 if node.nodeName == 'remote':
616 remote = self._ParseRemote(node)
David Pursehouse717ece92012-11-13 08:49:16 +0900617 if remote:
618 if remote.name in self._remotes:
619 if remote != self._remotes[remote.name]:
620 raise ManifestParseError(
621 'remote %s already exists with different attributes' %
622 (remote.name))
623 else:
624 self._remotes[remote.name] = remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700625
Colin Cross23acdd32012-04-21 00:33:54 -0700626 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700627 if node.nodeName == 'default':
Julien Campergue74879922013-10-09 14:38:46 +0200628 new_default = self._ParseDefault(node)
629 if self._default is None:
630 self._default = new_default
631 elif new_default != self._default:
David Pursehouse37128b62013-10-15 10:48:40 +0900632 raise ManifestParseError('duplicate default in %s' %
633 (self.manifestFile))
Julien Campergue74879922013-10-09 14:38:46 +0200634
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700635 if self._default is None:
636 self._default = _Default()
637
Colin Cross23acdd32012-04-21 00:33:54 -0700638 for node in itertools.chain(*node_list):
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700639 if node.nodeName == 'notice':
640 if self._notice is not None:
Doug Anderson37282b42011-03-04 11:54:18 -0800641 raise ManifestParseError(
642 'duplicate notice in %s' %
643 (self.manifestFile))
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700644 self._notice = self._ParseNotice(node)
645
Colin Cross23acdd32012-04-21 00:33:54 -0700646 for node in itertools.chain(*node_list):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700647 if node.nodeName == 'manifest-server':
648 url = self._reqatt(node, 'url')
649 if self._manifest_server is not None:
David Pursehousec1b86a22012-11-14 11:36:51 +0900650 raise ManifestParseError(
651 'duplicate manifest-server in %s' %
652 (self.manifestFile))
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700653 self._manifest_server = url
654
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800655 def recursively_add_projects(project):
David James8d201162013-10-11 17:03:19 -0700656 projects = self._projects.setdefault(project.name, [])
657 if project.relpath is None:
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800658 raise ManifestParseError(
David James8d201162013-10-11 17:03:19 -0700659 'missing path for %s in %s' %
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800660 (project.name, self.manifestFile))
David James8d201162013-10-11 17:03:19 -0700661 if project.relpath in self._paths:
662 raise ManifestParseError(
663 'duplicate path %s in %s' %
664 (project.relpath, self.manifestFile))
665 self._paths[project.relpath] = project
666 projects.append(project)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800667 for subproject in project.subprojects:
668 recursively_add_projects(subproject)
669
Colin Cross23acdd32012-04-21 00:33:54 -0700670 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700671 if node.nodeName == 'project':
672 project = self._ParseProject(node)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800673 recursively_add_projects(project)
Josh Triplett884a3872014-06-12 14:57:29 -0700674 if node.nodeName == 'extend-project':
675 name = self._reqatt(node, 'name')
676
677 if name not in self._projects:
678 raise ManifestParseError('extend-project element specifies non-existent '
679 'project: %s' % name)
680
681 path = node.getAttribute('path')
682 groups = node.getAttribute('groups')
683 if groups:
684 groups = self._ParseGroups(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -0700685 revision = node.getAttribute('revision')
Kyunam Jobd0aae92020-02-04 11:38:53 +0900686 remote = node.getAttribute('remote')
687 if remote:
688 remote = self._get_remote(node)
Josh Triplett884a3872014-06-12 14:57:29 -0700689
690 for p in self._projects[name]:
691 if path and p.relpath != path:
692 continue
693 if groups:
694 p.groups.extend(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -0700695 if revision:
696 p.revisionExpr = revision
Kyunam Jobd0aae92020-02-04 11:38:53 +0900697 if remote:
698 p.remote = remote.ToRemoteSpec(name)
Doug Anderson37282b42011-03-04 11:54:18 -0800699 if node.nodeName == 'repo-hooks':
700 # Get the name of the project and the (space-separated) list of enabled.
701 repo_hooks_project = self._reqatt(node, 'in-project')
702 enabled_repo_hooks = self._reqatt(node, 'enabled-list').split()
703
704 # Only one project can be the hooks project
705 if self._repo_hooks_project is not None:
706 raise ManifestParseError(
707 'duplicate repo-hooks in %s' %
708 (self.manifestFile))
709
710 # Store a reference to the Project.
711 try:
David James8d201162013-10-11 17:03:19 -0700712 repo_hooks_projects = self._projects[repo_hooks_project]
Doug Anderson37282b42011-03-04 11:54:18 -0800713 except KeyError:
714 raise ManifestParseError(
715 'project %s not found for repo-hooks' %
716 (repo_hooks_project))
717
David James8d201162013-10-11 17:03:19 -0700718 if len(repo_hooks_projects) != 1:
719 raise ManifestParseError(
720 'internal error parsing repo-hooks in %s' %
721 (self.manifestFile))
722 self._repo_hooks_project = repo_hooks_projects[0]
723
Doug Anderson37282b42011-03-04 11:54:18 -0800724 # Store the enabled hooks in the Project object.
725 self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
Colin Cross23acdd32012-04-21 00:33:54 -0700726 if node.nodeName == 'remove-project':
727 name = self._reqatt(node, 'name')
David Jamesb8433df2014-01-30 10:11:17 -0800728
729 if name not in self._projects:
David Pursehousef9107482012-11-16 19:12:32 +0900730 raise ManifestParseError('remove-project element specifies non-existent '
731 'project: %s' % name)
Colin Cross23acdd32012-04-21 00:33:54 -0700732
David Jamesb8433df2014-01-30 10:11:17 -0800733 for p in self._projects[name]:
734 del self._paths[p.relpath]
735 del self._projects[name]
736
Colin Cross23acdd32012-04-21 00:33:54 -0700737 # If the manifest removes the hooks project, treat it as if it deleted
738 # the repo-hooks element too.
739 if self._repo_hooks_project and (self._repo_hooks_project.name == name):
740 self._repo_hooks_project = None
741
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800742 def _AddMetaProjectMirror(self, m):
743 name = None
744 m_url = m.GetRemote(m.remote.name).url
745 if m_url.endswith('/.git'):
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530746 raise ManifestParseError('refusing to mirror %s' % m_url)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800747
748 if self._default and self._default.remote:
Conley Owensceea3682011-10-20 10:45:47 -0700749 url = self._default.remote.resolvedFetchUrl
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800750 if not url.endswith('/'):
751 url += '/'
752 if m_url.startswith(url):
753 remote = self._default.remote
754 name = m_url[len(url):]
755
756 if name is None:
757 s = m_url.rindex('/') + 1
Conley Owensdb728cd2011-09-26 16:34:01 -0700758 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Shawn O. Pearcef35b2d92012-08-02 11:46:22 -0700759 remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800760 name = m_url[s:]
761
762 if name.endswith('.git'):
763 name = name[:-4]
764
765 if name not in self._projects:
766 m.PreSync()
767 gitdir = os.path.join(self.topdir, '%s.git' % name)
David Pursehousee5913ae2020-02-12 13:56:59 +0900768 project = Project(manifest=self,
769 name=name,
770 remote=remote.ToRemoteSpec(name),
771 gitdir=gitdir,
772 objdir=gitdir,
773 worktree=None,
774 relpath=name or None,
775 revisionExpr=m.revisionExpr,
776 revisionId=None)
David James8d201162013-10-11 17:03:19 -0700777 self._projects[project.name] = [project]
Kwanhong Leeccd218c2014-02-17 13:07:32 +0900778 self._paths[project.relpath] = project
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800779
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700780 def _ParseRemote(self, node):
781 """
782 reads a <remote> element from the manifest file
783 """
784 name = self._reqatt(node, 'name')
Yestin Sunb292b982012-07-02 07:32:50 -0700785 alias = node.getAttribute('alias')
786 if alias == '':
787 alias = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700788 fetch = self._reqatt(node, 'fetch')
Steve Raed6480452016-08-10 15:00:00 -0700789 pushUrl = node.getAttribute('pushurl')
790 if pushUrl == '':
791 pushUrl = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700792 review = node.getAttribute('review')
Shawn O. Pearceae6e0942008-11-06 10:25:35 -0800793 if review == '':
794 review = None
Anthony King36ea2fb2014-05-06 11:54:01 +0100795 revision = node.getAttribute('revision')
796 if revision == '':
797 revision = None
Conley Owensdb728cd2011-09-26 16:34:01 -0700798 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Steve Raed6480452016-08-10 15:00:00 -0700799 return _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700800
801 def _ParseDefault(self, node):
802 """
803 reads a <default> element from the manifest file
804 """
805 d = _Default()
806 d.remote = self._get_remote(node)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700807 d.revisionExpr = node.getAttribute('revision')
808 if d.revisionExpr == '':
809 d.revisionExpr = None
Anatol Pomazau79770d22012-04-20 14:41:59 -0700810
Bryan Jacobsf609f912013-05-06 13:36:24 -0400811 d.destBranchExpr = node.getAttribute('dest-branch') or None
Nasser Grainawida403412018-05-04 12:53:29 -0600812 d.upstreamExpr = node.getAttribute('upstream') or None
Bryan Jacobsf609f912013-05-06 13:36:24 -0400813
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500814 d.sync_j = XmlInt(node, 'sync-j', 1)
815 if d.sync_j <= 0:
816 raise ManifestParseError('%s: sync-j must be greater than 0, not "%s"' %
817 (self.manifestFile, d.sync_j))
Anatol Pomazau79770d22012-04-20 14:41:59 -0700818
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500819 d.sync_c = XmlBool(node, 'sync-c', False)
820 d.sync_s = XmlBool(node, 'sync-s', False)
821 d.sync_tags = XmlBool(node, 'sync-tags', True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700822 return d
823
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700824 def _ParseNotice(self, node):
825 """
826 reads a <notice> element from the manifest file
827
828 The <notice> element is distinct from other tags in the XML in that the
829 data is conveyed between the start and end tag (it's not an empty-element
830 tag).
831
832 The white space (carriage returns, indentation) for the notice element is
833 relevant and is parsed in a way that is based on how python docstrings work.
834 In fact, the code is remarkably similar to here:
835 http://www.python.org/dev/peps/pep-0257/
836 """
837 # Get the data out of the node...
838 notice = node.childNodes[0].data
839
840 # Figure out minimum indentation, skipping the first line (the same line
841 # as the <notice> tag)...
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530842 minIndent = sys.maxsize
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700843 lines = notice.splitlines()
844 for line in lines[1:]:
845 lstrippedLine = line.lstrip()
846 if lstrippedLine:
847 indent = len(line) - len(lstrippedLine)
848 minIndent = min(indent, minIndent)
849
850 # Strip leading / trailing blank lines and also indentation.
851 cleanLines = [lines[0].strip()]
852 for line in lines[1:]:
853 cleanLines.append(line[minIndent:].rstrip())
854
855 # Clear completely blank lines from front and back...
856 while cleanLines and not cleanLines[0]:
857 del cleanLines[0]
858 while cleanLines and not cleanLines[-1]:
859 del cleanLines[-1]
860
861 return '\n'.join(cleanLines)
862
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800863 def _JoinName(self, parent_name, name):
864 return os.path.join(parent_name, name)
865
866 def _UnjoinName(self, parent_name, name):
867 return os.path.relpath(name, parent_name)
868
David Pursehousee5913ae2020-02-12 13:56:59 +0900869 def _ParseProject(self, node, parent=None, **extra_proj_attrs):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700870 """
871 reads a <project> element from the manifest file
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700872 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700873 name = self._reqatt(node, 'name')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800874 if parent:
875 name = self._JoinName(parent.name, name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700876
877 remote = self._get_remote(node)
878 if remote is None:
879 remote = self._default.remote
880 if remote is None:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530881 raise ManifestParseError("no remote for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +0900882 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700883
Anthony King36ea2fb2014-05-06 11:54:01 +0100884 revisionExpr = node.getAttribute('revision') or remote.revision
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700885 if not revisionExpr:
886 revisionExpr = self._default.revisionExpr
887 if not revisionExpr:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530888 raise ManifestParseError("no revision for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +0900889 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700890
891 path = node.getAttribute('path')
892 if not path:
893 path = name
894 if path.startswith('/'):
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530895 raise ManifestParseError("project %s path cannot be absolute in %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +0900896 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700897
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500898 rebase = XmlBool(node, 'rebase', True)
899 sync_c = XmlBool(node, 'sync-c', False)
900 sync_s = XmlBool(node, 'sync-s', self._default.sync_s)
901 sync_tags = XmlBool(node, 'sync-tags', self._default.sync_tags)
Mike Pontillod3153822012-02-28 11:53:24 -0800902
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500903 clone_depth = XmlInt(node, 'clone-depth')
904 if clone_depth is not None and clone_depth <= 0:
905 raise ManifestParseError('%s: clone-depth must be greater than 0, not "%s"' %
906 (self.manifestFile, clone_depth))
David Pursehouseede7f122012-11-27 22:25:30 +0900907
Bryan Jacobsf609f912013-05-06 13:36:24 -0400908 dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
909
Nasser Grainawida403412018-05-04 12:53:29 -0600910 upstream = node.getAttribute('upstream') or self._default.upstreamExpr
Brian Harring14a66742012-09-28 20:21:57 -0700911
Conley Owens971de8e2012-04-16 10:36:08 -0700912 groups = ''
913 if node.hasAttribute('groups'):
914 groups = node.getAttribute('groups')
Josh Triplett884a3872014-06-12 14:57:29 -0700915 groups = self._ParseGroups(groups)
Brian Harring7da13142012-06-15 02:24:20 -0700916
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800917 if parent is None:
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500918 relpath, worktree, gitdir, objdir, use_git_worktrees = \
919 self.GetProjectPaths(name, path)
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -0700920 else:
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500921 use_git_worktrees = False
David James8d201162013-10-11 17:03:19 -0700922 relpath, worktree, gitdir, objdir = \
923 self.GetSubprojectPaths(parent, name, path)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800924
925 default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
926 groups.extend(set(default_groups).difference(groups))
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -0700927
Scott Fandb83b1b2013-02-28 09:34:14 +0800928 if self.IsMirror and node.hasAttribute('force-path'):
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500929 if XmlBool(node, 'force-path', False):
Scott Fandb83b1b2013-02-28 09:34:14 +0800930 gitdir = os.path.join(self.topdir, '%s.git' % path)
931
David Pursehousee5913ae2020-02-12 13:56:59 +0900932 project = Project(manifest=self,
933 name=name,
934 remote=remote.ToRemoteSpec(name),
935 gitdir=gitdir,
936 objdir=objdir,
937 worktree=worktree,
938 relpath=relpath,
939 revisionExpr=revisionExpr,
940 revisionId=None,
941 rebase=rebase,
942 groups=groups,
943 sync_c=sync_c,
944 sync_s=sync_s,
945 sync_tags=sync_tags,
946 clone_depth=clone_depth,
947 upstream=upstream,
948 parent=parent,
949 dest_branch=dest_branch,
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500950 use_git_worktrees=use_git_worktrees,
Simran Basib9a1b732015-08-20 12:19:28 -0700951 **extra_proj_attrs)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700952
953 for n in node.childNodes:
Shawn O. Pearce242b5262009-05-19 13:00:29 -0700954 if n.nodeName == 'copyfile':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700955 self._ParseCopyFile(project, n)
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500956 if n.nodeName == 'linkfile':
957 self._ParseLinkFile(project, n)
James W. Mills24c13082012-04-12 15:04:13 -0500958 if n.nodeName == 'annotation':
959 self._ParseAnnotation(project, n)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800960 if n.nodeName == 'project':
David Pursehousee5913ae2020-02-12 13:56:59 +0900961 project.subprojects.append(self._ParseProject(n, parent=project))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700962
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700963 return project
964
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800965 def GetProjectPaths(self, name, path):
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500966 use_git_worktrees = False
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800967 relpath = path
968 if self.IsMirror:
969 worktree = None
970 gitdir = os.path.join(self.topdir, '%s.git' % name)
David James8d201162013-10-11 17:03:19 -0700971 objdir = gitdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800972 else:
973 worktree = os.path.join(self.topdir, path).replace('\\', '/')
974 gitdir = os.path.join(self.repodir, 'projects', '%s.git' % path)
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500975 # We allow people to mix git worktrees & non-git worktrees for now.
976 # This allows for in situ migration of repo clients.
977 if os.path.exists(gitdir) or not self.UseGitWorktrees:
978 objdir = os.path.join(self.repodir, 'project-objects', '%s.git' % name)
979 else:
980 use_git_worktrees = True
981 gitdir = os.path.join(self.repodir, 'worktrees', '%s.git' % name)
982 objdir = gitdir
983 return relpath, worktree, gitdir, objdir, use_git_worktrees
David James8d201162013-10-11 17:03:19 -0700984
985 def GetProjectsWithName(self, name):
986 return self._projects.get(name, [])
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800987
988 def GetSubprojectName(self, parent, submodule_path):
989 return os.path.join(parent.name, submodule_path)
990
991 def _JoinRelpath(self, parent_relpath, relpath):
992 return os.path.join(parent_relpath, relpath)
993
994 def _UnjoinRelpath(self, parent_relpath, relpath):
995 return os.path.relpath(relpath, parent_relpath)
996
David James8d201162013-10-11 17:03:19 -0700997 def GetSubprojectPaths(self, parent, name, path):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800998 relpath = self._JoinRelpath(parent.relpath, path)
999 gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
David James8d201162013-10-11 17:03:19 -07001000 objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001001 if self.IsMirror:
1002 worktree = None
1003 else:
1004 worktree = os.path.join(parent.worktree, path).replace('\\', '/')
David James8d201162013-10-11 17:03:19 -07001005 return relpath, worktree, gitdir, objdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001006
Mike Frysinger04122b72019-07-31 23:32:58 -04001007 @staticmethod
1008 def _CheckLocalPath(path, symlink=False):
1009 """Verify |path| is reasonable for use in <copyfile> & <linkfile>."""
1010 if '~' in path:
1011 return '~ not allowed (due to 8.3 filenames on Windows filesystems)'
1012
1013 # Some filesystems (like Apple's HFS+) try to normalize Unicode codepoints
1014 # which means there are alternative names for ".git". Reject paths with
1015 # these in it as there shouldn't be any reasonable need for them here.
1016 # The set of codepoints here was cribbed from jgit's implementation:
1017 # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
1018 BAD_CODEPOINTS = {
1019 u'\u200C', # ZERO WIDTH NON-JOINER
1020 u'\u200D', # ZERO WIDTH JOINER
1021 u'\u200E', # LEFT-TO-RIGHT MARK
1022 u'\u200F', # RIGHT-TO-LEFT MARK
1023 u'\u202A', # LEFT-TO-RIGHT EMBEDDING
1024 u'\u202B', # RIGHT-TO-LEFT EMBEDDING
1025 u'\u202C', # POP DIRECTIONAL FORMATTING
1026 u'\u202D', # LEFT-TO-RIGHT OVERRIDE
1027 u'\u202E', # RIGHT-TO-LEFT OVERRIDE
1028 u'\u206A', # INHIBIT SYMMETRIC SWAPPING
1029 u'\u206B', # ACTIVATE SYMMETRIC SWAPPING
1030 u'\u206C', # INHIBIT ARABIC FORM SHAPING
1031 u'\u206D', # ACTIVATE ARABIC FORM SHAPING
1032 u'\u206E', # NATIONAL DIGIT SHAPES
1033 u'\u206F', # NOMINAL DIGIT SHAPES
1034 u'\uFEFF', # ZERO WIDTH NO-BREAK SPACE
1035 }
1036 if BAD_CODEPOINTS & set(path):
1037 # This message is more expansive than reality, but should be fine.
1038 return 'Unicode combining characters not allowed'
1039
1040 # Assume paths might be used on case-insensitive filesystems.
1041 path = path.lower()
1042
Mike Frysingerd9254592020-02-19 22:36:26 -05001043 # Split up the path by its components. We can't use os.path.sep exclusively
1044 # as some platforms (like Windows) will convert / to \ and that bypasses all
1045 # our constructed logic here. Especially since manifest authors only use
1046 # / in their paths.
1047 resep = re.compile(r'[/%s]' % re.escape(os.path.sep))
1048 parts = resep.split(path)
1049
Mike Frysingerae625412020-02-10 17:10:03 -05001050 # Some people use src="." to create stable links to projects. Lets allow
1051 # that but reject all other uses of "." to keep things simple.
Mike Frysingerae625412020-02-10 17:10:03 -05001052 if parts != ['.']:
1053 for part in set(parts):
1054 if part in {'.', '..', '.git'} or part.startswith('.repo'):
1055 return 'bad component: %s' % (part,)
Mike Frysinger04122b72019-07-31 23:32:58 -04001056
Mike Frysingerd9254592020-02-19 22:36:26 -05001057 if not symlink and resep.match(path[-1]):
Mike Frysinger04122b72019-07-31 23:32:58 -04001058 return 'dirs not allowed'
1059
Mike Frysingerd9254592020-02-19 22:36:26 -05001060 # NB: The two abspath checks here are to handle platforms with multiple
1061 # filesystem path styles (e.g. Windows).
Mike Frysinger04122b72019-07-31 23:32:58 -04001062 norm = os.path.normpath(path)
Mike Frysingerd9254592020-02-19 22:36:26 -05001063 if (norm == '..' or
1064 (len(norm) >= 3 and norm.startswith('..') and resep.match(norm[0])) or
1065 os.path.isabs(norm) or
1066 norm.startswith('/')):
Mike Frysinger04122b72019-07-31 23:32:58 -04001067 return 'path cannot be outside'
1068
1069 @classmethod
1070 def _ValidateFilePaths(cls, element, src, dest):
1071 """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
1072
1073 We verify the path independent of any filesystem state as we won't have a
1074 checkout available to compare to. i.e. This is for parsing validation
1075 purposes only.
1076
1077 We'll do full/live sanity checking before we do the actual filesystem
1078 modifications in _CopyFile/_LinkFile/etc...
1079 """
1080 # |dest| is the file we write to or symlink we create.
1081 # It is relative to the top of the repo client checkout.
1082 msg = cls._CheckLocalPath(dest)
1083 if msg:
1084 raise ManifestInvalidPathError(
1085 '<%s> invalid "dest": %s: %s' % (element, dest, msg))
1086
1087 # |src| is the file we read from or path we point to for symlinks.
1088 # It is relative to the top of the git project checkout.
1089 msg = cls._CheckLocalPath(src, symlink=element == 'linkfile')
1090 if msg:
1091 raise ManifestInvalidPathError(
1092 '<%s> invalid "src": %s: %s' % (element, src, msg))
1093
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001094 def _ParseCopyFile(self, project, node):
1095 src = self._reqatt(node, 'src')
1096 dest = self._reqatt(node, 'dest')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001097 if not self.IsMirror:
1098 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001099 # dest is relative to the top of the tree.
1100 # We only validate paths if we actually plan to process them.
1101 self._ValidateFilePaths('copyfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001102 project.AddCopyFile(src, dest, self.topdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001103
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001104 def _ParseLinkFile(self, project, node):
1105 src = self._reqatt(node, 'src')
1106 dest = self._reqatt(node, 'dest')
1107 if not self.IsMirror:
1108 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001109 # dest is relative to the top of the tree.
1110 # We only validate paths if we actually plan to process them.
1111 self._ValidateFilePaths('linkfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001112 project.AddLinkFile(src, dest, self.topdir)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001113
James W. Mills24c13082012-04-12 15:04:13 -05001114 def _ParseAnnotation(self, project, node):
1115 name = self._reqatt(node, 'name')
1116 value = self._reqatt(node, 'value')
1117 try:
1118 keep = self._reqatt(node, 'keep').lower()
1119 except ManifestParseError:
1120 keep = "true"
1121 if keep != "true" and keep != "false":
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301122 raise ManifestParseError('optional "keep" attribute must be '
David Pursehouseabdf7502020-02-12 14:58:39 +09001123 '"true" or "false"')
James W. Mills24c13082012-04-12 15:04:13 -05001124 project.AddAnnotation(name, value, keep)
1125
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001126 def _get_remote(self, node):
1127 name = node.getAttribute('remote')
1128 if not name:
1129 return None
1130
1131 v = self._remotes.get(name)
1132 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301133 raise ManifestParseError("remote %s not defined in %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001134 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001135 return v
1136
1137 def _reqatt(self, node, attname):
1138 """
1139 reads a required attribute from the node.
1140 """
1141 v = node.getAttribute(attname)
1142 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301143 raise ManifestParseError("no %s in <%s> within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001144 (attname, node.nodeName, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001145 return v
Julien Camperguedd654222014-01-09 16:21:37 +01001146
1147 def projectsDiff(self, manifest):
1148 """return the projects differences between two manifests.
1149
1150 The diff will be from self to given manifest.
1151
1152 """
1153 fromProjects = self.paths
1154 toProjects = manifest.paths
1155
Anthony King7446c592014-05-06 09:19:39 +01001156 fromKeys = sorted(fromProjects.keys())
1157 toKeys = sorted(toProjects.keys())
Julien Camperguedd654222014-01-09 16:21:37 +01001158
1159 diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
1160
1161 for proj in fromKeys:
David Pursehouseeeff3532020-02-12 11:24:10 +09001162 if proj not in toKeys:
Julien Camperguedd654222014-01-09 16:21:37 +01001163 diff['removed'].append(fromProjects[proj])
1164 else:
1165 fromProj = fromProjects[proj]
1166 toProj = toProjects[proj]
1167 try:
1168 fromRevId = fromProj.GetCommitRevisionId()
1169 toRevId = toProj.GetCommitRevisionId()
1170 except ManifestInvalidRevisionError:
1171 diff['unreachable'].append((fromProj, toProj))
1172 else:
1173 if fromRevId != toRevId:
1174 diff['changed'].append((fromProj, toProj))
1175 toKeys.remove(proj)
1176
1177 for proj in toKeys:
1178 diff['added'].append(toProjects[proj])
1179
1180 return diff
Simran Basib9a1b732015-08-20 12:19:28 -07001181
1182
1183class GitcManifest(XmlManifest):
1184
1185 def __init__(self, repodir, gitc_client_name):
1186 """Initialize the GitcManifest object."""
1187 super(GitcManifest, self).__init__(repodir)
1188 self.isGitcClient = True
1189 self.gitc_client_name = gitc_client_name
Simran Basi8ce50412015-08-28 14:25:44 -07001190 self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
Simran Basib9a1b732015-08-20 12:19:28 -07001191 gitc_client_name)
1192 self.manifestFile = os.path.join(self.gitc_client_dir, '.manifest')
1193
David Pursehousee5913ae2020-02-12 13:56:59 +09001194 def _ParseProject(self, node, parent=None):
Simran Basib9a1b732015-08-20 12:19:28 -07001195 """Override _ParseProject and add support for GITC specific attributes."""
1196 return super(GitcManifest, self)._ParseProject(
1197 node, parent=parent, old_revision=node.getAttribute('old-revision'))
1198
1199 def _output_manifest_project_extras(self, p, e):
1200 """Output GITC Specific Project attributes"""
1201 if p.old_revision:
Stefan Beller66851062016-06-17 16:40:08 -07001202 e.setAttribute('old-revision', str(p.old_revision))