manifest_xml.py 45 KB

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