manifest_xml.py 44 KB

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