manifest_xml.py 44 KB

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