manifest_xml.py 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  1. # -*- coding:utf-8 -*-
  2. #
  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. from __future__ import print_function
  17. import itertools
  18. import os
  19. import re
  20. import sys
  21. import xml.dom.minidom
  22. from pyversion import is_python3
  23. if is_python3():
  24. import urllib.parse
  25. else:
  26. import imp
  27. import urlparse
  28. urllib = imp.new_module('urllib')
  29. urllib.parse = urlparse
  30. import gitc_utils
  31. from git_config import GitConfig
  32. from git_refs import R_HEADS, HEAD
  33. import platform_utils
  34. from project import RemoteSpec, Project, MetaProject
  35. from error import (ManifestParseError, ManifestInvalidPathError,
  36. ManifestInvalidRevisionError)
  37. MANIFEST_FILE_NAME = 'manifest.xml'
  38. LOCAL_MANIFEST_NAME = 'local_manifest.xml'
  39. LOCAL_MANIFESTS_DIR_NAME = 'local_manifests'
  40. # urljoin gets confused if the scheme is not known.
  41. urllib.parse.uses_relative.extend([
  42. 'ssh',
  43. 'git',
  44. 'persistent-https',
  45. 'sso',
  46. 'rpc'])
  47. urllib.parse.uses_netloc.extend([
  48. 'ssh',
  49. 'git',
  50. 'persistent-https',
  51. 'sso',
  52. 'rpc'])
  53. def XmlBool(node, attr, default=None):
  54. """Determine boolean value of |node|'s |attr|.
  55. Invalid values will issue a non-fatal warning.
  56. Args:
  57. node: XML node whose attributes we access.
  58. attr: The attribute to access.
  59. default: If the attribute is not set (value is empty), then use this.
  60. Returns:
  61. True if the attribute is a valid string representing true.
  62. False if the attribute is a valid string representing false.
  63. |default| otherwise.
  64. """
  65. value = node.getAttribute(attr)
  66. s = value.lower()
  67. if s == '':
  68. return default
  69. elif s in {'yes', 'true', '1'}:
  70. return True
  71. elif s in {'no', 'false', '0'}:
  72. return False
  73. else:
  74. print('warning: manifest: %s="%s": ignoring invalid XML boolean' %
  75. (attr, value), file=sys.stderr)
  76. return default
  77. def XmlInt(node, attr, default=None):
  78. """Determine integer value of |node|'s |attr|.
  79. Args:
  80. node: XML node whose attributes we access.
  81. attr: The attribute to access.
  82. default: If the attribute is not set (value is empty), then use this.
  83. Returns:
  84. The number if the attribute is a valid number.
  85. Raises:
  86. ManifestParseError: The number is invalid.
  87. """
  88. value = node.getAttribute(attr)
  89. if not value:
  90. return default
  91. try:
  92. return int(value)
  93. except ValueError:
  94. raise ManifestParseError('manifest: invalid %s="%s" integer' %
  95. (attr, value))
  96. class _Default(object):
  97. """Project defaults within the manifest."""
  98. revisionExpr = None
  99. destBranchExpr = None
  100. upstreamExpr = None
  101. remote = None
  102. sync_j = 1
  103. sync_c = False
  104. sync_s = False
  105. sync_tags = True
  106. def __eq__(self, other):
  107. return self.__dict__ == other.__dict__
  108. def __ne__(self, other):
  109. return self.__dict__ != other.__dict__
  110. class _XmlRemote(object):
  111. def __init__(self,
  112. name,
  113. alias=None,
  114. fetch=None,
  115. pushUrl=None,
  116. manifestUrl=None,
  117. review=None,
  118. revision=None):
  119. self.name = name
  120. self.fetchUrl = fetch
  121. self.pushUrl = pushUrl
  122. self.manifestUrl = manifestUrl
  123. self.remoteAlias = alias
  124. self.reviewUrl = review
  125. self.revision = revision
  126. self.resolvedFetchUrl = self._resolveFetchUrl()
  127. def __eq__(self, other):
  128. return self.__dict__ == other.__dict__
  129. def __ne__(self, other):
  130. return self.__dict__ != other.__dict__
  131. def _resolveFetchUrl(self):
  132. url = self.fetchUrl.rstrip('/')
  133. manifestUrl = self.manifestUrl.rstrip('/')
  134. # urljoin will gets confused over quite a few things. The ones we care
  135. # about here are:
  136. # * no scheme in the base url, like <hostname:port>
  137. # We handle no scheme by replacing it with an obscure protocol, gopher
  138. # and then replacing it with the original when we are done.
  139. if manifestUrl.find(':') != manifestUrl.find('/') - 1:
  140. url = urllib.parse.urljoin('gopher://' + manifestUrl, url)
  141. url = re.sub(r'^gopher://', '', url)
  142. else:
  143. url = urllib.parse.urljoin(manifestUrl, url)
  144. return url
  145. def ToRemoteSpec(self, projectName):
  146. fetchUrl = self.resolvedFetchUrl.rstrip('/')
  147. url = fetchUrl + '/' + projectName
  148. remoteName = self.name
  149. if self.remoteAlias:
  150. remoteName = self.remoteAlias
  151. return RemoteSpec(remoteName,
  152. url=url,
  153. pushUrl=self.pushUrl,
  154. review=self.reviewUrl,
  155. orig_name=self.name,
  156. fetchUrl=self.fetchUrl)
  157. class XmlManifest(object):
  158. """manages the repo configuration file"""
  159. def __init__(self, repodir):
  160. self.repodir = os.path.abspath(repodir)
  161. self.topdir = os.path.dirname(self.repodir)
  162. self.manifestFile = os.path.join(self.repodir, MANIFEST_FILE_NAME)
  163. self.globalConfig = GitConfig.ForUser()
  164. self.localManifestWarning = False
  165. self.isGitcClient = False
  166. self._load_local_manifests = True
  167. self.repoProject = MetaProject(self, 'repo',
  168. gitdir=os.path.join(repodir, 'repo/.git'),
  169. worktree=os.path.join(repodir, 'repo'))
  170. mp = MetaProject(self, 'manifests',
  171. gitdir=os.path.join(repodir, 'manifests.git'),
  172. worktree=os.path.join(repodir, 'manifests'))
  173. self.manifestProject = mp
  174. # This is a bit hacky, but we're in a chicken & egg situation: all the
  175. # normal repo settings live in the manifestProject which we just setup
  176. # above, so we couldn't easily query before that. We assume Project()
  177. # init doesn't care if this changes afterwards.
  178. if os.path.exists(mp.gitdir) and mp.config.GetBoolean('repo.worktree'):
  179. mp.use_git_worktrees = True
  180. self._Unload()
  181. def Override(self, name, load_local_manifests=True):
  182. """Use a different manifest, just for the current instantiation.
  183. """
  184. path = None
  185. # Look for a manifest by path in the filesystem (including the cwd).
  186. if not load_local_manifests:
  187. local_path = os.path.abspath(name)
  188. if os.path.isfile(local_path):
  189. path = local_path
  190. # Look for manifests by name from the manifests repo.
  191. if path is None:
  192. path = os.path.join(self.manifestProject.worktree, name)
  193. if not os.path.isfile(path):
  194. raise ManifestParseError('manifest %s not found' % name)
  195. old = self.manifestFile
  196. try:
  197. self._load_local_manifests = load_local_manifests
  198. self.manifestFile = path
  199. self._Unload()
  200. self._Load()
  201. finally:
  202. self.manifestFile = old
  203. def Link(self, name):
  204. """Update the repo metadata to use a different manifest.
  205. """
  206. self.Override(name)
  207. # Old versions of repo would generate symlinks we need to clean up.
  208. if os.path.lexists(self.manifestFile):
  209. platform_utils.remove(self.manifestFile)
  210. # This file is interpreted as if it existed inside the manifest repo.
  211. # That allows us to use <include> with the relative file name.
  212. with open(self.manifestFile, 'w') as fp:
  213. fp.write("""<?xml version="1.0" encoding="UTF-8"?>
  214. <!--
  215. DO NOT EDIT THIS FILE! It is generated by repo and changes will be discarded.
  216. If you want to use a different manifest, use `repo init -m <file>` instead.
  217. If you want to customize your checkout by overriding manifest settings, use
  218. the local_manifests/ directory instead.
  219. For more information on repo manifests, check out:
  220. https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
  221. -->
  222. <manifest>
  223. <include name="%s" />
  224. </manifest>
  225. """ % (name,))
  226. def _RemoteToXml(self, r, doc, root):
  227. e = doc.createElement('remote')
  228. root.appendChild(e)
  229. e.setAttribute('name', r.name)
  230. e.setAttribute('fetch', r.fetchUrl)
  231. if r.pushUrl is not None:
  232. e.setAttribute('pushurl', r.pushUrl)
  233. if r.remoteAlias is not None:
  234. e.setAttribute('alias', r.remoteAlias)
  235. if r.reviewUrl is not None:
  236. e.setAttribute('review', r.reviewUrl)
  237. if r.revision is not None:
  238. e.setAttribute('revision', r.revision)
  239. def _ParseGroups(self, groups):
  240. return [x for x in re.split(r'[,\s]+', groups) if x]
  241. def Save(self, fd, peg_rev=False, peg_rev_upstream=True, peg_rev_dest_branch=True, groups=None):
  242. """Write the current manifest out to the given file descriptor.
  243. """
  244. mp = self.manifestProject
  245. if groups is None:
  246. groups = mp.config.GetString('manifest.groups')
  247. if groups:
  248. groups = self._ParseGroups(groups)
  249. doc = xml.dom.minidom.Document()
  250. root = doc.createElement('manifest')
  251. doc.appendChild(root)
  252. # Save out the notice. There's a little bit of work here to give it the
  253. # right whitespace, which assumes that the notice is automatically indented
  254. # by 4 by minidom.
  255. if self.notice:
  256. notice_element = root.appendChild(doc.createElement('notice'))
  257. notice_lines = self.notice.splitlines()
  258. indented_notice = ('\n'.join(" " * 4 + line for line in notice_lines))[4:]
  259. notice_element.appendChild(doc.createTextNode(indented_notice))
  260. d = self.default
  261. for r in sorted(self.remotes):
  262. self._RemoteToXml(self.remotes[r], doc, root)
  263. if self.remotes:
  264. root.appendChild(doc.createTextNode(''))
  265. have_default = False
  266. e = doc.createElement('default')
  267. if d.remote:
  268. have_default = True
  269. e.setAttribute('remote', d.remote.name)
  270. if d.revisionExpr:
  271. have_default = True
  272. e.setAttribute('revision', d.revisionExpr)
  273. if d.destBranchExpr:
  274. have_default = True
  275. e.setAttribute('dest-branch', d.destBranchExpr)
  276. if d.upstreamExpr:
  277. have_default = True
  278. e.setAttribute('upstream', d.upstreamExpr)
  279. if d.sync_j > 1:
  280. have_default = True
  281. e.setAttribute('sync-j', '%d' % d.sync_j)
  282. if d.sync_c:
  283. have_default = True
  284. e.setAttribute('sync-c', 'true')
  285. if d.sync_s:
  286. have_default = True
  287. e.setAttribute('sync-s', 'true')
  288. if not d.sync_tags:
  289. have_default = True
  290. e.setAttribute('sync-tags', 'false')
  291. if have_default:
  292. root.appendChild(e)
  293. root.appendChild(doc.createTextNode(''))
  294. if self._manifest_server:
  295. e = doc.createElement('manifest-server')
  296. e.setAttribute('url', self._manifest_server)
  297. root.appendChild(e)
  298. root.appendChild(doc.createTextNode(''))
  299. def output_projects(parent, parent_node, projects):
  300. for project_name in projects:
  301. for project in self._projects[project_name]:
  302. output_project(parent, parent_node, project)
  303. def output_project(parent, parent_node, p):
  304. if not p.MatchesGroups(groups):
  305. return
  306. name = p.name
  307. relpath = p.relpath
  308. if parent:
  309. name = self._UnjoinName(parent.name, name)
  310. relpath = self._UnjoinRelpath(parent.relpath, relpath)
  311. e = doc.createElement('project')
  312. parent_node.appendChild(e)
  313. e.setAttribute('name', name)
  314. if relpath != name:
  315. e.setAttribute('path', relpath)
  316. remoteName = None
  317. if d.remote:
  318. remoteName = d.remote.name
  319. if not d.remote or p.remote.orig_name != remoteName:
  320. remoteName = p.remote.orig_name
  321. e.setAttribute('remote', remoteName)
  322. if peg_rev:
  323. if self.IsMirror:
  324. value = p.bare_git.rev_parse(p.revisionExpr + '^0')
  325. else:
  326. value = p.work_git.rev_parse(HEAD + '^0')
  327. e.setAttribute('revision', value)
  328. if peg_rev_upstream:
  329. if p.upstream:
  330. e.setAttribute('upstream', p.upstream)
  331. elif value != p.revisionExpr:
  332. # Only save the origin if the origin is not a sha1, and the default
  333. # isn't our value
  334. e.setAttribute('upstream', p.revisionExpr)
  335. if peg_rev_dest_branch:
  336. if p.dest_branch:
  337. e.setAttribute('dest-branch', p.dest_branch)
  338. elif value != p.revisionExpr:
  339. e.setAttribute('dest-branch', p.revisionExpr)
  340. else:
  341. revision = self.remotes[p.remote.orig_name].revision or d.revisionExpr
  342. if not revision or revision != p.revisionExpr:
  343. e.setAttribute('revision', p.revisionExpr)
  344. if (p.upstream and (p.upstream != p.revisionExpr or
  345. p.upstream != d.upstreamExpr)):
  346. e.setAttribute('upstream', p.upstream)
  347. if p.dest_branch and p.dest_branch != d.destBranchExpr:
  348. e.setAttribute('dest-branch', p.dest_branch)
  349. for c in p.copyfiles:
  350. ce = doc.createElement('copyfile')
  351. ce.setAttribute('src', c.src)
  352. ce.setAttribute('dest', c.dest)
  353. e.appendChild(ce)
  354. for l in p.linkfiles:
  355. le = doc.createElement('linkfile')
  356. le.setAttribute('src', l.src)
  357. le.setAttribute('dest', l.dest)
  358. e.appendChild(le)
  359. default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
  360. egroups = [g for g in p.groups if g not in default_groups]
  361. if egroups:
  362. e.setAttribute('groups', ','.join(egroups))
  363. for a in p.annotations:
  364. if a.keep == "true":
  365. ae = doc.createElement('annotation')
  366. ae.setAttribute('name', a.name)
  367. ae.setAttribute('value', a.value)
  368. e.appendChild(ae)
  369. if p.sync_c:
  370. e.setAttribute('sync-c', 'true')
  371. if p.sync_s:
  372. e.setAttribute('sync-s', 'true')
  373. if not p.sync_tags:
  374. e.setAttribute('sync-tags', 'false')
  375. if p.clone_depth:
  376. e.setAttribute('clone-depth', str(p.clone_depth))
  377. self._output_manifest_project_extras(p, e)
  378. if p.subprojects:
  379. subprojects = set(subp.name for subp in p.subprojects)
  380. output_projects(p, e, list(sorted(subprojects)))
  381. projects = set(p.name for p in self._paths.values() if not p.parent)
  382. output_projects(None, root, list(sorted(projects)))
  383. if self._repo_hooks_project:
  384. root.appendChild(doc.createTextNode(''))
  385. e = doc.createElement('repo-hooks')
  386. e.setAttribute('in-project', self._repo_hooks_project.name)
  387. e.setAttribute('enabled-list',
  388. ' '.join(self._repo_hooks_project.enabled_repo_hooks))
  389. root.appendChild(e)
  390. doc.writexml(fd, '', ' ', '\n', 'UTF-8')
  391. def _output_manifest_project_extras(self, p, e):
  392. """Manifests can modify e if they support extra project attributes."""
  393. pass
  394. @property
  395. def paths(self):
  396. self._Load()
  397. return self._paths
  398. @property
  399. def projects(self):
  400. self._Load()
  401. return list(self._paths.values())
  402. @property
  403. def remotes(self):
  404. self._Load()
  405. return self._remotes
  406. @property
  407. def default(self):
  408. self._Load()
  409. return self._default
  410. @property
  411. def repo_hooks_project(self):
  412. self._Load()
  413. return self._repo_hooks_project
  414. @property
  415. def notice(self):
  416. self._Load()
  417. return self._notice
  418. @property
  419. def manifest_server(self):
  420. self._Load()
  421. return self._manifest_server
  422. @property
  423. def CloneBundle(self):
  424. clone_bundle = self.manifestProject.config.GetBoolean('repo.clonebundle')
  425. if clone_bundle is None:
  426. return False if self.manifestProject.config.GetBoolean('repo.partialclone') else True
  427. else:
  428. return clone_bundle
  429. @property
  430. def CloneFilter(self):
  431. if self.manifestProject.config.GetBoolean('repo.partialclone'):
  432. return self.manifestProject.config.GetString('repo.clonefilter')
  433. return None
  434. @property
  435. def IsMirror(self):
  436. return self.manifestProject.config.GetBoolean('repo.mirror')
  437. @property
  438. def UseGitWorktrees(self):
  439. return self.manifestProject.config.GetBoolean('repo.worktree')
  440. @property
  441. def IsArchive(self):
  442. return self.manifestProject.config.GetBoolean('repo.archive')
  443. @property
  444. def HasSubmodules(self):
  445. return self.manifestProject.config.GetBoolean('repo.submodules')
  446. def _Unload(self):
  447. self._loaded = False
  448. self._projects = {}
  449. self._paths = {}
  450. self._remotes = {}
  451. self._default = None
  452. self._repo_hooks_project = None
  453. self._notice = None
  454. self.branch = None
  455. self._manifest_server = None
  456. def _Load(self):
  457. if not self._loaded:
  458. m = self.manifestProject
  459. b = m.GetBranch(m.CurrentBranch).merge
  460. if b is not None and b.startswith(R_HEADS):
  461. b = b[len(R_HEADS):]
  462. self.branch = b
  463. nodes = []
  464. nodes.append(self._ParseManifestXml(self.manifestFile,
  465. self.manifestProject.worktree))
  466. if self._load_local_manifests:
  467. local = os.path.join(self.repodir, LOCAL_MANIFEST_NAME)
  468. if os.path.exists(local):
  469. if not self.localManifestWarning:
  470. self.localManifestWarning = True
  471. print('warning: %s is deprecated; put local manifests '
  472. 'in `%s` instead' % (LOCAL_MANIFEST_NAME,
  473. os.path.join(self.repodir, LOCAL_MANIFESTS_DIR_NAME)),
  474. file=sys.stderr)
  475. nodes.append(self._ParseManifestXml(local, self.repodir))
  476. local_dir = os.path.abspath(os.path.join(self.repodir,
  477. LOCAL_MANIFESTS_DIR_NAME))
  478. try:
  479. for local_file in sorted(platform_utils.listdir(local_dir)):
  480. if local_file.endswith('.xml'):
  481. local = os.path.join(local_dir, local_file)
  482. nodes.append(self._ParseManifestXml(local, self.repodir))
  483. except OSError:
  484. pass
  485. try:
  486. self._ParseManifest(nodes)
  487. except ManifestParseError as e:
  488. # There was a problem parsing, unload ourselves in case they catch
  489. # this error and try again later, we will show the correct error
  490. self._Unload()
  491. raise e
  492. if self.IsMirror:
  493. self._AddMetaProjectMirror(self.repoProject)
  494. self._AddMetaProjectMirror(self.manifestProject)
  495. self._loaded = True
  496. def _ParseManifestXml(self, path, include_root):
  497. try:
  498. root = xml.dom.minidom.parse(path)
  499. except (OSError, xml.parsers.expat.ExpatError) as e:
  500. raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
  501. if not root or not root.childNodes:
  502. raise ManifestParseError("no root node in %s" % (path,))
  503. for manifest in root.childNodes:
  504. if manifest.nodeName == 'manifest':
  505. break
  506. else:
  507. raise ManifestParseError("no <manifest> in %s" % (path,))
  508. nodes = []
  509. for node in manifest.childNodes:
  510. if node.nodeName == 'include':
  511. name = self._reqatt(node, 'name')
  512. fp = os.path.join(include_root, name)
  513. if not os.path.isfile(fp):
  514. raise ManifestParseError("include %s doesn't exist or isn't a file"
  515. % (name,))
  516. try:
  517. nodes.extend(self._ParseManifestXml(fp, include_root))
  518. # should isolate this to the exact exception, but that's
  519. # tricky. actual parsing implementation may vary.
  520. except (KeyboardInterrupt, RuntimeError, SystemExit):
  521. raise
  522. except Exception as e:
  523. raise ManifestParseError(
  524. "failed parsing included manifest %s: %s" % (name, e))
  525. else:
  526. nodes.append(node)
  527. return nodes
  528. def _ParseManifest(self, node_list):
  529. for node in itertools.chain(*node_list):
  530. if node.nodeName == 'remote':
  531. remote = self._ParseRemote(node)
  532. if remote:
  533. if remote.name in self._remotes:
  534. if remote != self._remotes[remote.name]:
  535. raise ManifestParseError(
  536. 'remote %s already exists with different attributes' %
  537. (remote.name))
  538. else:
  539. self._remotes[remote.name] = remote
  540. for node in itertools.chain(*node_list):
  541. if node.nodeName == 'default':
  542. new_default = self._ParseDefault(node)
  543. if self._default is None:
  544. self._default = new_default
  545. elif new_default != self._default:
  546. raise ManifestParseError('duplicate default in %s' %
  547. (self.manifestFile))
  548. if self._default is None:
  549. self._default = _Default()
  550. for node in itertools.chain(*node_list):
  551. if node.nodeName == 'notice':
  552. if self._notice is not None:
  553. raise ManifestParseError(
  554. 'duplicate notice in %s' %
  555. (self.manifestFile))
  556. self._notice = self._ParseNotice(node)
  557. for node in itertools.chain(*node_list):
  558. if node.nodeName == 'manifest-server':
  559. url = self._reqatt(node, 'url')
  560. if self._manifest_server is not None:
  561. raise ManifestParseError(
  562. 'duplicate manifest-server in %s' %
  563. (self.manifestFile))
  564. self._manifest_server = url
  565. def recursively_add_projects(project):
  566. projects = self._projects.setdefault(project.name, [])
  567. if project.relpath is None:
  568. raise ManifestParseError(
  569. 'missing path for %s in %s' %
  570. (project.name, self.manifestFile))
  571. if project.relpath in self._paths:
  572. raise ManifestParseError(
  573. 'duplicate path %s in %s' %
  574. (project.relpath, self.manifestFile))
  575. self._paths[project.relpath] = project
  576. projects.append(project)
  577. for subproject in project.subprojects:
  578. recursively_add_projects(subproject)
  579. for node in itertools.chain(*node_list):
  580. if node.nodeName == 'project':
  581. project = self._ParseProject(node)
  582. recursively_add_projects(project)
  583. if node.nodeName == 'extend-project':
  584. name = self._reqatt(node, 'name')
  585. if name not in self._projects:
  586. raise ManifestParseError('extend-project element specifies non-existent '
  587. 'project: %s' % name)
  588. path = node.getAttribute('path')
  589. groups = node.getAttribute('groups')
  590. if groups:
  591. groups = self._ParseGroups(groups)
  592. revision = node.getAttribute('revision')
  593. remote = node.getAttribute('remote')
  594. if remote:
  595. remote = self._get_remote(node)
  596. for p in self._projects[name]:
  597. if path and p.relpath != path:
  598. continue
  599. if groups:
  600. p.groups.extend(groups)
  601. if revision:
  602. p.revisionExpr = revision
  603. if remote:
  604. p.remote = remote.ToRemoteSpec(name)
  605. if node.nodeName == 'repo-hooks':
  606. # Get the name of the project and the (space-separated) list of enabled.
  607. repo_hooks_project = self._reqatt(node, 'in-project')
  608. enabled_repo_hooks = self._reqatt(node, 'enabled-list').split()
  609. # Only one project can be the hooks project
  610. if self._repo_hooks_project is not None:
  611. raise ManifestParseError(
  612. 'duplicate repo-hooks in %s' %
  613. (self.manifestFile))
  614. # Store a reference to the Project.
  615. try:
  616. repo_hooks_projects = self._projects[repo_hooks_project]
  617. except KeyError:
  618. raise ManifestParseError(
  619. 'project %s not found for repo-hooks' %
  620. (repo_hooks_project))
  621. if len(repo_hooks_projects) != 1:
  622. raise ManifestParseError(
  623. 'internal error parsing repo-hooks in %s' %
  624. (self.manifestFile))
  625. self._repo_hooks_project = repo_hooks_projects[0]
  626. # Store the enabled hooks in the Project object.
  627. self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
  628. if node.nodeName == 'remove-project':
  629. name = self._reqatt(node, 'name')
  630. if name not in self._projects:
  631. raise ManifestParseError('remove-project element specifies non-existent '
  632. 'project: %s' % name)
  633. for p in self._projects[name]:
  634. del self._paths[p.relpath]
  635. del self._projects[name]
  636. # If the manifest removes the hooks project, treat it as if it deleted
  637. # the repo-hooks element too.
  638. if self._repo_hooks_project and (self._repo_hooks_project.name == name):
  639. self._repo_hooks_project = None
  640. def _AddMetaProjectMirror(self, m):
  641. name = None
  642. m_url = m.GetRemote(m.remote.name).url
  643. if m_url.endswith('/.git'):
  644. raise ManifestParseError('refusing to mirror %s' % m_url)
  645. if self._default and self._default.remote:
  646. url = self._default.remote.resolvedFetchUrl
  647. if not url.endswith('/'):
  648. url += '/'
  649. if m_url.startswith(url):
  650. remote = self._default.remote
  651. name = m_url[len(url):]
  652. if name is None:
  653. s = m_url.rindex('/') + 1
  654. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  655. remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
  656. name = m_url[s:]
  657. if name.endswith('.git'):
  658. name = name[:-4]
  659. if name not in self._projects:
  660. m.PreSync()
  661. gitdir = os.path.join(self.topdir, '%s.git' % name)
  662. project = Project(manifest=self,
  663. name=name,
  664. remote=remote.ToRemoteSpec(name),
  665. gitdir=gitdir,
  666. objdir=gitdir,
  667. worktree=None,
  668. relpath=name or None,
  669. revisionExpr=m.revisionExpr,
  670. revisionId=None)
  671. self._projects[project.name] = [project]
  672. self._paths[project.relpath] = project
  673. def _ParseRemote(self, node):
  674. """
  675. reads a <remote> element from the manifest file
  676. """
  677. name = self._reqatt(node, 'name')
  678. alias = node.getAttribute('alias')
  679. if alias == '':
  680. alias = None
  681. fetch = self._reqatt(node, 'fetch')
  682. pushUrl = node.getAttribute('pushurl')
  683. if pushUrl == '':
  684. pushUrl = None
  685. review = node.getAttribute('review')
  686. if review == '':
  687. review = None
  688. revision = node.getAttribute('revision')
  689. if revision == '':
  690. revision = None
  691. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  692. return _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
  693. def _ParseDefault(self, node):
  694. """
  695. reads a <default> element from the manifest file
  696. """
  697. d = _Default()
  698. d.remote = self._get_remote(node)
  699. d.revisionExpr = node.getAttribute('revision')
  700. if d.revisionExpr == '':
  701. d.revisionExpr = None
  702. d.destBranchExpr = node.getAttribute('dest-branch') or None
  703. d.upstreamExpr = node.getAttribute('upstream') or None
  704. d.sync_j = XmlInt(node, 'sync-j', 1)
  705. if d.sync_j <= 0:
  706. raise ManifestParseError('%s: sync-j must be greater than 0, not "%s"' %
  707. (self.manifestFile, d.sync_j))
  708. d.sync_c = XmlBool(node, 'sync-c', False)
  709. d.sync_s = XmlBool(node, 'sync-s', False)
  710. d.sync_tags = XmlBool(node, 'sync-tags', True)
  711. return d
  712. def _ParseNotice(self, node):
  713. """
  714. reads a <notice> element from the manifest file
  715. The <notice> element is distinct from other tags in the XML in that the
  716. data is conveyed between the start and end tag (it's not an empty-element
  717. tag).
  718. The white space (carriage returns, indentation) for the notice element is
  719. relevant and is parsed in a way that is based on how python docstrings work.
  720. In fact, the code is remarkably similar to here:
  721. http://www.python.org/dev/peps/pep-0257/
  722. """
  723. # Get the data out of the node...
  724. notice = node.childNodes[0].data
  725. # Figure out minimum indentation, skipping the first line (the same line
  726. # as the <notice> tag)...
  727. minIndent = sys.maxsize
  728. lines = notice.splitlines()
  729. for line in lines[1:]:
  730. lstrippedLine = line.lstrip()
  731. if lstrippedLine:
  732. indent = len(line) - len(lstrippedLine)
  733. minIndent = min(indent, minIndent)
  734. # Strip leading / trailing blank lines and also indentation.
  735. cleanLines = [lines[0].strip()]
  736. for line in lines[1:]:
  737. cleanLines.append(line[minIndent:].rstrip())
  738. # Clear completely blank lines from front and back...
  739. while cleanLines and not cleanLines[0]:
  740. del cleanLines[0]
  741. while cleanLines and not cleanLines[-1]:
  742. del cleanLines[-1]
  743. return '\n'.join(cleanLines)
  744. def _JoinName(self, parent_name, name):
  745. return os.path.join(parent_name, name)
  746. def _UnjoinName(self, parent_name, name):
  747. return os.path.relpath(name, parent_name)
  748. def _ParseProject(self, node, parent=None, **extra_proj_attrs):
  749. """
  750. reads a <project> element from the manifest file
  751. """
  752. name = self._reqatt(node, 'name')
  753. if parent:
  754. name = self._JoinName(parent.name, name)
  755. remote = self._get_remote(node)
  756. if remote is None:
  757. remote = self._default.remote
  758. if remote is None:
  759. raise ManifestParseError("no remote for project %s within %s" %
  760. (name, self.manifestFile))
  761. revisionExpr = node.getAttribute('revision') or remote.revision
  762. if not revisionExpr:
  763. revisionExpr = self._default.revisionExpr
  764. if not revisionExpr:
  765. raise ManifestParseError("no revision for project %s within %s" %
  766. (name, self.manifestFile))
  767. path = node.getAttribute('path')
  768. if not path:
  769. path = name
  770. if path.startswith('/'):
  771. raise ManifestParseError("project %s path cannot be absolute in %s" %
  772. (name, self.manifestFile))
  773. rebase = XmlBool(node, 'rebase', True)
  774. sync_c = XmlBool(node, 'sync-c', False)
  775. sync_s = XmlBool(node, 'sync-s', self._default.sync_s)
  776. sync_tags = XmlBool(node, 'sync-tags', self._default.sync_tags)
  777. clone_depth = XmlInt(node, 'clone-depth')
  778. if clone_depth is not None and clone_depth <= 0:
  779. raise ManifestParseError('%s: clone-depth must be greater than 0, not "%s"' %
  780. (self.manifestFile, clone_depth))
  781. dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
  782. upstream = node.getAttribute('upstream') or self._default.upstreamExpr
  783. groups = ''
  784. if node.hasAttribute('groups'):
  785. groups = node.getAttribute('groups')
  786. groups = self._ParseGroups(groups)
  787. if parent is None:
  788. relpath, worktree, gitdir, objdir, use_git_worktrees = \
  789. self.GetProjectPaths(name, path)
  790. else:
  791. use_git_worktrees = False
  792. relpath, worktree, gitdir, objdir = \
  793. self.GetSubprojectPaths(parent, name, path)
  794. default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
  795. groups.extend(set(default_groups).difference(groups))
  796. if self.IsMirror and node.hasAttribute('force-path'):
  797. if XmlBool(node, 'force-path', False):
  798. gitdir = os.path.join(self.topdir, '%s.git' % path)
  799. project = Project(manifest=self,
  800. name=name,
  801. remote=remote.ToRemoteSpec(name),
  802. gitdir=gitdir,
  803. objdir=objdir,
  804. worktree=worktree,
  805. relpath=relpath,
  806. revisionExpr=revisionExpr,
  807. revisionId=None,
  808. rebase=rebase,
  809. groups=groups,
  810. sync_c=sync_c,
  811. sync_s=sync_s,
  812. sync_tags=sync_tags,
  813. clone_depth=clone_depth,
  814. upstream=upstream,
  815. parent=parent,
  816. dest_branch=dest_branch,
  817. use_git_worktrees=use_git_worktrees,
  818. **extra_proj_attrs)
  819. for n in node.childNodes:
  820. if n.nodeName == 'copyfile':
  821. self._ParseCopyFile(project, n)
  822. if n.nodeName == 'linkfile':
  823. self._ParseLinkFile(project, n)
  824. if n.nodeName == 'annotation':
  825. self._ParseAnnotation(project, n)
  826. if n.nodeName == 'project':
  827. project.subprojects.append(self._ParseProject(n, parent=project))
  828. return project
  829. def GetProjectPaths(self, name, path):
  830. use_git_worktrees = False
  831. relpath = path
  832. if self.IsMirror:
  833. worktree = None
  834. gitdir = os.path.join(self.topdir, '%s.git' % name)
  835. objdir = gitdir
  836. else:
  837. worktree = os.path.join(self.topdir, path).replace('\\', '/')
  838. gitdir = os.path.join(self.repodir, 'projects', '%s.git' % path)
  839. # We allow people to mix git worktrees & non-git worktrees for now.
  840. # This allows for in situ migration of repo clients.
  841. if os.path.exists(gitdir) or not self.UseGitWorktrees:
  842. objdir = os.path.join(self.repodir, 'project-objects', '%s.git' % name)
  843. else:
  844. use_git_worktrees = True
  845. gitdir = os.path.join(self.repodir, 'worktrees', '%s.git' % name)
  846. objdir = gitdir
  847. return relpath, worktree, gitdir, objdir, use_git_worktrees
  848. def GetProjectsWithName(self, name):
  849. return self._projects.get(name, [])
  850. def GetSubprojectName(self, parent, submodule_path):
  851. return os.path.join(parent.name, submodule_path)
  852. def _JoinRelpath(self, parent_relpath, relpath):
  853. return os.path.join(parent_relpath, relpath)
  854. def _UnjoinRelpath(self, parent_relpath, relpath):
  855. return os.path.relpath(relpath, parent_relpath)
  856. def GetSubprojectPaths(self, parent, name, path):
  857. relpath = self._JoinRelpath(parent.relpath, path)
  858. gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
  859. objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
  860. if self.IsMirror:
  861. worktree = None
  862. else:
  863. worktree = os.path.join(parent.worktree, path).replace('\\', '/')
  864. return relpath, worktree, gitdir, objdir
  865. @staticmethod
  866. def _CheckLocalPath(path, symlink=False):
  867. """Verify |path| is reasonable for use in <copyfile> & <linkfile>."""
  868. if '~' in path:
  869. return '~ not allowed (due to 8.3 filenames on Windows filesystems)'
  870. # Some filesystems (like Apple's HFS+) try to normalize Unicode codepoints
  871. # which means there are alternative names for ".git". Reject paths with
  872. # these in it as there shouldn't be any reasonable need for them here.
  873. # The set of codepoints here was cribbed from jgit's implementation:
  874. # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
  875. BAD_CODEPOINTS = {
  876. u'\u200C', # ZERO WIDTH NON-JOINER
  877. u'\u200D', # ZERO WIDTH JOINER
  878. u'\u200E', # LEFT-TO-RIGHT MARK
  879. u'\u200F', # RIGHT-TO-LEFT MARK
  880. u'\u202A', # LEFT-TO-RIGHT EMBEDDING
  881. u'\u202B', # RIGHT-TO-LEFT EMBEDDING
  882. u'\u202C', # POP DIRECTIONAL FORMATTING
  883. u'\u202D', # LEFT-TO-RIGHT OVERRIDE
  884. u'\u202E', # RIGHT-TO-LEFT OVERRIDE
  885. u'\u206A', # INHIBIT SYMMETRIC SWAPPING
  886. u'\u206B', # ACTIVATE SYMMETRIC SWAPPING
  887. u'\u206C', # INHIBIT ARABIC FORM SHAPING
  888. u'\u206D', # ACTIVATE ARABIC FORM SHAPING
  889. u'\u206E', # NATIONAL DIGIT SHAPES
  890. u'\u206F', # NOMINAL DIGIT SHAPES
  891. u'\uFEFF', # ZERO WIDTH NO-BREAK SPACE
  892. }
  893. if BAD_CODEPOINTS & set(path):
  894. # This message is more expansive than reality, but should be fine.
  895. return 'Unicode combining characters not allowed'
  896. # Assume paths might be used on case-insensitive filesystems.
  897. path = path.lower()
  898. # Split up the path by its components. We can't use os.path.sep exclusively
  899. # as some platforms (like Windows) will convert / to \ and that bypasses all
  900. # our constructed logic here. Especially since manifest authors only use
  901. # / in their paths.
  902. resep = re.compile(r'[/%s]' % re.escape(os.path.sep))
  903. parts = resep.split(path)
  904. # Some people use src="." to create stable links to projects. Lets allow
  905. # that but reject all other uses of "." to keep things simple.
  906. if parts != ['.']:
  907. for part in set(parts):
  908. if part in {'.', '..', '.git'} or part.startswith('.repo'):
  909. return 'bad component: %s' % (part,)
  910. if not symlink and resep.match(path[-1]):
  911. return 'dirs not allowed'
  912. # NB: The two abspath checks here are to handle platforms with multiple
  913. # filesystem path styles (e.g. Windows).
  914. norm = os.path.normpath(path)
  915. if (norm == '..' or
  916. (len(norm) >= 3 and norm.startswith('..') and resep.match(norm[0])) or
  917. os.path.isabs(norm) or
  918. norm.startswith('/')):
  919. return 'path cannot be outside'
  920. @classmethod
  921. def _ValidateFilePaths(cls, element, src, dest):
  922. """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
  923. We verify the path independent of any filesystem state as we won't have a
  924. checkout available to compare to. i.e. This is for parsing validation
  925. purposes only.
  926. We'll do full/live sanity checking before we do the actual filesystem
  927. modifications in _CopyFile/_LinkFile/etc...
  928. """
  929. # |dest| is the file we write to or symlink we create.
  930. # It is relative to the top of the repo client checkout.
  931. msg = cls._CheckLocalPath(dest)
  932. if msg:
  933. raise ManifestInvalidPathError(
  934. '<%s> invalid "dest": %s: %s' % (element, dest, msg))
  935. # |src| is the file we read from or path we point to for symlinks.
  936. # It is relative to the top of the git project checkout.
  937. msg = cls._CheckLocalPath(src, symlink=element == 'linkfile')
  938. if msg:
  939. raise ManifestInvalidPathError(
  940. '<%s> invalid "src": %s: %s' % (element, src, msg))
  941. def _ParseCopyFile(self, project, node):
  942. src = self._reqatt(node, 'src')
  943. dest = self._reqatt(node, 'dest')
  944. if not self.IsMirror:
  945. # src is project relative;
  946. # dest is relative to the top of the tree.
  947. # We only validate paths if we actually plan to process them.
  948. self._ValidateFilePaths('copyfile', src, dest)
  949. project.AddCopyFile(src, dest, self.topdir)
  950. def _ParseLinkFile(self, project, node):
  951. src = self._reqatt(node, 'src')
  952. dest = self._reqatt(node, 'dest')
  953. if not self.IsMirror:
  954. # src is project relative;
  955. # dest is relative to the top of the tree.
  956. # We only validate paths if we actually plan to process them.
  957. self._ValidateFilePaths('linkfile', src, dest)
  958. project.AddLinkFile(src, dest, self.topdir)
  959. def _ParseAnnotation(self, project, node):
  960. name = self._reqatt(node, 'name')
  961. value = self._reqatt(node, 'value')
  962. try:
  963. keep = self._reqatt(node, 'keep').lower()
  964. except ManifestParseError:
  965. keep = "true"
  966. if keep != "true" and keep != "false":
  967. raise ManifestParseError('optional "keep" attribute must be '
  968. '"true" or "false"')
  969. project.AddAnnotation(name, value, keep)
  970. def _get_remote(self, node):
  971. name = node.getAttribute('remote')
  972. if not name:
  973. return None
  974. v = self._remotes.get(name)
  975. if not v:
  976. raise ManifestParseError("remote %s not defined in %s" %
  977. (name, self.manifestFile))
  978. return v
  979. def _reqatt(self, node, attname):
  980. """
  981. reads a required attribute from the node.
  982. """
  983. v = node.getAttribute(attname)
  984. if not v:
  985. raise ManifestParseError("no %s in <%s> within %s" %
  986. (attname, node.nodeName, self.manifestFile))
  987. return v
  988. def projectsDiff(self, manifest):
  989. """return the projects differences between two manifests.
  990. The diff will be from self to given manifest.
  991. """
  992. fromProjects = self.paths
  993. toProjects = manifest.paths
  994. fromKeys = sorted(fromProjects.keys())
  995. toKeys = sorted(toProjects.keys())
  996. diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
  997. for proj in fromKeys:
  998. if proj not in toKeys:
  999. diff['removed'].append(fromProjects[proj])
  1000. else:
  1001. fromProj = fromProjects[proj]
  1002. toProj = toProjects[proj]
  1003. try:
  1004. fromRevId = fromProj.GetCommitRevisionId()
  1005. toRevId = toProj.GetCommitRevisionId()
  1006. except ManifestInvalidRevisionError:
  1007. diff['unreachable'].append((fromProj, toProj))
  1008. else:
  1009. if fromRevId != toRevId:
  1010. diff['changed'].append((fromProj, toProj))
  1011. toKeys.remove(proj)
  1012. for proj in toKeys:
  1013. diff['added'].append(toProjects[proj])
  1014. return diff
  1015. class GitcManifest(XmlManifest):
  1016. def __init__(self, repodir, gitc_client_name):
  1017. """Initialize the GitcManifest object."""
  1018. super(GitcManifest, self).__init__(repodir)
  1019. self.isGitcClient = True
  1020. self.gitc_client_name = gitc_client_name
  1021. self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
  1022. gitc_client_name)
  1023. self.manifestFile = os.path.join(self.gitc_client_dir, '.manifest')
  1024. def _ParseProject(self, node, parent=None):
  1025. """Override _ParseProject and add support for GITC specific attributes."""
  1026. return super(GitcManifest, self)._ParseProject(
  1027. node, parent=parent, old_revision=node.getAttribute('old-revision'))
  1028. def _output_manifest_project_extras(self, p, e):
  1029. """Output GITC Specific Project attributes"""
  1030. if p.old_revision:
  1031. e.setAttribute('old-revision', str(p.old_revision))