manifest_xml.py 40 KB

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