manifest_xml.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. #
  2. # Copyright (C) 2008 The Android Open Source Project
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from __future__ import print_function
  16. import itertools
  17. import os
  18. import re
  19. import sys
  20. import xml.dom.minidom
  21. from pyversion import is_python3
  22. if is_python3():
  23. import urllib.parse
  24. else:
  25. import imp
  26. import urlparse
  27. urllib = imp.new_module('urllib')
  28. urllib.parse = urlparse
  29. from git_config import GitConfig
  30. from git_refs import R_HEADS, HEAD
  31. from project import RemoteSpec, Project, MetaProject
  32. from error import ManifestParseError, ManifestInvalidRevisionError
  33. MANIFEST_FILE_NAME = 'manifest.xml'
  34. LOCAL_MANIFEST_NAME = 'local_manifest.xml'
  35. LOCAL_MANIFESTS_DIR_NAME = 'local_manifests'
  36. urllib.parse.uses_relative.extend(['ssh', 'git'])
  37. urllib.parse.uses_netloc.extend(['ssh', 'git'])
  38. class _Default(object):
  39. """Project defaults within the manifest."""
  40. revisionExpr = None
  41. destBranchExpr = None
  42. remote = None
  43. sync_j = 1
  44. sync_c = False
  45. sync_s = False
  46. def __eq__(self, other):
  47. return self.__dict__ == other.__dict__
  48. def __ne__(self, other):
  49. return self.__dict__ != other.__dict__
  50. class _XmlRemote(object):
  51. def __init__(self,
  52. name,
  53. alias=None,
  54. fetch=None,
  55. manifestUrl=None,
  56. review=None,
  57. revision=None):
  58. self.name = name
  59. self.fetchUrl = fetch
  60. self.manifestUrl = manifestUrl
  61. self.remoteAlias = alias
  62. self.reviewUrl = review
  63. self.revision = revision
  64. self.resolvedFetchUrl = self._resolveFetchUrl()
  65. def __eq__(self, other):
  66. return self.__dict__ == other.__dict__
  67. def __ne__(self, other):
  68. return self.__dict__ != other.__dict__
  69. def _resolveFetchUrl(self):
  70. url = self.fetchUrl.rstrip('/')
  71. manifestUrl = self.manifestUrl.rstrip('/')
  72. # urljoin will gets confused over quite a few things. The ones we care
  73. # about here are:
  74. # * no scheme in the base url, like <hostname:port>
  75. # * persistent-https://
  76. # We handle this by replacing these with obscure protocols
  77. # and then replacing them with the original when we are done.
  78. # gopher -> <none>
  79. # wais -> persistent-https
  80. if manifestUrl.find(':') != manifestUrl.find('/') - 1:
  81. manifestUrl = 'gopher://' + manifestUrl
  82. manifestUrl = re.sub(r'^persistent-https://', 'wais://', manifestUrl)
  83. url = urllib.parse.urljoin(manifestUrl, url)
  84. url = re.sub(r'^gopher://', '', url)
  85. url = re.sub(r'^wais://', 'persistent-https://', url)
  86. return url
  87. def ToRemoteSpec(self, projectName):
  88. url = self.resolvedFetchUrl.rstrip('/') + '/' + projectName
  89. remoteName = self.name
  90. if self.remoteAlias:
  91. remoteName = self.remoteAlias
  92. return RemoteSpec(remoteName, url, self.reviewUrl)
  93. class XmlManifest(object):
  94. """manages the repo configuration file"""
  95. def __init__(self, repodir):
  96. self.repodir = os.path.abspath(repodir)
  97. self.topdir = os.path.dirname(self.repodir)
  98. self.manifestFile = os.path.join(self.repodir, MANIFEST_FILE_NAME)
  99. self.globalConfig = GitConfig.ForUser()
  100. self.localManifestWarning = False
  101. self.repoProject = MetaProject(self, 'repo',
  102. gitdir = os.path.join(repodir, 'repo/.git'),
  103. worktree = os.path.join(repodir, 'repo'))
  104. self.manifestProject = MetaProject(self, 'manifests',
  105. gitdir = os.path.join(repodir, 'manifests.git'),
  106. worktree = os.path.join(repodir, 'manifests'))
  107. self._Unload()
  108. def Override(self, name):
  109. """Use a different manifest, just for the current instantiation.
  110. """
  111. path = os.path.join(self.manifestProject.worktree, name)
  112. if not os.path.isfile(path):
  113. raise ManifestParseError('manifest %s not found' % name)
  114. old = self.manifestFile
  115. try:
  116. self.manifestFile = path
  117. self._Unload()
  118. self._Load()
  119. finally:
  120. self.manifestFile = old
  121. def Link(self, name):
  122. """Update the repo metadata to use a different manifest.
  123. """
  124. self.Override(name)
  125. try:
  126. if os.path.lexists(self.manifestFile):
  127. os.remove(self.manifestFile)
  128. os.symlink('manifests/%s' % name, self.manifestFile)
  129. except OSError as e:
  130. raise ManifestParseError('cannot link manifest %s: %s' % (name, str(e)))
  131. def _RemoteToXml(self, r, doc, root):
  132. e = doc.createElement('remote')
  133. root.appendChild(e)
  134. e.setAttribute('name', r.name)
  135. e.setAttribute('fetch', r.fetchUrl)
  136. if r.remoteAlias is not None:
  137. e.setAttribute('alias', r.remoteAlias)
  138. if r.reviewUrl is not None:
  139. e.setAttribute('review', r.reviewUrl)
  140. if r.revision is not None:
  141. e.setAttribute('revision', r.revision)
  142. def Save(self, fd, peg_rev=False, peg_rev_upstream=True):
  143. """Write the current manifest out to the given file descriptor.
  144. """
  145. mp = self.manifestProject
  146. groups = mp.config.GetString('manifest.groups')
  147. if groups:
  148. groups = [x for x in re.split(r'[,\s]+', groups) if x]
  149. doc = xml.dom.minidom.Document()
  150. root = doc.createElement('manifest')
  151. doc.appendChild(root)
  152. # Save out the notice. There's a little bit of work here to give it the
  153. # right whitespace, which assumes that the notice is automatically indented
  154. # by 4 by minidom.
  155. if self.notice:
  156. notice_element = root.appendChild(doc.createElement('notice'))
  157. notice_lines = self.notice.splitlines()
  158. indented_notice = ('\n'.join(" "*4 + line for line in notice_lines))[4:]
  159. notice_element.appendChild(doc.createTextNode(indented_notice))
  160. d = self.default
  161. for r in sorted(self.remotes):
  162. self._RemoteToXml(self.remotes[r], doc, root)
  163. if self.remotes:
  164. root.appendChild(doc.createTextNode(''))
  165. have_default = False
  166. e = doc.createElement('default')
  167. if d.remote:
  168. have_default = True
  169. e.setAttribute('remote', d.remote.name)
  170. if d.revisionExpr:
  171. have_default = True
  172. e.setAttribute('revision', d.revisionExpr)
  173. if d.sync_j > 1:
  174. have_default = True
  175. e.setAttribute('sync-j', '%d' % d.sync_j)
  176. if d.sync_c:
  177. have_default = True
  178. e.setAttribute('sync-c', 'true')
  179. if d.sync_s:
  180. have_default = True
  181. e.setAttribute('sync-s', 'true')
  182. if have_default:
  183. root.appendChild(e)
  184. root.appendChild(doc.createTextNode(''))
  185. if self._manifest_server:
  186. e = doc.createElement('manifest-server')
  187. e.setAttribute('url', self._manifest_server)
  188. root.appendChild(e)
  189. root.appendChild(doc.createTextNode(''))
  190. def output_projects(parent, parent_node, projects):
  191. for project_name in projects:
  192. for project in self._projects[project_name]:
  193. output_project(parent, parent_node, project)
  194. def output_project(parent, parent_node, p):
  195. if not p.MatchesGroups(groups):
  196. return
  197. name = p.name
  198. relpath = p.relpath
  199. if parent:
  200. name = self._UnjoinName(parent.name, name)
  201. relpath = self._UnjoinRelpath(parent.relpath, relpath)
  202. e = doc.createElement('project')
  203. parent_node.appendChild(e)
  204. e.setAttribute('name', name)
  205. if relpath != name:
  206. e.setAttribute('path', relpath)
  207. remoteName = None
  208. if d.remote:
  209. remoteName = d.remote.remoteAlias or d.remote.name
  210. if not d.remote or p.remote.name != remoteName:
  211. remoteName = p.remote.name
  212. e.setAttribute('remote', remoteName)
  213. if peg_rev:
  214. if self.IsMirror:
  215. value = p.bare_git.rev_parse(p.revisionExpr + '^0')
  216. else:
  217. value = p.work_git.rev_parse(HEAD + '^0')
  218. e.setAttribute('revision', value)
  219. if peg_rev_upstream and value != p.revisionExpr:
  220. # Only save the origin if the origin is not a sha1, and the default
  221. # isn't our value, and the if the default doesn't already have that
  222. # covered.
  223. e.setAttribute('upstream', p.revisionExpr)
  224. else:
  225. revision = self.remotes[remoteName].revision or d.revisionExpr
  226. if not revision or revision != p.revisionExpr:
  227. e.setAttribute('revision', p.revisionExpr)
  228. if p.upstream and p.upstream != p.revisionExpr:
  229. e.setAttribute('upstream', p.upstream)
  230. for c in p.copyfiles:
  231. ce = doc.createElement('copyfile')
  232. ce.setAttribute('src', c.src)
  233. ce.setAttribute('dest', c.dest)
  234. e.appendChild(ce)
  235. for l in p.linkfiles:
  236. le = doc.createElement('linkfile')
  237. le.setAttribute('src', l.src)
  238. le.setAttribute('dest', l.dest)
  239. e.appendChild(le)
  240. default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
  241. egroups = [g for g in p.groups if g not in default_groups]
  242. if egroups:
  243. e.setAttribute('groups', ','.join(egroups))
  244. for a in p.annotations:
  245. if a.keep == "true":
  246. ae = doc.createElement('annotation')
  247. ae.setAttribute('name', a.name)
  248. ae.setAttribute('value', a.value)
  249. e.appendChild(ae)
  250. if p.sync_c:
  251. e.setAttribute('sync-c', 'true')
  252. if p.sync_s:
  253. e.setAttribute('sync-s', 'true')
  254. if p.subprojects:
  255. subprojects = set(subp.name for subp in p.subprojects)
  256. output_projects(p, e, list(sorted(subprojects)))
  257. projects = set(p.name for p in self._paths.values() if not p.parent)
  258. output_projects(None, root, list(sorted(projects)))
  259. if self._repo_hooks_project:
  260. root.appendChild(doc.createTextNode(''))
  261. e = doc.createElement('repo-hooks')
  262. e.setAttribute('in-project', self._repo_hooks_project.name)
  263. e.setAttribute('enabled-list',
  264. ' '.join(self._repo_hooks_project.enabled_repo_hooks))
  265. root.appendChild(e)
  266. doc.writexml(fd, '', ' ', '\n', 'UTF-8')
  267. @property
  268. def paths(self):
  269. self._Load()
  270. return self._paths
  271. @property
  272. def projects(self):
  273. self._Load()
  274. return list(self._paths.values())
  275. @property
  276. def remotes(self):
  277. self._Load()
  278. return self._remotes
  279. @property
  280. def default(self):
  281. self._Load()
  282. return self._default
  283. @property
  284. def repo_hooks_project(self):
  285. self._Load()
  286. return self._repo_hooks_project
  287. @property
  288. def notice(self):
  289. self._Load()
  290. return self._notice
  291. @property
  292. def manifest_server(self):
  293. self._Load()
  294. return self._manifest_server
  295. @property
  296. def IsMirror(self):
  297. return self.manifestProject.config.GetBoolean('repo.mirror')
  298. @property
  299. def IsArchive(self):
  300. return self.manifestProject.config.GetBoolean('repo.archive')
  301. def _Unload(self):
  302. self._loaded = False
  303. self._projects = {}
  304. self._paths = {}
  305. self._remotes = {}
  306. self._default = None
  307. self._repo_hooks_project = None
  308. self._notice = None
  309. self.branch = None
  310. self._manifest_server = None
  311. def _Load(self):
  312. if not self._loaded:
  313. m = self.manifestProject
  314. b = m.GetBranch(m.CurrentBranch).merge
  315. if b is not None and b.startswith(R_HEADS):
  316. b = b[len(R_HEADS):]
  317. self.branch = b
  318. nodes = []
  319. nodes.append(self._ParseManifestXml(self.manifestFile,
  320. self.manifestProject.worktree))
  321. local = os.path.join(self.repodir, LOCAL_MANIFEST_NAME)
  322. if os.path.exists(local):
  323. if not self.localManifestWarning:
  324. self.localManifestWarning = True
  325. print('warning: %s is deprecated; put local manifests in `%s` instead'
  326. % (LOCAL_MANIFEST_NAME, os.path.join(self.repodir, LOCAL_MANIFESTS_DIR_NAME)),
  327. file=sys.stderr)
  328. nodes.append(self._ParseManifestXml(local, self.repodir))
  329. local_dir = os.path.abspath(os.path.join(self.repodir, LOCAL_MANIFESTS_DIR_NAME))
  330. try:
  331. for local_file in sorted(os.listdir(local_dir)):
  332. if local_file.endswith('.xml'):
  333. local = os.path.join(local_dir, local_file)
  334. nodes.append(self._ParseManifestXml(local, self.repodir))
  335. except OSError:
  336. pass
  337. try:
  338. self._ParseManifest(nodes)
  339. except ManifestParseError as e:
  340. # There was a problem parsing, unload ourselves in case they catch
  341. # this error and try again later, we will show the correct error
  342. self._Unload()
  343. raise e
  344. if self.IsMirror:
  345. self._AddMetaProjectMirror(self.repoProject)
  346. self._AddMetaProjectMirror(self.manifestProject)
  347. self._loaded = True
  348. def _ParseManifestXml(self, path, include_root):
  349. try:
  350. root = xml.dom.minidom.parse(path)
  351. except (OSError, xml.parsers.expat.ExpatError) as e:
  352. raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
  353. if not root or not root.childNodes:
  354. raise ManifestParseError("no root node in %s" % (path,))
  355. for manifest in root.childNodes:
  356. if manifest.nodeName == 'manifest':
  357. break
  358. else:
  359. raise ManifestParseError("no <manifest> in %s" % (path,))
  360. nodes = []
  361. for node in manifest.childNodes: # pylint:disable=W0631
  362. # We only get here if manifest is initialised
  363. if node.nodeName == 'include':
  364. name = self._reqatt(node, 'name')
  365. fp = os.path.join(include_root, name)
  366. if not os.path.isfile(fp):
  367. raise ManifestParseError("include %s doesn't exist or isn't a file"
  368. % (name,))
  369. try:
  370. nodes.extend(self._ParseManifestXml(fp, include_root))
  371. # should isolate this to the exact exception, but that's
  372. # tricky. actual parsing implementation may vary.
  373. except (KeyboardInterrupt, RuntimeError, SystemExit):
  374. raise
  375. except Exception as e:
  376. raise ManifestParseError(
  377. "failed parsing included manifest %s: %s", (name, e))
  378. else:
  379. nodes.append(node)
  380. return nodes
  381. def _ParseManifest(self, node_list):
  382. for node in itertools.chain(*node_list):
  383. if node.nodeName == 'remote':
  384. remote = self._ParseRemote(node)
  385. if remote:
  386. if remote.name in self._remotes:
  387. if remote != self._remotes[remote.name]:
  388. raise ManifestParseError(
  389. 'remote %s already exists with different attributes' %
  390. (remote.name))
  391. else:
  392. self._remotes[remote.name] = remote
  393. for node in itertools.chain(*node_list):
  394. if node.nodeName == 'default':
  395. new_default = self._ParseDefault(node)
  396. if self._default is None:
  397. self._default = new_default
  398. elif new_default != self._default:
  399. raise ManifestParseError('duplicate default in %s' %
  400. (self.manifestFile))
  401. if self._default is None:
  402. self._default = _Default()
  403. for node in itertools.chain(*node_list):
  404. if node.nodeName == 'notice':
  405. if self._notice is not None:
  406. raise ManifestParseError(
  407. 'duplicate notice in %s' %
  408. (self.manifestFile))
  409. self._notice = self._ParseNotice(node)
  410. for node in itertools.chain(*node_list):
  411. if node.nodeName == 'manifest-server':
  412. url = self._reqatt(node, 'url')
  413. if self._manifest_server is not None:
  414. raise ManifestParseError(
  415. 'duplicate manifest-server in %s' %
  416. (self.manifestFile))
  417. self._manifest_server = url
  418. def recursively_add_projects(project):
  419. projects = self._projects.setdefault(project.name, [])
  420. if project.relpath is None:
  421. raise ManifestParseError(
  422. 'missing path for %s in %s' %
  423. (project.name, self.manifestFile))
  424. if project.relpath in self._paths:
  425. raise ManifestParseError(
  426. 'duplicate path %s in %s' %
  427. (project.relpath, self.manifestFile))
  428. self._paths[project.relpath] = project
  429. projects.append(project)
  430. for subproject in project.subprojects:
  431. recursively_add_projects(subproject)
  432. for node in itertools.chain(*node_list):
  433. if node.nodeName == 'project':
  434. project = self._ParseProject(node)
  435. recursively_add_projects(project)
  436. if node.nodeName == 'repo-hooks':
  437. # Get the name of the project and the (space-separated) list of enabled.
  438. repo_hooks_project = self._reqatt(node, 'in-project')
  439. enabled_repo_hooks = self._reqatt(node, 'enabled-list').split()
  440. # Only one project can be the hooks project
  441. if self._repo_hooks_project is not None:
  442. raise ManifestParseError(
  443. 'duplicate repo-hooks in %s' %
  444. (self.manifestFile))
  445. # Store a reference to the Project.
  446. try:
  447. repo_hooks_projects = self._projects[repo_hooks_project]
  448. except KeyError:
  449. raise ManifestParseError(
  450. 'project %s not found for repo-hooks' %
  451. (repo_hooks_project))
  452. if len(repo_hooks_projects) != 1:
  453. raise ManifestParseError(
  454. 'internal error parsing repo-hooks in %s' %
  455. (self.manifestFile))
  456. self._repo_hooks_project = repo_hooks_projects[0]
  457. # Store the enabled hooks in the Project object.
  458. self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
  459. if node.nodeName == 'remove-project':
  460. name = self._reqatt(node, 'name')
  461. if name not in self._projects:
  462. raise ManifestParseError('remove-project element specifies non-existent '
  463. 'project: %s' % name)
  464. for p in self._projects[name]:
  465. del self._paths[p.relpath]
  466. del self._projects[name]
  467. # If the manifest removes the hooks project, treat it as if it deleted
  468. # the repo-hooks element too.
  469. if self._repo_hooks_project and (self._repo_hooks_project.name == name):
  470. self._repo_hooks_project = None
  471. def _AddMetaProjectMirror(self, m):
  472. name = None
  473. m_url = m.GetRemote(m.remote.name).url
  474. if m_url.endswith('/.git'):
  475. raise ManifestParseError('refusing to mirror %s' % m_url)
  476. if self._default and self._default.remote:
  477. url = self._default.remote.resolvedFetchUrl
  478. if not url.endswith('/'):
  479. url += '/'
  480. if m_url.startswith(url):
  481. remote = self._default.remote
  482. name = m_url[len(url):]
  483. if name is None:
  484. s = m_url.rindex('/') + 1
  485. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  486. remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
  487. name = m_url[s:]
  488. if name.endswith('.git'):
  489. name = name[:-4]
  490. if name not in self._projects:
  491. m.PreSync()
  492. gitdir = os.path.join(self.topdir, '%s.git' % name)
  493. project = Project(manifest = self,
  494. name = name,
  495. remote = remote.ToRemoteSpec(name),
  496. gitdir = gitdir,
  497. objdir = gitdir,
  498. worktree = None,
  499. relpath = name or None,
  500. revisionExpr = m.revisionExpr,
  501. revisionId = None)
  502. self._projects[project.name] = [project]
  503. self._paths[project.relpath] = project
  504. def _ParseRemote(self, node):
  505. """
  506. reads a <remote> element from the manifest file
  507. """
  508. name = self._reqatt(node, 'name')
  509. alias = node.getAttribute('alias')
  510. if alias == '':
  511. alias = None
  512. fetch = self._reqatt(node, 'fetch')
  513. review = node.getAttribute('review')
  514. if review == '':
  515. review = None
  516. revision = node.getAttribute('revision')
  517. if revision == '':
  518. revision = None
  519. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  520. return _XmlRemote(name, alias, fetch, manifestUrl, review, revision)
  521. def _ParseDefault(self, node):
  522. """
  523. reads a <default> element from the manifest file
  524. """
  525. d = _Default()
  526. d.remote = self._get_remote(node)
  527. d.revisionExpr = node.getAttribute('revision')
  528. if d.revisionExpr == '':
  529. d.revisionExpr = None
  530. d.destBranchExpr = node.getAttribute('dest-branch') or None
  531. sync_j = node.getAttribute('sync-j')
  532. if sync_j == '' or sync_j is None:
  533. d.sync_j = 1
  534. else:
  535. d.sync_j = int(sync_j)
  536. sync_c = node.getAttribute('sync-c')
  537. if not sync_c:
  538. d.sync_c = False
  539. else:
  540. d.sync_c = sync_c.lower() in ("yes", "true", "1")
  541. sync_s = node.getAttribute('sync-s')
  542. if not sync_s:
  543. d.sync_s = False
  544. else:
  545. d.sync_s = sync_s.lower() in ("yes", "true", "1")
  546. return d
  547. def _ParseNotice(self, node):
  548. """
  549. reads a <notice> element from the manifest file
  550. The <notice> element is distinct from other tags in the XML in that the
  551. data is conveyed between the start and end tag (it's not an empty-element
  552. tag).
  553. The white space (carriage returns, indentation) for the notice element is
  554. relevant and is parsed in a way that is based on how python docstrings work.
  555. In fact, the code is remarkably similar to here:
  556. http://www.python.org/dev/peps/pep-0257/
  557. """
  558. # Get the data out of the node...
  559. notice = node.childNodes[0].data
  560. # Figure out minimum indentation, skipping the first line (the same line
  561. # as the <notice> tag)...
  562. minIndent = sys.maxsize
  563. lines = notice.splitlines()
  564. for line in lines[1:]:
  565. lstrippedLine = line.lstrip()
  566. if lstrippedLine:
  567. indent = len(line) - len(lstrippedLine)
  568. minIndent = min(indent, minIndent)
  569. # Strip leading / trailing blank lines and also indentation.
  570. cleanLines = [lines[0].strip()]
  571. for line in lines[1:]:
  572. cleanLines.append(line[minIndent:].rstrip())
  573. # Clear completely blank lines from front and back...
  574. while cleanLines and not cleanLines[0]:
  575. del cleanLines[0]
  576. while cleanLines and not cleanLines[-1]:
  577. del cleanLines[-1]
  578. return '\n'.join(cleanLines)
  579. def _JoinName(self, parent_name, name):
  580. return os.path.join(parent_name, name)
  581. def _UnjoinName(self, parent_name, name):
  582. return os.path.relpath(name, parent_name)
  583. def _ParseProject(self, node, parent = None):
  584. """
  585. reads a <project> element from the manifest file
  586. """
  587. name = self._reqatt(node, 'name')
  588. if parent:
  589. name = self._JoinName(parent.name, name)
  590. remote = self._get_remote(node)
  591. if remote is None:
  592. remote = self._default.remote
  593. if remote is None:
  594. raise ManifestParseError("no remote for project %s within %s" %
  595. (name, self.manifestFile))
  596. revisionExpr = node.getAttribute('revision') or remote.revision
  597. if not revisionExpr:
  598. revisionExpr = self._default.revisionExpr
  599. if not revisionExpr:
  600. raise ManifestParseError("no revision for project %s within %s" %
  601. (name, self.manifestFile))
  602. path = node.getAttribute('path')
  603. if not path:
  604. path = name
  605. if path.startswith('/'):
  606. raise ManifestParseError("project %s path cannot be absolute in %s" %
  607. (name, self.manifestFile))
  608. rebase = node.getAttribute('rebase')
  609. if not rebase:
  610. rebase = True
  611. else:
  612. rebase = rebase.lower() in ("yes", "true", "1")
  613. sync_c = node.getAttribute('sync-c')
  614. if not sync_c:
  615. sync_c = False
  616. else:
  617. sync_c = sync_c.lower() in ("yes", "true", "1")
  618. sync_s = node.getAttribute('sync-s')
  619. if not sync_s:
  620. sync_s = self._default.sync_s
  621. else:
  622. sync_s = sync_s.lower() in ("yes", "true", "1")
  623. clone_depth = node.getAttribute('clone-depth')
  624. if clone_depth:
  625. try:
  626. clone_depth = int(clone_depth)
  627. if clone_depth <= 0:
  628. raise ValueError()
  629. except ValueError:
  630. raise ManifestParseError('invalid clone-depth %s in %s' %
  631. (clone_depth, self.manifestFile))
  632. dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
  633. upstream = node.getAttribute('upstream')
  634. groups = ''
  635. if node.hasAttribute('groups'):
  636. groups = node.getAttribute('groups')
  637. groups = [x for x in re.split(r'[,\s]+', groups) if x]
  638. if parent is None:
  639. relpath, worktree, gitdir, objdir = self.GetProjectPaths(name, path)
  640. else:
  641. relpath, worktree, gitdir, objdir = \
  642. self.GetSubprojectPaths(parent, name, path)
  643. default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
  644. groups.extend(set(default_groups).difference(groups))
  645. if self.IsMirror and node.hasAttribute('force-path'):
  646. if node.getAttribute('force-path').lower() in ("yes", "true", "1"):
  647. gitdir = os.path.join(self.topdir, '%s.git' % path)
  648. project = Project(manifest = self,
  649. name = name,
  650. remote = remote.ToRemoteSpec(name),
  651. gitdir = gitdir,
  652. objdir = objdir,
  653. worktree = worktree,
  654. relpath = relpath,
  655. revisionExpr = revisionExpr,
  656. revisionId = None,
  657. rebase = rebase,
  658. groups = groups,
  659. sync_c = sync_c,
  660. sync_s = sync_s,
  661. clone_depth = clone_depth,
  662. upstream = upstream,
  663. parent = parent,
  664. dest_branch = dest_branch)
  665. for n in node.childNodes:
  666. if n.nodeName == 'copyfile':
  667. self._ParseCopyFile(project, n)
  668. if n.nodeName == 'linkfile':
  669. self._ParseLinkFile(project, n)
  670. if n.nodeName == 'annotation':
  671. self._ParseAnnotation(project, n)
  672. if n.nodeName == 'project':
  673. project.subprojects.append(self._ParseProject(n, parent = project))
  674. return project
  675. def GetProjectPaths(self, name, path):
  676. relpath = path
  677. if self.IsMirror:
  678. worktree = None
  679. gitdir = os.path.join(self.topdir, '%s.git' % name)
  680. objdir = gitdir
  681. else:
  682. worktree = os.path.join(self.topdir, path).replace('\\', '/')
  683. gitdir = os.path.join(self.repodir, 'projects', '%s.git' % path)
  684. objdir = os.path.join(self.repodir, 'project-objects', '%s.git' % name)
  685. return relpath, worktree, gitdir, objdir
  686. def GetProjectsWithName(self, name):
  687. return self._projects.get(name, [])
  688. def GetSubprojectName(self, parent, submodule_path):
  689. return os.path.join(parent.name, submodule_path)
  690. def _JoinRelpath(self, parent_relpath, relpath):
  691. return os.path.join(parent_relpath, relpath)
  692. def _UnjoinRelpath(self, parent_relpath, relpath):
  693. return os.path.relpath(relpath, parent_relpath)
  694. def GetSubprojectPaths(self, parent, name, path):
  695. relpath = self._JoinRelpath(parent.relpath, path)
  696. gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
  697. objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
  698. if self.IsMirror:
  699. worktree = None
  700. else:
  701. worktree = os.path.join(parent.worktree, path).replace('\\', '/')
  702. return relpath, worktree, gitdir, objdir
  703. def _ParseCopyFile(self, project, node):
  704. src = self._reqatt(node, 'src')
  705. dest = self._reqatt(node, 'dest')
  706. if not self.IsMirror:
  707. # src is project relative;
  708. # dest is relative to the top of the tree
  709. project.AddCopyFile(src, dest, os.path.join(self.topdir, dest))
  710. def _ParseLinkFile(self, project, node):
  711. src = self._reqatt(node, 'src')
  712. dest = self._reqatt(node, 'dest')
  713. if not self.IsMirror:
  714. # src is project relative;
  715. # dest is relative to the top of the tree
  716. project.AddLinkFile(src, dest, os.path.join(self.topdir, dest))
  717. def _ParseAnnotation(self, project, node):
  718. name = self._reqatt(node, 'name')
  719. value = self._reqatt(node, 'value')
  720. try:
  721. keep = self._reqatt(node, 'keep').lower()
  722. except ManifestParseError:
  723. keep = "true"
  724. if keep != "true" and keep != "false":
  725. raise ManifestParseError('optional "keep" attribute must be '
  726. '"true" or "false"')
  727. project.AddAnnotation(name, value, keep)
  728. def _get_remote(self, node):
  729. name = node.getAttribute('remote')
  730. if not name:
  731. return None
  732. v = self._remotes.get(name)
  733. if not v:
  734. raise ManifestParseError("remote %s not defined in %s" %
  735. (name, self.manifestFile))
  736. return v
  737. def _reqatt(self, node, attname):
  738. """
  739. reads a required attribute from the node.
  740. """
  741. v = node.getAttribute(attname)
  742. if not v:
  743. raise ManifestParseError("no %s in <%s> within %s" %
  744. (attname, node.nodeName, self.manifestFile))
  745. return v
  746. def projectsDiff(self, manifest):
  747. """return the projects differences between two manifests.
  748. The diff will be from self to given manifest.
  749. """
  750. fromProjects = self.paths
  751. toProjects = manifest.paths
  752. fromKeys = sorted(fromProjects.keys())
  753. toKeys = sorted(toProjects.keys())
  754. diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
  755. for proj in fromKeys:
  756. if not proj in toKeys:
  757. diff['removed'].append(fromProjects[proj])
  758. else:
  759. fromProj = fromProjects[proj]
  760. toProj = toProjects[proj]
  761. try:
  762. fromRevId = fromProj.GetCommitRevisionId()
  763. toRevId = toProj.GetCommitRevisionId()
  764. except ManifestInvalidRevisionError:
  765. diff['unreachable'].append((fromProj, toProj))
  766. else:
  767. if fromRevId != toRevId:
  768. diff['changed'].append((fromProj, toProj))
  769. toKeys.remove(proj)
  770. for proj in toKeys:
  771. diff['added'].append(toProjects[proj])
  772. return diff