manifest_xml.py 39 KB

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