manifest_xml.py 37 KB

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