manifest_xml.py 44 KB

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