blob: f2d04df2430cec853b49a9bb55af8b5b233e5c36 [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()
Simran Basib9a1b732015-08-20 12:19:28 -0700195 self.isGitcClient = False
Basil Gelloc7453502018-05-25 20:23:52 +0300196 self._load_local_manifests = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700197
198 self.repoProject = MetaProject(self, 'repo',
David Pursehouseabdf7502020-02-12 14:58:39 +0900199 gitdir=os.path.join(repodir, 'repo/.git'),
200 worktree=os.path.join(repodir, 'repo'))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700201
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500202 mp = MetaProject(self, 'manifests',
203 gitdir=os.path.join(repodir, 'manifests.git'),
204 worktree=os.path.join(repodir, 'manifests'))
205 self.manifestProject = mp
206
207 # This is a bit hacky, but we're in a chicken & egg situation: all the
208 # normal repo settings live in the manifestProject which we just setup
209 # above, so we couldn't easily query before that. We assume Project()
210 # init doesn't care if this changes afterwards.
Mike Frysingerd957ec62020-02-24 14:40:25 -0500211 if os.path.exists(mp.gitdir) and mp.config.GetBoolean('repo.worktree'):
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500212 mp.use_git_worktrees = True
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700213
214 self._Unload()
215
Basil Gelloc7453502018-05-25 20:23:52 +0300216 def Override(self, name, load_local_manifests=True):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700217 """Use a different manifest, just for the current instantiation.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700218 """
Basil Gelloc7453502018-05-25 20:23:52 +0300219 path = None
220
221 # Look for a manifest by path in the filesystem (including the cwd).
222 if not load_local_manifests:
223 local_path = os.path.abspath(name)
224 if os.path.isfile(local_path):
225 path = local_path
226
227 # Look for manifests by name from the manifests repo.
228 if path is None:
229 path = os.path.join(self.manifestProject.worktree, name)
230 if not os.path.isfile(path):
231 raise ManifestParseError('manifest %s not found' % name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700232
233 old = self.manifestFile
234 try:
Basil Gelloc7453502018-05-25 20:23:52 +0300235 self._load_local_manifests = load_local_manifests
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700236 self.manifestFile = path
237 self._Unload()
238 self._Load()
239 finally:
240 self.manifestFile = old
241
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700242 def Link(self, name):
243 """Update the repo metadata to use a different manifest.
244 """
245 self.Override(name)
246
Mike Frysingera269b1c2020-02-21 00:49:41 -0500247 # Old versions of repo would generate symlinks we need to clean up.
248 if os.path.lexists(self.manifestFile):
249 platform_utils.remove(self.manifestFile)
250 # This file is interpreted as if it existed inside the manifest repo.
251 # That allows us to use <include> with the relative file name.
252 with open(self.manifestFile, 'w') as fp:
253 fp.write("""<?xml version="1.0" encoding="UTF-8"?>
254<!--
255DO NOT EDIT THIS FILE! It is generated by repo and changes will be discarded.
256If you want to use a different manifest, use `repo init -m <file>` instead.
257
258If you want to customize your checkout by overriding manifest settings, use
259the local_manifests/ directory instead.
260
261For more information on repo manifests, check out:
262https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
263-->
264<manifest>
265 <include name="%s" />
266</manifest>
267""" % (name,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700268
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800269 def _RemoteToXml(self, r, doc, root):
270 e = doc.createElement('remote')
271 root.appendChild(e)
272 e.setAttribute('name', r.name)
273 e.setAttribute('fetch', r.fetchUrl)
Steve Raed6480452016-08-10 15:00:00 -0700274 if r.pushUrl is not None:
275 e.setAttribute('pushurl', r.pushUrl)
Conley Owens1e7ab2a2013-10-08 17:26:57 -0700276 if r.remoteAlias is not None:
277 e.setAttribute('alias', r.remoteAlias)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800278 if r.reviewUrl is not None:
279 e.setAttribute('review', r.reviewUrl)
Anthony King36ea2fb2014-05-06 11:54:01 +0100280 if r.revision is not None:
281 e.setAttribute('revision', r.revision)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800282
Josh Triplett884a3872014-06-12 14:57:29 -0700283 def _ParseGroups(self, groups):
284 return [x for x in re.split(r'[,\s]+', groups) if x]
285
Sean McAllisteraf908cb2020-04-20 08:41:58 -0600286 def Save(self, fd, peg_rev=False, peg_rev_upstream=True, peg_rev_dest_branch=True, groups=None):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800287 """Write the current manifest out to the given file descriptor.
288 """
Colin Cross5acde752012-03-28 20:15:45 -0700289 mp = self.manifestProject
290
Dan Willemsen5ea32d12015-09-08 13:27:20 -0700291 if groups is None:
292 groups = mp.config.GetString('manifest.groups')
Matt Gumbel0c635bb2012-12-21 10:14:53 -0800293 if groups:
Josh Triplett884a3872014-06-12 14:57:29 -0700294 groups = self._ParseGroups(groups)
Colin Cross5acde752012-03-28 20:15:45 -0700295
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800296 doc = xml.dom.minidom.Document()
297 root = doc.createElement('manifest')
298 doc.appendChild(root)
299
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700300 # Save out the notice. There's a little bit of work here to give it the
301 # right whitespace, which assumes that the notice is automatically indented
302 # by 4 by minidom.
303 if self.notice:
304 notice_element = root.appendChild(doc.createElement('notice'))
305 notice_lines = self.notice.splitlines()
David Pursehouse54a4e602020-02-12 14:31:05 +0900306 indented_notice = ('\n'.join(" " * 4 + line for line in notice_lines))[4:]
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700307 notice_element.appendChild(doc.createTextNode(indented_notice))
308
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800309 d = self.default
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800310
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530311 for r in sorted(self.remotes):
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800312 self._RemoteToXml(self.remotes[r], doc, root)
313 if self.remotes:
314 root.appendChild(doc.createTextNode(''))
315
316 have_default = False
317 e = doc.createElement('default')
318 if d.remote:
319 have_default = True
320 e.setAttribute('remote', d.remote.name)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700321 if d.revisionExpr:
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800322 have_default = True
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700323 e.setAttribute('revision', d.revisionExpr)
Simon Ruggier7e59de22015-07-24 12:50:06 +0200324 if d.destBranchExpr:
325 have_default = True
326 e.setAttribute('dest-branch', d.destBranchExpr)
Nasser Grainawida403412018-05-04 12:53:29 -0600327 if d.upstreamExpr:
328 have_default = True
329 e.setAttribute('upstream', d.upstreamExpr)
Shawn O. Pearce6392c872011-09-22 17:44:31 -0700330 if d.sync_j > 1:
331 have_default = True
332 e.setAttribute('sync-j', '%d' % d.sync_j)
Anatol Pomazau79770d22012-04-20 14:41:59 -0700333 if d.sync_c:
334 have_default = True
335 e.setAttribute('sync-c', 'true')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800336 if d.sync_s:
337 have_default = True
338 e.setAttribute('sync-s', 'true')
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900339 if not d.sync_tags:
340 have_default = True
341 e.setAttribute('sync-tags', 'false')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800342 if have_default:
343 root.appendChild(e)
344 root.appendChild(doc.createTextNode(''))
345
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700346 if self._manifest_server:
347 e = doc.createElement('manifest-server')
348 e.setAttribute('url', self._manifest_server)
349 root.appendChild(e)
350 root.appendChild(doc.createTextNode(''))
351
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800352 def output_projects(parent, parent_node, projects):
David James8d201162013-10-11 17:03:19 -0700353 for project_name in projects:
354 for project in self._projects[project_name]:
355 output_project(parent, parent_node, project)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800356
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800357 def output_project(parent, parent_node, p):
Colin Cross5acde752012-03-28 20:15:45 -0700358 if not p.MatchesGroups(groups):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800359 return
360
361 name = p.name
362 relpath = p.relpath
363 if parent:
364 name = self._UnjoinName(parent.name, name)
365 relpath = self._UnjoinRelpath(parent.relpath, relpath)
Colin Cross5acde752012-03-28 20:15:45 -0700366
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800367 e = doc.createElement('project')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800368 parent_node.appendChild(e)
369 e.setAttribute('name', name)
370 if relpath != name:
371 e.setAttribute('path', relpath)
Conley Owensa17d7af2013-10-16 14:38:09 -0700372 remoteName = None
373 if d.remote:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700374 remoteName = d.remote.name
375 if not d.remote or p.remote.orig_name != remoteName:
376 remoteName = p.remote.orig_name
Anthony King36ea2fb2014-05-06 11:54:01 +0100377 e.setAttribute('remote', remoteName)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800378 if peg_rev:
379 if self.IsMirror:
Brian Harring14a66742012-09-28 20:21:57 -0700380 value = p.bare_git.rev_parse(p.revisionExpr + '^0')
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800381 else:
Brian Harring14a66742012-09-28 20:21:57 -0700382 value = p.work_git.rev_parse(HEAD + '^0')
383 e.setAttribute('revision', value)
Conley Owens551dfec2015-07-10 14:54:54 -0700384 if peg_rev_upstream:
385 if p.upstream:
386 e.setAttribute('upstream', p.upstream)
387 elif value != p.revisionExpr:
388 # Only save the origin if the origin is not a sha1, and the default
389 # isn't our value
390 e.setAttribute('upstream', p.revisionExpr)
Sean McAllisteraf908cb2020-04-20 08:41:58 -0600391
392 if peg_rev_dest_branch:
393 if p.dest_branch:
394 e.setAttribute('dest-branch', p.dest_branch)
395 elif value != p.revisionExpr:
396 e.setAttribute('dest-branch', p.revisionExpr)
397
Anthony King36ea2fb2014-05-06 11:54:01 +0100398 else:
Dan Willemsen96c2d652016-04-06 16:03:54 -0700399 revision = self.remotes[p.remote.orig_name].revision or d.revisionExpr
Anthony King36ea2fb2014-05-06 11:54:01 +0100400 if not revision or revision != p.revisionExpr:
401 e.setAttribute('revision', p.revisionExpr)
Nasser Grainawida403412018-05-04 12:53:29 -0600402 if (p.upstream and (p.upstream != p.revisionExpr or
403 p.upstream != d.upstreamExpr)):
Mani Chandel7a91d512014-07-24 16:27:08 +0530404 e.setAttribute('upstream', p.upstream)
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800405
Simon Ruggier7e59de22015-07-24 12:50:06 +0200406 if p.dest_branch and p.dest_branch != d.destBranchExpr:
407 e.setAttribute('dest-branch', p.dest_branch)
408
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800409 for c in p.copyfiles:
410 ce = doc.createElement('copyfile')
411 ce.setAttribute('src', c.src)
412 ce.setAttribute('dest', c.dest)
413 e.appendChild(ce)
414
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500415 for l in p.linkfiles:
416 le = doc.createElement('linkfile')
417 le.setAttribute('src', l.src)
418 le.setAttribute('dest', l.dest)
419 e.appendChild(le)
420
Conley Owensbb1b5f52012-08-13 13:11:18 -0700421 default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
Dmitry Fink17f85ea2012-08-06 14:52:29 -0700422 egroups = [g for g in p.groups if g not in default_groups]
Conley Owens971de8e2012-04-16 10:36:08 -0700423 if egroups:
424 e.setAttribute('groups', ','.join(egroups))
Colin Cross5acde752012-03-28 20:15:45 -0700425
James W. Mills24c13082012-04-12 15:04:13 -0500426 for a in p.annotations:
427 if a.keep == "true":
428 ae = doc.createElement('annotation')
429 ae.setAttribute('name', a.name)
430 ae.setAttribute('value', a.value)
431 e.appendChild(ae)
432
Anatol Pomazau79770d22012-04-20 14:41:59 -0700433 if p.sync_c:
434 e.setAttribute('sync-c', 'true')
435
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800436 if p.sync_s:
437 e.setAttribute('sync-s', 'true')
438
YOUNG HO CHAa32c92c2018-02-14 16:57:31 +0900439 if not p.sync_tags:
440 e.setAttribute('sync-tags', 'false')
441
Dan Willemsen88409222015-08-17 15:29:10 -0700442 if p.clone_depth:
443 e.setAttribute('clone-depth', str(p.clone_depth))
444
Simran Basib9a1b732015-08-20 12:19:28 -0700445 self._output_manifest_project_extras(p, e)
446
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800447 if p.subprojects:
David James8d201162013-10-11 17:03:19 -0700448 subprojects = set(subp.name for subp in p.subprojects)
449 output_projects(p, e, list(sorted(subprojects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800450
David James8d201162013-10-11 17:03:19 -0700451 projects = set(p.name for p in self._paths.values() if not p.parent)
452 output_projects(None, root, list(sorted(projects)))
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800453
Doug Anderson37282b42011-03-04 11:54:18 -0800454 if self._repo_hooks_project:
455 root.appendChild(doc.createTextNode(''))
456 e = doc.createElement('repo-hooks')
457 e.setAttribute('in-project', self._repo_hooks_project.name)
458 e.setAttribute('enabled-list',
459 ' '.join(self._repo_hooks_project.enabled_repo_hooks))
460 root.appendChild(e)
461
Shawn O. Pearcec7a4eef2009-03-05 10:32:38 -0800462 doc.writexml(fd, '', ' ', '\n', 'UTF-8')
463
Simran Basib9a1b732015-08-20 12:19:28 -0700464 def _output_manifest_project_extras(self, p, e):
465 """Manifests can modify e if they support extra project attributes."""
466 pass
467
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700468 @property
David James8d201162013-10-11 17:03:19 -0700469 def paths(self):
470 self._Load()
471 return self._paths
472
473 @property
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700474 def projects(self):
475 self._Load()
Anthony Kingd58bfe52014-05-05 23:30:49 +0100476 return list(self._paths.values())
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700477
478 @property
479 def remotes(self):
480 self._Load()
481 return self._remotes
482
483 @property
484 def default(self):
485 self._Load()
486 return self._default
487
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800488 @property
Doug Anderson37282b42011-03-04 11:54:18 -0800489 def repo_hooks_project(self):
490 self._Load()
491 return self._repo_hooks_project
492
493 @property
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700494 def notice(self):
495 self._Load()
496 return self._notice
497
498 @property
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700499 def manifest_server(self):
500 self._Load()
Shawn O. Pearce34fb20f2011-11-30 13:41:02 -0800501 return self._manifest_server
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700502
503 @property
Xin Lid79a4bc2020-05-20 16:03:45 -0700504 def CloneBundle(self):
505 clone_bundle = self.manifestProject.config.GetBoolean('repo.clonebundle')
506 if clone_bundle is None:
507 return False if self.manifestProject.config.GetBoolean('repo.partialclone') else True
508 else:
509 return clone_bundle
510
511 @property
Xin Li745be2e2019-06-03 11:24:30 -0700512 def CloneFilter(self):
513 if self.manifestProject.config.GetBoolean('repo.partialclone'):
514 return self.manifestProject.config.GetString('repo.clonefilter')
515 return None
516
517 @property
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800518 def IsMirror(self):
519 return self.manifestProject.config.GetBoolean('repo.mirror')
520
Julien Campergue335f5ef2013-10-16 11:02:35 +0200521 @property
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500522 def UseGitWorktrees(self):
523 return self.manifestProject.config.GetBoolean('repo.worktree')
524
525 @property
Julien Campergue335f5ef2013-10-16 11:02:35 +0200526 def IsArchive(self):
527 return self.manifestProject.config.GetBoolean('repo.archive')
528
Martin Kellye4e94d22017-03-21 16:05:12 -0700529 @property
530 def HasSubmodules(self):
531 return self.manifestProject.config.GetBoolean('repo.submodules')
532
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700533 def _Unload(self):
534 self._loaded = False
535 self._projects = {}
David James8d201162013-10-11 17:03:19 -0700536 self._paths = {}
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700537 self._remotes = {}
538 self._default = None
Doug Anderson37282b42011-03-04 11:54:18 -0800539 self._repo_hooks_project = None
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700540 self._notice = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700541 self.branch = None
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700542 self._manifest_server = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700543
544 def _Load(self):
545 if not self._loaded:
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800546 m = self.manifestProject
547 b = m.GetBranch(m.CurrentBranch).merge
Shawn O. Pearce21c5c342009-06-25 16:47:30 -0700548 if b is not None and b.startswith(R_HEADS):
Shawn O. Pearce2450a292008-11-04 08:22:07 -0800549 b = b[len(R_HEADS):]
550 self.branch = b
551
Colin Cross23acdd32012-04-21 00:33:54 -0700552 nodes = []
Brian Harring475a47d2012-06-07 20:05:35 -0700553 nodes.append(self._ParseManifestXml(self.manifestFile,
554 self.manifestProject.worktree))
Shawn O. Pearce5cc66792008-10-23 16:19:27 -0700555
Basil Gelloc7453502018-05-25 20:23:52 +0300556 if self._load_local_manifests:
Mike Frysinger4e1fc102020-09-06 14:42:47 -0400557 if os.path.exists(os.path.join(self.repodir, LOCAL_MANIFEST_NAME)):
558 print('error: %s is not supported; put local manifests in `%s`'
559 'instead' % (LOCAL_MANIFEST_NAME,
560 os.path.join(self.repodir, LOCAL_MANIFESTS_DIR_NAME)),
561 file=sys.stderr)
562 sys.exit(1)
Colin Cross23acdd32012-04-21 00:33:54 -0700563
Basil Gelloc7453502018-05-25 20:23:52 +0300564 local_dir = os.path.abspath(os.path.join(self.repodir,
David Pursehouseabdf7502020-02-12 14:58:39 +0900565 LOCAL_MANIFESTS_DIR_NAME))
Basil Gelloc7453502018-05-25 20:23:52 +0300566 try:
567 for local_file in sorted(platform_utils.listdir(local_dir)):
568 if local_file.endswith('.xml'):
569 local = os.path.join(local_dir, local_file)
570 nodes.append(self._ParseManifestXml(local, self.repodir))
571 except OSError:
572 pass
David Pursehouse2d5a0df2012-11-13 02:50:36 +0900573
Joe Onorato26e24752013-01-11 12:35:53 -0800574 try:
575 self._ParseManifest(nodes)
576 except ManifestParseError as e:
577 # There was a problem parsing, unload ourselves in case they catch
578 # this error and try again later, we will show the correct error
579 self._Unload()
580 raise e
Shawn O. Pearce5cc66792008-10-23 16:19:27 -0700581
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800582 if self.IsMirror:
583 self._AddMetaProjectMirror(self.repoProject)
584 self._AddMetaProjectMirror(self.manifestProject)
585
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700586 self._loaded = True
587
Brian Harring475a47d2012-06-07 20:05:35 -0700588 def _ParseManifestXml(self, path, include_root):
David Pursehousef7fc8a92012-11-13 04:00:28 +0900589 try:
590 root = xml.dom.minidom.parse(path)
David Pursehouse2d5a0df2012-11-13 02:50:36 +0900591 except (OSError, xml.parsers.expat.ExpatError) as e:
David Pursehousef7fc8a92012-11-13 04:00:28 +0900592 raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
593
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700594 if not root or not root.childNodes:
Brian Harring26448742011-04-28 05:04:41 -0700595 raise ManifestParseError("no root node in %s" % (path,))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700596
Jooncheol Park34acdd22012-08-27 02:25:59 +0900597 for manifest in root.childNodes:
598 if manifest.nodeName == 'manifest':
599 break
600 else:
Brian Harring26448742011-04-28 05:04:41 -0700601 raise ManifestParseError("no <manifest> in %s" % (path,))
602
Colin Cross23acdd32012-04-21 00:33:54 -0700603 nodes = []
David Pursehouse65b0ba52018-06-24 16:21:51 +0900604 for node in manifest.childNodes:
David Pursehousec1b86a22012-11-14 11:36:51 +0900605 if node.nodeName == 'include':
606 name = self._reqatt(node, 'name')
607 fp = os.path.join(include_root, name)
608 if not os.path.isfile(fp):
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530609 raise ManifestParseError("include %s doesn't exist or isn't a file"
David Pursehouseabdf7502020-02-12 14:58:39 +0900610 % (name,))
David Pursehousec1b86a22012-11-14 11:36:51 +0900611 try:
612 nodes.extend(self._ParseManifestXml(fp, include_root))
613 # should isolate this to the exact exception, but that's
614 # tricky. actual parsing implementation may vary.
615 except (KeyboardInterrupt, RuntimeError, SystemExit):
616 raise
617 except Exception as e:
618 raise ManifestParseError(
Mike Frysingerec558df2019-07-05 01:38:05 -0400619 "failed parsing included manifest %s: %s" % (name, e))
David Pursehousec1b86a22012-11-14 11:36:51 +0900620 else:
621 nodes.append(node)
Colin Cross23acdd32012-04-21 00:33:54 -0700622 return nodes
Brian Harring26448742011-04-28 05:04:41 -0700623
Colin Cross23acdd32012-04-21 00:33:54 -0700624 def _ParseManifest(self, node_list):
625 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700626 if node.nodeName == 'remote':
627 remote = self._ParseRemote(node)
David Pursehouse717ece92012-11-13 08:49:16 +0900628 if remote:
629 if remote.name in self._remotes:
630 if remote != self._remotes[remote.name]:
631 raise ManifestParseError(
632 'remote %s already exists with different attributes' %
633 (remote.name))
634 else:
635 self._remotes[remote.name] = remote
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700636
Colin Cross23acdd32012-04-21 00:33:54 -0700637 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700638 if node.nodeName == 'default':
Julien Campergue74879922013-10-09 14:38:46 +0200639 new_default = self._ParseDefault(node)
640 if self._default is None:
641 self._default = new_default
642 elif new_default != self._default:
David Pursehouse37128b62013-10-15 10:48:40 +0900643 raise ManifestParseError('duplicate default in %s' %
644 (self.manifestFile))
Julien Campergue74879922013-10-09 14:38:46 +0200645
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700646 if self._default is None:
647 self._default = _Default()
648
Colin Cross23acdd32012-04-21 00:33:54 -0700649 for node in itertools.chain(*node_list):
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700650 if node.nodeName == 'notice':
651 if self._notice is not None:
Doug Anderson37282b42011-03-04 11:54:18 -0800652 raise ManifestParseError(
653 'duplicate notice in %s' %
654 (self.manifestFile))
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700655 self._notice = self._ParseNotice(node)
656
Colin Cross23acdd32012-04-21 00:33:54 -0700657 for node in itertools.chain(*node_list):
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700658 if node.nodeName == 'manifest-server':
659 url = self._reqatt(node, 'url')
660 if self._manifest_server is not None:
David Pursehousec1b86a22012-11-14 11:36:51 +0900661 raise ManifestParseError(
662 'duplicate manifest-server in %s' %
663 (self.manifestFile))
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700664 self._manifest_server = url
665
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800666 def recursively_add_projects(project):
David James8d201162013-10-11 17:03:19 -0700667 projects = self._projects.setdefault(project.name, [])
668 if project.relpath is None:
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800669 raise ManifestParseError(
David James8d201162013-10-11 17:03:19 -0700670 'missing path for %s in %s' %
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800671 (project.name, self.manifestFile))
David James8d201162013-10-11 17:03:19 -0700672 if project.relpath in self._paths:
673 raise ManifestParseError(
674 'duplicate path %s in %s' %
675 (project.relpath, self.manifestFile))
676 self._paths[project.relpath] = project
677 projects.append(project)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800678 for subproject in project.subprojects:
679 recursively_add_projects(subproject)
680
Colin Cross23acdd32012-04-21 00:33:54 -0700681 for node in itertools.chain(*node_list):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700682 if node.nodeName == 'project':
683 project = self._ParseProject(node)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800684 recursively_add_projects(project)
Josh Triplett884a3872014-06-12 14:57:29 -0700685 if node.nodeName == 'extend-project':
686 name = self._reqatt(node, 'name')
687
688 if name not in self._projects:
689 raise ManifestParseError('extend-project element specifies non-existent '
690 'project: %s' % name)
691
692 path = node.getAttribute('path')
693 groups = node.getAttribute('groups')
694 if groups:
695 groups = self._ParseGroups(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -0700696 revision = node.getAttribute('revision')
Kyunam Jobd0aae92020-02-04 11:38:53 +0900697 remote = node.getAttribute('remote')
698 if remote:
699 remote = self._get_remote(node)
Josh Triplett884a3872014-06-12 14:57:29 -0700700
701 for p in self._projects[name]:
702 if path and p.relpath != path:
703 continue
704 if groups:
705 p.groups.extend(groups)
Luis Hector Chavez7d525852018-03-15 09:54:08 -0700706 if revision:
707 p.revisionExpr = revision
Kyunam Jobd0aae92020-02-04 11:38:53 +0900708 if remote:
709 p.remote = remote.ToRemoteSpec(name)
Doug Anderson37282b42011-03-04 11:54:18 -0800710 if node.nodeName == 'repo-hooks':
711 # Get the name of the project and the (space-separated) list of enabled.
712 repo_hooks_project = self._reqatt(node, 'in-project')
713 enabled_repo_hooks = self._reqatt(node, 'enabled-list').split()
714
715 # Only one project can be the hooks project
716 if self._repo_hooks_project is not None:
717 raise ManifestParseError(
718 'duplicate repo-hooks in %s' %
719 (self.manifestFile))
720
721 # Store a reference to the Project.
722 try:
David James8d201162013-10-11 17:03:19 -0700723 repo_hooks_projects = self._projects[repo_hooks_project]
Doug Anderson37282b42011-03-04 11:54:18 -0800724 except KeyError:
725 raise ManifestParseError(
726 'project %s not found for repo-hooks' %
727 (repo_hooks_project))
728
David James8d201162013-10-11 17:03:19 -0700729 if len(repo_hooks_projects) != 1:
730 raise ManifestParseError(
731 'internal error parsing repo-hooks in %s' %
732 (self.manifestFile))
733 self._repo_hooks_project = repo_hooks_projects[0]
734
Doug Anderson37282b42011-03-04 11:54:18 -0800735 # Store the enabled hooks in the Project object.
736 self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
Colin Cross23acdd32012-04-21 00:33:54 -0700737 if node.nodeName == 'remove-project':
738 name = self._reqatt(node, 'name')
David Jamesb8433df2014-01-30 10:11:17 -0800739
740 if name not in self._projects:
David Pursehousef9107482012-11-16 19:12:32 +0900741 raise ManifestParseError('remove-project element specifies non-existent '
742 'project: %s' % name)
Colin Cross23acdd32012-04-21 00:33:54 -0700743
David Jamesb8433df2014-01-30 10:11:17 -0800744 for p in self._projects[name]:
745 del self._paths[p.relpath]
746 del self._projects[name]
747
Colin Cross23acdd32012-04-21 00:33:54 -0700748 # If the manifest removes the hooks project, treat it as if it deleted
749 # the repo-hooks element too.
750 if self._repo_hooks_project and (self._repo_hooks_project.name == name):
751 self._repo_hooks_project = None
752
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800753 def _AddMetaProjectMirror(self, m):
754 name = None
755 m_url = m.GetRemote(m.remote.name).url
756 if m_url.endswith('/.git'):
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530757 raise ManifestParseError('refusing to mirror %s' % m_url)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800758
759 if self._default and self._default.remote:
Conley Owensceea3682011-10-20 10:45:47 -0700760 url = self._default.remote.resolvedFetchUrl
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800761 if not url.endswith('/'):
762 url += '/'
763 if m_url.startswith(url):
764 remote = self._default.remote
765 name = m_url[len(url):]
766
767 if name is None:
768 s = m_url.rindex('/') + 1
Conley Owensdb728cd2011-09-26 16:34:01 -0700769 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Shawn O. Pearcef35b2d92012-08-02 11:46:22 -0700770 remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800771 name = m_url[s:]
772
773 if name.endswith('.git'):
774 name = name[:-4]
775
776 if name not in self._projects:
777 m.PreSync()
778 gitdir = os.path.join(self.topdir, '%s.git' % name)
David Pursehousee5913ae2020-02-12 13:56:59 +0900779 project = Project(manifest=self,
780 name=name,
781 remote=remote.ToRemoteSpec(name),
782 gitdir=gitdir,
783 objdir=gitdir,
784 worktree=None,
785 relpath=name or None,
786 revisionExpr=m.revisionExpr,
787 revisionId=None)
David James8d201162013-10-11 17:03:19 -0700788 self._projects[project.name] = [project]
Kwanhong Leeccd218c2014-02-17 13:07:32 +0900789 self._paths[project.relpath] = project
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800790
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700791 def _ParseRemote(self, node):
792 """
793 reads a <remote> element from the manifest file
794 """
795 name = self._reqatt(node, 'name')
Yestin Sunb292b982012-07-02 07:32:50 -0700796 alias = node.getAttribute('alias')
797 if alias == '':
798 alias = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700799 fetch = self._reqatt(node, 'fetch')
Steve Raed6480452016-08-10 15:00:00 -0700800 pushUrl = node.getAttribute('pushurl')
801 if pushUrl == '':
802 pushUrl = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700803 review = node.getAttribute('review')
Shawn O. Pearceae6e0942008-11-06 10:25:35 -0800804 if review == '':
805 review = None
Anthony King36ea2fb2014-05-06 11:54:01 +0100806 revision = node.getAttribute('revision')
807 if revision == '':
808 revision = None
Conley Owensdb728cd2011-09-26 16:34:01 -0700809 manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
Steve Raed6480452016-08-10 15:00:00 -0700810 return _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700811
812 def _ParseDefault(self, node):
813 """
814 reads a <default> element from the manifest file
815 """
816 d = _Default()
817 d.remote = self._get_remote(node)
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700818 d.revisionExpr = node.getAttribute('revision')
819 if d.revisionExpr == '':
820 d.revisionExpr = None
Anatol Pomazau79770d22012-04-20 14:41:59 -0700821
Bryan Jacobsf609f912013-05-06 13:36:24 -0400822 d.destBranchExpr = node.getAttribute('dest-branch') or None
Nasser Grainawida403412018-05-04 12:53:29 -0600823 d.upstreamExpr = node.getAttribute('upstream') or None
Bryan Jacobsf609f912013-05-06 13:36:24 -0400824
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500825 d.sync_j = XmlInt(node, 'sync-j', 1)
826 if d.sync_j <= 0:
827 raise ManifestParseError('%s: sync-j must be greater than 0, not "%s"' %
828 (self.manifestFile, d.sync_j))
Anatol Pomazau79770d22012-04-20 14:41:59 -0700829
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500830 d.sync_c = XmlBool(node, 'sync-c', False)
831 d.sync_s = XmlBool(node, 'sync-s', False)
832 d.sync_tags = XmlBool(node, 'sync-tags', True)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700833 return d
834
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700835 def _ParseNotice(self, node):
836 """
837 reads a <notice> element from the manifest file
838
839 The <notice> element is distinct from other tags in the XML in that the
840 data is conveyed between the start and end tag (it's not an empty-element
841 tag).
842
843 The white space (carriage returns, indentation) for the notice element is
844 relevant and is parsed in a way that is based on how python docstrings work.
845 In fact, the code is remarkably similar to here:
846 http://www.python.org/dev/peps/pep-0257/
847 """
848 # Get the data out of the node...
849 notice = node.childNodes[0].data
850
851 # Figure out minimum indentation, skipping the first line (the same line
852 # as the <notice> tag)...
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530853 minIndent = sys.maxsize
Doug Anderson2b8db3c2010-11-01 15:08:06 -0700854 lines = notice.splitlines()
855 for line in lines[1:]:
856 lstrippedLine = line.lstrip()
857 if lstrippedLine:
858 indent = len(line) - len(lstrippedLine)
859 minIndent = min(indent, minIndent)
860
861 # Strip leading / trailing blank lines and also indentation.
862 cleanLines = [lines[0].strip()]
863 for line in lines[1:]:
864 cleanLines.append(line[minIndent:].rstrip())
865
866 # Clear completely blank lines from front and back...
867 while cleanLines and not cleanLines[0]:
868 del cleanLines[0]
869 while cleanLines and not cleanLines[-1]:
870 del cleanLines[-1]
871
872 return '\n'.join(cleanLines)
873
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800874 def _JoinName(self, parent_name, name):
875 return os.path.join(parent_name, name)
876
877 def _UnjoinName(self, parent_name, name):
878 return os.path.relpath(name, parent_name)
879
David Pursehousee5913ae2020-02-12 13:56:59 +0900880 def _ParseProject(self, node, parent=None, **extra_proj_attrs):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700881 """
882 reads a <project> element from the manifest file
Nico Sallembiena1bfd2c2010-04-06 10:40:01 -0700883 """
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700884 name = self._reqatt(node, 'name')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800885 if parent:
886 name = self._JoinName(parent.name, name)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700887
888 remote = self._get_remote(node)
889 if remote is None:
890 remote = self._default.remote
891 if remote is None:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530892 raise ManifestParseError("no remote for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +0900893 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700894
Anthony King36ea2fb2014-05-06 11:54:01 +0100895 revisionExpr = node.getAttribute('revision') or remote.revision
Shawn O. Pearce3c8dea12009-05-29 18:38:17 -0700896 if not revisionExpr:
897 revisionExpr = self._default.revisionExpr
898 if not revisionExpr:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530899 raise ManifestParseError("no revision for project %s within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +0900900 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700901
902 path = node.getAttribute('path')
903 if not path:
904 path = name
905 if path.startswith('/'):
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530906 raise ManifestParseError("project %s path cannot be absolute in %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +0900907 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700908
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500909 rebase = XmlBool(node, 'rebase', True)
910 sync_c = XmlBool(node, 'sync-c', False)
911 sync_s = XmlBool(node, 'sync-s', self._default.sync_s)
912 sync_tags = XmlBool(node, 'sync-tags', self._default.sync_tags)
Mike Pontillod3153822012-02-28 11:53:24 -0800913
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500914 clone_depth = XmlInt(node, 'clone-depth')
915 if clone_depth is not None and clone_depth <= 0:
916 raise ManifestParseError('%s: clone-depth must be greater than 0, not "%s"' %
917 (self.manifestFile, clone_depth))
David Pursehouseede7f122012-11-27 22:25:30 +0900918
Bryan Jacobsf609f912013-05-06 13:36:24 -0400919 dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
920
Nasser Grainawida403412018-05-04 12:53:29 -0600921 upstream = node.getAttribute('upstream') or self._default.upstreamExpr
Brian Harring14a66742012-09-28 20:21:57 -0700922
Conley Owens971de8e2012-04-16 10:36:08 -0700923 groups = ''
924 if node.hasAttribute('groups'):
925 groups = node.getAttribute('groups')
Josh Triplett884a3872014-06-12 14:57:29 -0700926 groups = self._ParseGroups(groups)
Brian Harring7da13142012-06-15 02:24:20 -0700927
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800928 if parent is None:
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500929 relpath, worktree, gitdir, objdir, use_git_worktrees = \
930 self.GetProjectPaths(name, path)
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -0700931 else:
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500932 use_git_worktrees = False
David James8d201162013-10-11 17:03:19 -0700933 relpath, worktree, gitdir, objdir = \
934 self.GetSubprojectPaths(parent, name, path)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800935
936 default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
937 groups.extend(set(default_groups).difference(groups))
Shawn O. Pearcecd81dd62012-10-26 12:18:00 -0700938
Scott Fandb83b1b2013-02-28 09:34:14 +0800939 if self.IsMirror and node.hasAttribute('force-path'):
Mike Frysingerbb8ee7f2020-02-22 05:30:12 -0500940 if XmlBool(node, 'force-path', False):
Scott Fandb83b1b2013-02-28 09:34:14 +0800941 gitdir = os.path.join(self.topdir, '%s.git' % path)
942
David Pursehousee5913ae2020-02-12 13:56:59 +0900943 project = Project(manifest=self,
944 name=name,
945 remote=remote.ToRemoteSpec(name),
946 gitdir=gitdir,
947 objdir=objdir,
948 worktree=worktree,
949 relpath=relpath,
950 revisionExpr=revisionExpr,
951 revisionId=None,
952 rebase=rebase,
953 groups=groups,
954 sync_c=sync_c,
955 sync_s=sync_s,
956 sync_tags=sync_tags,
957 clone_depth=clone_depth,
958 upstream=upstream,
959 parent=parent,
960 dest_branch=dest_branch,
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500961 use_git_worktrees=use_git_worktrees,
Simran Basib9a1b732015-08-20 12:19:28 -0700962 **extra_proj_attrs)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700963
964 for n in node.childNodes:
Shawn O. Pearce242b5262009-05-19 13:00:29 -0700965 if n.nodeName == 'copyfile':
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700966 self._ParseCopyFile(project, n)
Jeff Hamiltone0df2322014-04-21 17:10:59 -0500967 if n.nodeName == 'linkfile':
968 self._ParseLinkFile(project, n)
James W. Mills24c13082012-04-12 15:04:13 -0500969 if n.nodeName == 'annotation':
970 self._ParseAnnotation(project, n)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800971 if n.nodeName == 'project':
David Pursehousee5913ae2020-02-12 13:56:59 +0900972 project.subprojects.append(self._ParseProject(n, parent=project))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700973
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700974 return project
975
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800976 def GetProjectPaths(self, name, path):
Mike Frysingercebf2272020-05-26 01:02:29 -0400977 # The manifest entries might have trailing slashes. Normalize them to avoid
978 # unexpected filesystem behavior since we do string concatenation below.
979 path = path.rstrip('/')
980 name = name.rstrip('/')
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500981 use_git_worktrees = False
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800982 relpath = path
983 if self.IsMirror:
984 worktree = None
985 gitdir = os.path.join(self.topdir, '%s.git' % name)
David James8d201162013-10-11 17:03:19 -0700986 objdir = gitdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800987 else:
988 worktree = os.path.join(self.topdir, path).replace('\\', '/')
989 gitdir = os.path.join(self.repodir, 'projects', '%s.git' % path)
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500990 # We allow people to mix git worktrees & non-git worktrees for now.
991 # This allows for in situ migration of repo clients.
992 if os.path.exists(gitdir) or not self.UseGitWorktrees:
993 objdir = os.path.join(self.repodir, 'project-objects', '%s.git' % name)
994 else:
995 use_git_worktrees = True
996 gitdir = os.path.join(self.repodir, 'worktrees', '%s.git' % name)
997 objdir = gitdir
998 return relpath, worktree, gitdir, objdir, use_git_worktrees
David James8d201162013-10-11 17:03:19 -0700999
1000 def GetProjectsWithName(self, name):
1001 return self._projects.get(name, [])
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001002
1003 def GetSubprojectName(self, parent, submodule_path):
1004 return os.path.join(parent.name, submodule_path)
1005
1006 def _JoinRelpath(self, parent_relpath, relpath):
1007 return os.path.join(parent_relpath, relpath)
1008
1009 def _UnjoinRelpath(self, parent_relpath, relpath):
1010 return os.path.relpath(relpath, parent_relpath)
1011
David James8d201162013-10-11 17:03:19 -07001012 def GetSubprojectPaths(self, parent, name, path):
Mike Frysingercebf2272020-05-26 01:02:29 -04001013 # The manifest entries might have trailing slashes. Normalize them to avoid
1014 # unexpected filesystem behavior since we do string concatenation below.
1015 path = path.rstrip('/')
1016 name = name.rstrip('/')
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001017 relpath = self._JoinRelpath(parent.relpath, path)
1018 gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
David James8d201162013-10-11 17:03:19 -07001019 objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001020 if self.IsMirror:
1021 worktree = None
1022 else:
1023 worktree = os.path.join(parent.worktree, path).replace('\\', '/')
David James8d201162013-10-11 17:03:19 -07001024 return relpath, worktree, gitdir, objdir
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +08001025
Mike Frysinger04122b72019-07-31 23:32:58 -04001026 @staticmethod
1027 def _CheckLocalPath(path, symlink=False):
1028 """Verify |path| is reasonable for use in <copyfile> & <linkfile>."""
1029 if '~' in path:
1030 return '~ not allowed (due to 8.3 filenames on Windows filesystems)'
1031
1032 # Some filesystems (like Apple's HFS+) try to normalize Unicode codepoints
1033 # which means there are alternative names for ".git". Reject paths with
1034 # these in it as there shouldn't be any reasonable need for them here.
1035 # The set of codepoints here was cribbed from jgit's implementation:
1036 # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
1037 BAD_CODEPOINTS = {
1038 u'\u200C', # ZERO WIDTH NON-JOINER
1039 u'\u200D', # ZERO WIDTH JOINER
1040 u'\u200E', # LEFT-TO-RIGHT MARK
1041 u'\u200F', # RIGHT-TO-LEFT MARK
1042 u'\u202A', # LEFT-TO-RIGHT EMBEDDING
1043 u'\u202B', # RIGHT-TO-LEFT EMBEDDING
1044 u'\u202C', # POP DIRECTIONAL FORMATTING
1045 u'\u202D', # LEFT-TO-RIGHT OVERRIDE
1046 u'\u202E', # RIGHT-TO-LEFT OVERRIDE
1047 u'\u206A', # INHIBIT SYMMETRIC SWAPPING
1048 u'\u206B', # ACTIVATE SYMMETRIC SWAPPING
1049 u'\u206C', # INHIBIT ARABIC FORM SHAPING
1050 u'\u206D', # ACTIVATE ARABIC FORM SHAPING
1051 u'\u206E', # NATIONAL DIGIT SHAPES
1052 u'\u206F', # NOMINAL DIGIT SHAPES
1053 u'\uFEFF', # ZERO WIDTH NO-BREAK SPACE
1054 }
1055 if BAD_CODEPOINTS & set(path):
1056 # This message is more expansive than reality, but should be fine.
1057 return 'Unicode combining characters not allowed'
1058
1059 # Assume paths might be used on case-insensitive filesystems.
1060 path = path.lower()
1061
Mike Frysingerd9254592020-02-19 22:36:26 -05001062 # Split up the path by its components. We can't use os.path.sep exclusively
1063 # as some platforms (like Windows) will convert / to \ and that bypasses all
1064 # our constructed logic here. Especially since manifest authors only use
1065 # / in their paths.
1066 resep = re.compile(r'[/%s]' % re.escape(os.path.sep))
1067 parts = resep.split(path)
1068
Mike Frysingerae625412020-02-10 17:10:03 -05001069 # Some people use src="." to create stable links to projects. Lets allow
1070 # that but reject all other uses of "." to keep things simple.
Mike Frysingerae625412020-02-10 17:10:03 -05001071 if parts != ['.']:
1072 for part in set(parts):
1073 if part in {'.', '..', '.git'} or part.startswith('.repo'):
1074 return 'bad component: %s' % (part,)
Mike Frysinger04122b72019-07-31 23:32:58 -04001075
Mike Frysingerd9254592020-02-19 22:36:26 -05001076 if not symlink and resep.match(path[-1]):
Mike Frysinger04122b72019-07-31 23:32:58 -04001077 return 'dirs not allowed'
1078
Mike Frysingerd9254592020-02-19 22:36:26 -05001079 # NB: The two abspath checks here are to handle platforms with multiple
1080 # filesystem path styles (e.g. Windows).
Mike Frysinger04122b72019-07-31 23:32:58 -04001081 norm = os.path.normpath(path)
Mike Frysingerd9254592020-02-19 22:36:26 -05001082 if (norm == '..' or
1083 (len(norm) >= 3 and norm.startswith('..') and resep.match(norm[0])) or
1084 os.path.isabs(norm) or
1085 norm.startswith('/')):
Mike Frysinger04122b72019-07-31 23:32:58 -04001086 return 'path cannot be outside'
1087
1088 @classmethod
1089 def _ValidateFilePaths(cls, element, src, dest):
1090 """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
1091
1092 We verify the path independent of any filesystem state as we won't have a
1093 checkout available to compare to. i.e. This is for parsing validation
1094 purposes only.
1095
1096 We'll do full/live sanity checking before we do the actual filesystem
1097 modifications in _CopyFile/_LinkFile/etc...
1098 """
1099 # |dest| is the file we write to or symlink we create.
1100 # It is relative to the top of the repo client checkout.
1101 msg = cls._CheckLocalPath(dest)
1102 if msg:
1103 raise ManifestInvalidPathError(
1104 '<%s> invalid "dest": %s: %s' % (element, dest, msg))
1105
1106 # |src| is the file we read from or path we point to for symlinks.
1107 # It is relative to the top of the git project checkout.
1108 msg = cls._CheckLocalPath(src, symlink=element == 'linkfile')
1109 if msg:
1110 raise ManifestInvalidPathError(
1111 '<%s> invalid "src": %s: %s' % (element, src, msg))
1112
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001113 def _ParseCopyFile(self, project, node):
1114 src = self._reqatt(node, 'src')
1115 dest = self._reqatt(node, 'dest')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -08001116 if not self.IsMirror:
1117 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001118 # dest is relative to the top of the tree.
1119 # We only validate paths if we actually plan to process them.
1120 self._ValidateFilePaths('copyfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001121 project.AddCopyFile(src, dest, self.topdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001122
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001123 def _ParseLinkFile(self, project, node):
1124 src = self._reqatt(node, 'src')
1125 dest = self._reqatt(node, 'dest')
1126 if not self.IsMirror:
1127 # src is project relative;
Mike Frysinger04122b72019-07-31 23:32:58 -04001128 # dest is relative to the top of the tree.
1129 # We only validate paths if we actually plan to process them.
1130 self._ValidateFilePaths('linkfile', src, dest)
Mike Frysingere6a202f2019-08-02 15:57:57 -04001131 project.AddLinkFile(src, dest, self.topdir)
Jeff Hamiltone0df2322014-04-21 17:10:59 -05001132
James W. Mills24c13082012-04-12 15:04:13 -05001133 def _ParseAnnotation(self, project, node):
1134 name = self._reqatt(node, 'name')
1135 value = self._reqatt(node, 'value')
1136 try:
1137 keep = self._reqatt(node, 'keep').lower()
1138 except ManifestParseError:
1139 keep = "true"
1140 if keep != "true" and keep != "false":
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301141 raise ManifestParseError('optional "keep" attribute must be '
David Pursehouseabdf7502020-02-12 14:58:39 +09001142 '"true" or "false"')
James W. Mills24c13082012-04-12 15:04:13 -05001143 project.AddAnnotation(name, value, keep)
1144
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001145 def _get_remote(self, node):
1146 name = node.getAttribute('remote')
1147 if not name:
1148 return None
1149
1150 v = self._remotes.get(name)
1151 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301152 raise ManifestParseError("remote %s not defined in %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001153 (name, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001154 return v
1155
1156 def _reqatt(self, node, attname):
1157 """
1158 reads a required attribute from the node.
1159 """
1160 v = node.getAttribute(attname)
1161 if not v:
Chirayu Desai217ea7d2013-03-01 19:14:38 +05301162 raise ManifestParseError("no %s in <%s> within %s" %
David Pursehouseabdf7502020-02-12 14:58:39 +09001163 (attname, node.nodeName, self.manifestFile))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001164 return v
Julien Camperguedd654222014-01-09 16:21:37 +01001165
1166 def projectsDiff(self, manifest):
1167 """return the projects differences between two manifests.
1168
1169 The diff will be from self to given manifest.
1170
1171 """
1172 fromProjects = self.paths
1173 toProjects = manifest.paths
1174
Anthony King7446c592014-05-06 09:19:39 +01001175 fromKeys = sorted(fromProjects.keys())
1176 toKeys = sorted(toProjects.keys())
Julien Camperguedd654222014-01-09 16:21:37 +01001177
1178 diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
1179
1180 for proj in fromKeys:
David Pursehouseeeff3532020-02-12 11:24:10 +09001181 if proj not in toKeys:
Julien Camperguedd654222014-01-09 16:21:37 +01001182 diff['removed'].append(fromProjects[proj])
1183 else:
1184 fromProj = fromProjects[proj]
1185 toProj = toProjects[proj]
1186 try:
1187 fromRevId = fromProj.GetCommitRevisionId()
1188 toRevId = toProj.GetCommitRevisionId()
1189 except ManifestInvalidRevisionError:
1190 diff['unreachable'].append((fromProj, toProj))
1191 else:
1192 if fromRevId != toRevId:
1193 diff['changed'].append((fromProj, toProj))
1194 toKeys.remove(proj)
1195
1196 for proj in toKeys:
1197 diff['added'].append(toProjects[proj])
1198
1199 return diff
Simran Basib9a1b732015-08-20 12:19:28 -07001200
1201
1202class GitcManifest(XmlManifest):
1203
1204 def __init__(self, repodir, gitc_client_name):
1205 """Initialize the GitcManifest object."""
1206 super(GitcManifest, self).__init__(repodir)
1207 self.isGitcClient = True
1208 self.gitc_client_name = gitc_client_name
Simran Basi8ce50412015-08-28 14:25:44 -07001209 self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
Simran Basib9a1b732015-08-20 12:19:28 -07001210 gitc_client_name)
1211 self.manifestFile = os.path.join(self.gitc_client_dir, '.manifest')
1212
David Pursehousee5913ae2020-02-12 13:56:59 +09001213 def _ParseProject(self, node, parent=None):
Simran Basib9a1b732015-08-20 12:19:28 -07001214 """Override _ParseProject and add support for GITC specific attributes."""
1215 return super(GitcManifest, self)._ParseProject(
1216 node, parent=parent, old_revision=node.getAttribute('old-revision'))
1217
1218 def _output_manifest_project_extras(self, p, e):
1219 """Output GITC Specific Project attributes"""
1220 if p.old_revision:
Stefan Beller66851062016-06-17 16:40:08 -07001221 e.setAttribute('old-revision', str(p.old_revision))