manifest_xml.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  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, 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. else:
  336. revision = self.remotes[p.remote.orig_name].revision or d.revisionExpr
  337. if not revision or revision != p.revisionExpr:
  338. e.setAttribute('revision', p.revisionExpr)
  339. if (p.upstream and (p.upstream != p.revisionExpr or
  340. p.upstream != d.upstreamExpr)):
  341. e.setAttribute('upstream', p.upstream)
  342. if p.dest_branch and p.dest_branch != d.destBranchExpr:
  343. e.setAttribute('dest-branch', p.dest_branch)
  344. for c in p.copyfiles:
  345. ce = doc.createElement('copyfile')
  346. ce.setAttribute('src', c.src)
  347. ce.setAttribute('dest', c.dest)
  348. e.appendChild(ce)
  349. for l in p.linkfiles:
  350. le = doc.createElement('linkfile')
  351. le.setAttribute('src', l.src)
  352. le.setAttribute('dest', l.dest)
  353. e.appendChild(le)
  354. default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
  355. egroups = [g for g in p.groups if g not in default_groups]
  356. if egroups:
  357. e.setAttribute('groups', ','.join(egroups))
  358. for a in p.annotations:
  359. if a.keep == "true":
  360. ae = doc.createElement('annotation')
  361. ae.setAttribute('name', a.name)
  362. ae.setAttribute('value', a.value)
  363. e.appendChild(ae)
  364. if p.sync_c:
  365. e.setAttribute('sync-c', 'true')
  366. if p.sync_s:
  367. e.setAttribute('sync-s', 'true')
  368. if not p.sync_tags:
  369. e.setAttribute('sync-tags', 'false')
  370. if p.clone_depth:
  371. e.setAttribute('clone-depth', str(p.clone_depth))
  372. self._output_manifest_project_extras(p, e)
  373. if p.subprojects:
  374. subprojects = set(subp.name for subp in p.subprojects)
  375. output_projects(p, e, list(sorted(subprojects)))
  376. projects = set(p.name for p in self._paths.values() if not p.parent)
  377. output_projects(None, root, list(sorted(projects)))
  378. if self._repo_hooks_project:
  379. root.appendChild(doc.createTextNode(''))
  380. e = doc.createElement('repo-hooks')
  381. e.setAttribute('in-project', self._repo_hooks_project.name)
  382. e.setAttribute('enabled-list',
  383. ' '.join(self._repo_hooks_project.enabled_repo_hooks))
  384. root.appendChild(e)
  385. doc.writexml(fd, '', ' ', '\n', 'UTF-8')
  386. def _output_manifest_project_extras(self, p, e):
  387. """Manifests can modify e if they support extra project attributes."""
  388. pass
  389. @property
  390. def paths(self):
  391. self._Load()
  392. return self._paths
  393. @property
  394. def projects(self):
  395. self._Load()
  396. return list(self._paths.values())
  397. @property
  398. def remotes(self):
  399. self._Load()
  400. return self._remotes
  401. @property
  402. def default(self):
  403. self._Load()
  404. return self._default
  405. @property
  406. def repo_hooks_project(self):
  407. self._Load()
  408. return self._repo_hooks_project
  409. @property
  410. def notice(self):
  411. self._Load()
  412. return self._notice
  413. @property
  414. def manifest_server(self):
  415. self._Load()
  416. return self._manifest_server
  417. @property
  418. def CloneFilter(self):
  419. if self.manifestProject.config.GetBoolean('repo.partialclone'):
  420. return self.manifestProject.config.GetString('repo.clonefilter')
  421. return None
  422. @property
  423. def IsMirror(self):
  424. return self.manifestProject.config.GetBoolean('repo.mirror')
  425. @property
  426. def UseGitWorktrees(self):
  427. return self.manifestProject.config.GetBoolean('repo.worktree')
  428. @property
  429. def IsArchive(self):
  430. return self.manifestProject.config.GetBoolean('repo.archive')
  431. @property
  432. def HasSubmodules(self):
  433. return self.manifestProject.config.GetBoolean('repo.submodules')
  434. def _Unload(self):
  435. self._loaded = False
  436. self._projects = {}
  437. self._paths = {}
  438. self._remotes = {}
  439. self._default = None
  440. self._repo_hooks_project = None
  441. self._notice = None
  442. self.branch = None
  443. self._manifest_server = None
  444. def _Load(self):
  445. if not self._loaded:
  446. m = self.manifestProject
  447. b = m.GetBranch(m.CurrentBranch).merge
  448. if b is not None and b.startswith(R_HEADS):
  449. b = b[len(R_HEADS):]
  450. self.branch = b
  451. nodes = []
  452. nodes.append(self._ParseManifestXml(self.manifestFile,
  453. self.manifestProject.worktree))
  454. if self._load_local_manifests:
  455. local = os.path.join(self.repodir, LOCAL_MANIFEST_NAME)
  456. if os.path.exists(local):
  457. if not self.localManifestWarning:
  458. self.localManifestWarning = True
  459. print('warning: %s is deprecated; put local manifests '
  460. 'in `%s` instead' % (LOCAL_MANIFEST_NAME,
  461. os.path.join(self.repodir, LOCAL_MANIFESTS_DIR_NAME)),
  462. file=sys.stderr)
  463. nodes.append(self._ParseManifestXml(local, self.repodir))
  464. local_dir = os.path.abspath(os.path.join(self.repodir,
  465. LOCAL_MANIFESTS_DIR_NAME))
  466. try:
  467. for local_file in sorted(platform_utils.listdir(local_dir)):
  468. if local_file.endswith('.xml'):
  469. local = os.path.join(local_dir, local_file)
  470. nodes.append(self._ParseManifestXml(local, self.repodir))
  471. except OSError:
  472. pass
  473. try:
  474. self._ParseManifest(nodes)
  475. except ManifestParseError as e:
  476. # There was a problem parsing, unload ourselves in case they catch
  477. # this error and try again later, we will show the correct error
  478. self._Unload()
  479. raise e
  480. if self.IsMirror:
  481. self._AddMetaProjectMirror(self.repoProject)
  482. self._AddMetaProjectMirror(self.manifestProject)
  483. self._loaded = True
  484. def _ParseManifestXml(self, path, include_root):
  485. try:
  486. root = xml.dom.minidom.parse(path)
  487. except (OSError, xml.parsers.expat.ExpatError) as e:
  488. raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
  489. if not root or not root.childNodes:
  490. raise ManifestParseError("no root node in %s" % (path,))
  491. for manifest in root.childNodes:
  492. if manifest.nodeName == 'manifest':
  493. break
  494. else:
  495. raise ManifestParseError("no <manifest> in %s" % (path,))
  496. nodes = []
  497. for node in manifest.childNodes:
  498. if node.nodeName == 'include':
  499. name = self._reqatt(node, 'name')
  500. fp = os.path.join(include_root, name)
  501. if not os.path.isfile(fp):
  502. raise ManifestParseError("include %s doesn't exist or isn't a file"
  503. % (name,))
  504. try:
  505. nodes.extend(self._ParseManifestXml(fp, include_root))
  506. # should isolate this to the exact exception, but that's
  507. # tricky. actual parsing implementation may vary.
  508. except (KeyboardInterrupt, RuntimeError, SystemExit):
  509. raise
  510. except Exception as e:
  511. raise ManifestParseError(
  512. "failed parsing included manifest %s: %s" % (name, e))
  513. else:
  514. nodes.append(node)
  515. return nodes
  516. def _ParseManifest(self, node_list):
  517. for node in itertools.chain(*node_list):
  518. if node.nodeName == 'remote':
  519. remote = self._ParseRemote(node)
  520. if remote:
  521. if remote.name in self._remotes:
  522. if remote != self._remotes[remote.name]:
  523. raise ManifestParseError(
  524. 'remote %s already exists with different attributes' %
  525. (remote.name))
  526. else:
  527. self._remotes[remote.name] = remote
  528. for node in itertools.chain(*node_list):
  529. if node.nodeName == 'default':
  530. new_default = self._ParseDefault(node)
  531. if self._default is None:
  532. self._default = new_default
  533. elif new_default != self._default:
  534. raise ManifestParseError('duplicate default in %s' %
  535. (self.manifestFile))
  536. if self._default is None:
  537. self._default = _Default()
  538. for node in itertools.chain(*node_list):
  539. if node.nodeName == 'notice':
  540. if self._notice is not None:
  541. raise ManifestParseError(
  542. 'duplicate notice in %s' %
  543. (self.manifestFile))
  544. self._notice = self._ParseNotice(node)
  545. for node in itertools.chain(*node_list):
  546. if node.nodeName == 'manifest-server':
  547. url = self._reqatt(node, 'url')
  548. if self._manifest_server is not None:
  549. raise ManifestParseError(
  550. 'duplicate manifest-server in %s' %
  551. (self.manifestFile))
  552. self._manifest_server = url
  553. def recursively_add_projects(project):
  554. projects = self._projects.setdefault(project.name, [])
  555. if project.relpath is None:
  556. raise ManifestParseError(
  557. 'missing path for %s in %s' %
  558. (project.name, self.manifestFile))
  559. if project.relpath in self._paths:
  560. raise ManifestParseError(
  561. 'duplicate path %s in %s' %
  562. (project.relpath, self.manifestFile))
  563. self._paths[project.relpath] = project
  564. projects.append(project)
  565. for subproject in project.subprojects:
  566. recursively_add_projects(subproject)
  567. for node in itertools.chain(*node_list):
  568. if node.nodeName == 'project':
  569. project = self._ParseProject(node)
  570. recursively_add_projects(project)
  571. if node.nodeName == 'extend-project':
  572. name = self._reqatt(node, 'name')
  573. if name not in self._projects:
  574. raise ManifestParseError('extend-project element specifies non-existent '
  575. 'project: %s' % name)
  576. path = node.getAttribute('path')
  577. groups = node.getAttribute('groups')
  578. if groups:
  579. groups = self._ParseGroups(groups)
  580. revision = node.getAttribute('revision')
  581. remote = node.getAttribute('remote')
  582. if remote:
  583. remote = self._get_remote(node)
  584. for p in self._projects[name]:
  585. if path and p.relpath != path:
  586. continue
  587. if groups:
  588. p.groups.extend(groups)
  589. if revision:
  590. p.revisionExpr = revision
  591. if remote:
  592. p.remote = remote.ToRemoteSpec(name)
  593. if node.nodeName == 'repo-hooks':
  594. # Get the name of the project and the (space-separated) list of enabled.
  595. repo_hooks_project = self._reqatt(node, 'in-project')
  596. enabled_repo_hooks = self._reqatt(node, 'enabled-list').split()
  597. # Only one project can be the hooks project
  598. if self._repo_hooks_project is not None:
  599. raise ManifestParseError(
  600. 'duplicate repo-hooks in %s' %
  601. (self.manifestFile))
  602. # Store a reference to the Project.
  603. try:
  604. repo_hooks_projects = self._projects[repo_hooks_project]
  605. except KeyError:
  606. raise ManifestParseError(
  607. 'project %s not found for repo-hooks' %
  608. (repo_hooks_project))
  609. if len(repo_hooks_projects) != 1:
  610. raise ManifestParseError(
  611. 'internal error parsing repo-hooks in %s' %
  612. (self.manifestFile))
  613. self._repo_hooks_project = repo_hooks_projects[0]
  614. # Store the enabled hooks in the Project object.
  615. self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
  616. if node.nodeName == 'remove-project':
  617. name = self._reqatt(node, 'name')
  618. if name not in self._projects:
  619. raise ManifestParseError('remove-project element specifies non-existent '
  620. 'project: %s' % name)
  621. for p in self._projects[name]:
  622. del self._paths[p.relpath]
  623. del self._projects[name]
  624. # If the manifest removes the hooks project, treat it as if it deleted
  625. # the repo-hooks element too.
  626. if self._repo_hooks_project and (self._repo_hooks_project.name == name):
  627. self._repo_hooks_project = None
  628. def _AddMetaProjectMirror(self, m):
  629. name = None
  630. m_url = m.GetRemote(m.remote.name).url
  631. if m_url.endswith('/.git'):
  632. raise ManifestParseError('refusing to mirror %s' % m_url)
  633. if self._default and self._default.remote:
  634. url = self._default.remote.resolvedFetchUrl
  635. if not url.endswith('/'):
  636. url += '/'
  637. if m_url.startswith(url):
  638. remote = self._default.remote
  639. name = m_url[len(url):]
  640. if name is None:
  641. s = m_url.rindex('/') + 1
  642. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  643. remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
  644. name = m_url[s:]
  645. if name.endswith('.git'):
  646. name = name[:-4]
  647. if name not in self._projects:
  648. m.PreSync()
  649. gitdir = os.path.join(self.topdir, '%s.git' % name)
  650. project = Project(manifest=self,
  651. name=name,
  652. remote=remote.ToRemoteSpec(name),
  653. gitdir=gitdir,
  654. objdir=gitdir,
  655. worktree=None,
  656. relpath=name or None,
  657. revisionExpr=m.revisionExpr,
  658. revisionId=None)
  659. self._projects[project.name] = [project]
  660. self._paths[project.relpath] = project
  661. def _ParseRemote(self, node):
  662. """
  663. reads a <remote> element from the manifest file
  664. """
  665. name = self._reqatt(node, 'name')
  666. alias = node.getAttribute('alias')
  667. if alias == '':
  668. alias = None
  669. fetch = self._reqatt(node, 'fetch')
  670. pushUrl = node.getAttribute('pushurl')
  671. if pushUrl == '':
  672. pushUrl = None
  673. review = node.getAttribute('review')
  674. if review == '':
  675. review = None
  676. revision = node.getAttribute('revision')
  677. if revision == '':
  678. revision = None
  679. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  680. return _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
  681. def _ParseDefault(self, node):
  682. """
  683. reads a <default> element from the manifest file
  684. """
  685. d = _Default()
  686. d.remote = self._get_remote(node)
  687. d.revisionExpr = node.getAttribute('revision')
  688. if d.revisionExpr == '':
  689. d.revisionExpr = None
  690. d.destBranchExpr = node.getAttribute('dest-branch') or None
  691. d.upstreamExpr = node.getAttribute('upstream') or None
  692. d.sync_j = XmlInt(node, 'sync-j', 1)
  693. if d.sync_j <= 0:
  694. raise ManifestParseError('%s: sync-j must be greater than 0, not "%s"' %
  695. (self.manifestFile, d.sync_j))
  696. d.sync_c = XmlBool(node, 'sync-c', False)
  697. d.sync_s = XmlBool(node, 'sync-s', False)
  698. d.sync_tags = XmlBool(node, 'sync-tags', True)
  699. return d
  700. def _ParseNotice(self, node):
  701. """
  702. reads a <notice> element from the manifest file
  703. The <notice> element is distinct from other tags in the XML in that the
  704. data is conveyed between the start and end tag (it's not an empty-element
  705. tag).
  706. The white space (carriage returns, indentation) for the notice element is
  707. relevant and is parsed in a way that is based on how python docstrings work.
  708. In fact, the code is remarkably similar to here:
  709. http://www.python.org/dev/peps/pep-0257/
  710. """
  711. # Get the data out of the node...
  712. notice = node.childNodes[0].data
  713. # Figure out minimum indentation, skipping the first line (the same line
  714. # as the <notice> tag)...
  715. minIndent = sys.maxsize
  716. lines = notice.splitlines()
  717. for line in lines[1:]:
  718. lstrippedLine = line.lstrip()
  719. if lstrippedLine:
  720. indent = len(line) - len(lstrippedLine)
  721. minIndent = min(indent, minIndent)
  722. # Strip leading / trailing blank lines and also indentation.
  723. cleanLines = [lines[0].strip()]
  724. for line in lines[1:]:
  725. cleanLines.append(line[minIndent:].rstrip())
  726. # Clear completely blank lines from front and back...
  727. while cleanLines and not cleanLines[0]:
  728. del cleanLines[0]
  729. while cleanLines and not cleanLines[-1]:
  730. del cleanLines[-1]
  731. return '\n'.join(cleanLines)
  732. def _JoinName(self, parent_name, name):
  733. return os.path.join(parent_name, name)
  734. def _UnjoinName(self, parent_name, name):
  735. return os.path.relpath(name, parent_name)
  736. def _ParseProject(self, node, parent=None, **extra_proj_attrs):
  737. """
  738. reads a <project> element from the manifest file
  739. """
  740. name = self._reqatt(node, 'name')
  741. if parent:
  742. name = self._JoinName(parent.name, name)
  743. remote = self._get_remote(node)
  744. if remote is None:
  745. remote = self._default.remote
  746. if remote is None:
  747. raise ManifestParseError("no remote for project %s within %s" %
  748. (name, self.manifestFile))
  749. revisionExpr = node.getAttribute('revision') or remote.revision
  750. if not revisionExpr:
  751. revisionExpr = self._default.revisionExpr
  752. if not revisionExpr:
  753. raise ManifestParseError("no revision for project %s within %s" %
  754. (name, self.manifestFile))
  755. path = node.getAttribute('path')
  756. if not path:
  757. path = name
  758. if path.startswith('/'):
  759. raise ManifestParseError("project %s path cannot be absolute in %s" %
  760. (name, self.manifestFile))
  761. rebase = XmlBool(node, 'rebase', True)
  762. sync_c = XmlBool(node, 'sync-c', False)
  763. sync_s = XmlBool(node, 'sync-s', self._default.sync_s)
  764. sync_tags = XmlBool(node, 'sync-tags', self._default.sync_tags)
  765. clone_depth = XmlInt(node, 'clone-depth')
  766. if clone_depth is not None and clone_depth <= 0:
  767. raise ManifestParseError('%s: clone-depth must be greater than 0, not "%s"' %
  768. (self.manifestFile, clone_depth))
  769. dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
  770. upstream = node.getAttribute('upstream') or self._default.upstreamExpr
  771. groups = ''
  772. if node.hasAttribute('groups'):
  773. groups = node.getAttribute('groups')
  774. groups = self._ParseGroups(groups)
  775. if parent is None:
  776. relpath, worktree, gitdir, objdir, use_git_worktrees = \
  777. self.GetProjectPaths(name, path)
  778. else:
  779. use_git_worktrees = False
  780. relpath, worktree, gitdir, objdir = \
  781. self.GetSubprojectPaths(parent, name, path)
  782. default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
  783. groups.extend(set(default_groups).difference(groups))
  784. if self.IsMirror and node.hasAttribute('force-path'):
  785. if XmlBool(node, 'force-path', False):
  786. gitdir = os.path.join(self.topdir, '%s.git' % path)
  787. project = Project(manifest=self,
  788. name=name,
  789. remote=remote.ToRemoteSpec(name),
  790. gitdir=gitdir,
  791. objdir=objdir,
  792. worktree=worktree,
  793. relpath=relpath,
  794. revisionExpr=revisionExpr,
  795. revisionId=None,
  796. rebase=rebase,
  797. groups=groups,
  798. sync_c=sync_c,
  799. sync_s=sync_s,
  800. sync_tags=sync_tags,
  801. clone_depth=clone_depth,
  802. upstream=upstream,
  803. parent=parent,
  804. dest_branch=dest_branch,
  805. use_git_worktrees=use_git_worktrees,
  806. **extra_proj_attrs)
  807. for n in node.childNodes:
  808. if n.nodeName == 'copyfile':
  809. self._ParseCopyFile(project, n)
  810. if n.nodeName == 'linkfile':
  811. self._ParseLinkFile(project, n)
  812. if n.nodeName == 'annotation':
  813. self._ParseAnnotation(project, n)
  814. if n.nodeName == 'project':
  815. project.subprojects.append(self._ParseProject(n, parent=project))
  816. return project
  817. def GetProjectPaths(self, name, path):
  818. use_git_worktrees = False
  819. relpath = path
  820. if self.IsMirror:
  821. worktree = None
  822. gitdir = os.path.join(self.topdir, '%s.git' % name)
  823. objdir = gitdir
  824. else:
  825. worktree = os.path.join(self.topdir, path).replace('\\', '/')
  826. gitdir = os.path.join(self.repodir, 'projects', '%s.git' % path)
  827. # We allow people to mix git worktrees & non-git worktrees for now.
  828. # This allows for in situ migration of repo clients.
  829. if os.path.exists(gitdir) or not self.UseGitWorktrees:
  830. objdir = os.path.join(self.repodir, 'project-objects', '%s.git' % name)
  831. else:
  832. use_git_worktrees = True
  833. gitdir = os.path.join(self.repodir, 'worktrees', '%s.git' % name)
  834. objdir = gitdir
  835. return relpath, worktree, gitdir, objdir, use_git_worktrees
  836. def GetProjectsWithName(self, name):
  837. return self._projects.get(name, [])
  838. def GetSubprojectName(self, parent, submodule_path):
  839. return os.path.join(parent.name, submodule_path)
  840. def _JoinRelpath(self, parent_relpath, relpath):
  841. return os.path.join(parent_relpath, relpath)
  842. def _UnjoinRelpath(self, parent_relpath, relpath):
  843. return os.path.relpath(relpath, parent_relpath)
  844. def GetSubprojectPaths(self, parent, name, path):
  845. relpath = self._JoinRelpath(parent.relpath, path)
  846. gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
  847. objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
  848. if self.IsMirror:
  849. worktree = None
  850. else:
  851. worktree = os.path.join(parent.worktree, path).replace('\\', '/')
  852. return relpath, worktree, gitdir, objdir
  853. @staticmethod
  854. def _CheckLocalPath(path, symlink=False):
  855. """Verify |path| is reasonable for use in <copyfile> & <linkfile>."""
  856. if '~' in path:
  857. return '~ not allowed (due to 8.3 filenames on Windows filesystems)'
  858. # Some filesystems (like Apple's HFS+) try to normalize Unicode codepoints
  859. # which means there are alternative names for ".git". Reject paths with
  860. # these in it as there shouldn't be any reasonable need for them here.
  861. # The set of codepoints here was cribbed from jgit's implementation:
  862. # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
  863. BAD_CODEPOINTS = {
  864. u'\u200C', # ZERO WIDTH NON-JOINER
  865. u'\u200D', # ZERO WIDTH JOINER
  866. u'\u200E', # LEFT-TO-RIGHT MARK
  867. u'\u200F', # RIGHT-TO-LEFT MARK
  868. u'\u202A', # LEFT-TO-RIGHT EMBEDDING
  869. u'\u202B', # RIGHT-TO-LEFT EMBEDDING
  870. u'\u202C', # POP DIRECTIONAL FORMATTING
  871. u'\u202D', # LEFT-TO-RIGHT OVERRIDE
  872. u'\u202E', # RIGHT-TO-LEFT OVERRIDE
  873. u'\u206A', # INHIBIT SYMMETRIC SWAPPING
  874. u'\u206B', # ACTIVATE SYMMETRIC SWAPPING
  875. u'\u206C', # INHIBIT ARABIC FORM SHAPING
  876. u'\u206D', # ACTIVATE ARABIC FORM SHAPING
  877. u'\u206E', # NATIONAL DIGIT SHAPES
  878. u'\u206F', # NOMINAL DIGIT SHAPES
  879. u'\uFEFF', # ZERO WIDTH NO-BREAK SPACE
  880. }
  881. if BAD_CODEPOINTS & set(path):
  882. # This message is more expansive than reality, but should be fine.
  883. return 'Unicode combining characters not allowed'
  884. # Assume paths might be used on case-insensitive filesystems.
  885. path = path.lower()
  886. # Split up the path by its components. We can't use os.path.sep exclusively
  887. # as some platforms (like Windows) will convert / to \ and that bypasses all
  888. # our constructed logic here. Especially since manifest authors only use
  889. # / in their paths.
  890. resep = re.compile(r'[/%s]' % re.escape(os.path.sep))
  891. parts = resep.split(path)
  892. # Some people use src="." to create stable links to projects. Lets allow
  893. # that but reject all other uses of "." to keep things simple.
  894. if parts != ['.']:
  895. for part in set(parts):
  896. if part in {'.', '..', '.git'} or part.startswith('.repo'):
  897. return 'bad component: %s' % (part,)
  898. if not symlink and resep.match(path[-1]):
  899. return 'dirs not allowed'
  900. # NB: The two abspath checks here are to handle platforms with multiple
  901. # filesystem path styles (e.g. Windows).
  902. norm = os.path.normpath(path)
  903. if (norm == '..' or
  904. (len(norm) >= 3 and norm.startswith('..') and resep.match(norm[0])) or
  905. os.path.isabs(norm) or
  906. norm.startswith('/')):
  907. return 'path cannot be outside'
  908. @classmethod
  909. def _ValidateFilePaths(cls, element, src, dest):
  910. """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
  911. We verify the path independent of any filesystem state as we won't have a
  912. checkout available to compare to. i.e. This is for parsing validation
  913. purposes only.
  914. We'll do full/live sanity checking before we do the actual filesystem
  915. modifications in _CopyFile/_LinkFile/etc...
  916. """
  917. # |dest| is the file we write to or symlink we create.
  918. # It is relative to the top of the repo client checkout.
  919. msg = cls._CheckLocalPath(dest)
  920. if msg:
  921. raise ManifestInvalidPathError(
  922. '<%s> invalid "dest": %s: %s' % (element, dest, msg))
  923. # |src| is the file we read from or path we point to for symlinks.
  924. # It is relative to the top of the git project checkout.
  925. msg = cls._CheckLocalPath(src, symlink=element == 'linkfile')
  926. if msg:
  927. raise ManifestInvalidPathError(
  928. '<%s> invalid "src": %s: %s' % (element, src, msg))
  929. def _ParseCopyFile(self, project, node):
  930. src = self._reqatt(node, 'src')
  931. dest = self._reqatt(node, 'dest')
  932. if not self.IsMirror:
  933. # src is project relative;
  934. # dest is relative to the top of the tree.
  935. # We only validate paths if we actually plan to process them.
  936. self._ValidateFilePaths('copyfile', src, dest)
  937. project.AddCopyFile(src, dest, self.topdir)
  938. def _ParseLinkFile(self, project, node):
  939. src = self._reqatt(node, 'src')
  940. dest = self._reqatt(node, 'dest')
  941. if not self.IsMirror:
  942. # src is project relative;
  943. # dest is relative to the top of the tree.
  944. # We only validate paths if we actually plan to process them.
  945. self._ValidateFilePaths('linkfile', src, dest)
  946. project.AddLinkFile(src, dest, self.topdir)
  947. def _ParseAnnotation(self, project, node):
  948. name = self._reqatt(node, 'name')
  949. value = self._reqatt(node, 'value')
  950. try:
  951. keep = self._reqatt(node, 'keep').lower()
  952. except ManifestParseError:
  953. keep = "true"
  954. if keep != "true" and keep != "false":
  955. raise ManifestParseError('optional "keep" attribute must be '
  956. '"true" or "false"')
  957. project.AddAnnotation(name, value, keep)
  958. def _get_remote(self, node):
  959. name = node.getAttribute('remote')
  960. if not name:
  961. return None
  962. v = self._remotes.get(name)
  963. if not v:
  964. raise ManifestParseError("remote %s not defined in %s" %
  965. (name, self.manifestFile))
  966. return v
  967. def _reqatt(self, node, attname):
  968. """
  969. reads a required attribute from the node.
  970. """
  971. v = node.getAttribute(attname)
  972. if not v:
  973. raise ManifestParseError("no %s in <%s> within %s" %
  974. (attname, node.nodeName, self.manifestFile))
  975. return v
  976. def projectsDiff(self, manifest):
  977. """return the projects differences between two manifests.
  978. The diff will be from self to given manifest.
  979. """
  980. fromProjects = self.paths
  981. toProjects = manifest.paths
  982. fromKeys = sorted(fromProjects.keys())
  983. toKeys = sorted(toProjects.keys())
  984. diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
  985. for proj in fromKeys:
  986. if proj not in toKeys:
  987. diff['removed'].append(fromProjects[proj])
  988. else:
  989. fromProj = fromProjects[proj]
  990. toProj = toProjects[proj]
  991. try:
  992. fromRevId = fromProj.GetCommitRevisionId()
  993. toRevId = toProj.GetCommitRevisionId()
  994. except ManifestInvalidRevisionError:
  995. diff['unreachable'].append((fromProj, toProj))
  996. else:
  997. if fromRevId != toRevId:
  998. diff['changed'].append((fromProj, toProj))
  999. toKeys.remove(proj)
  1000. for proj in toKeys:
  1001. diff['added'].append(toProjects[proj])
  1002. return diff
  1003. class GitcManifest(XmlManifest):
  1004. def __init__(self, repodir, gitc_client_name):
  1005. """Initialize the GitcManifest object."""
  1006. super(GitcManifest, self).__init__(repodir)
  1007. self.isGitcClient = True
  1008. self.gitc_client_name = gitc_client_name
  1009. self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
  1010. gitc_client_name)
  1011. self.manifestFile = os.path.join(self.gitc_client_dir, '.manifest')
  1012. def _ParseProject(self, node, parent=None):
  1013. """Override _ParseProject and add support for GITC specific attributes."""
  1014. return super(GitcManifest, self)._ParseProject(
  1015. node, parent=parent, old_revision=node.getAttribute('old-revision'))
  1016. def _output_manifest_project_extras(self, p, e):
  1017. """Output GITC Specific Project attributes"""
  1018. if p.old_revision:
  1019. e.setAttribute('old-revision', str(p.old_revision))