manifest_xml.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  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 urlparse
  21. import xml.dom.minidom
  22. from git_config import GitConfig
  23. from git_refs import R_HEADS, HEAD
  24. from project import RemoteSpec, Project, MetaProject
  25. from error import ManifestParseError
  26. MANIFEST_FILE_NAME = 'manifest.xml'
  27. LOCAL_MANIFEST_NAME = 'local_manifest.xml'
  28. LOCAL_MANIFESTS_DIR_NAME = 'local_manifests'
  29. urlparse.uses_relative.extend(['ssh', 'git'])
  30. urlparse.uses_netloc.extend(['ssh', 'git'])
  31. class _Default(object):
  32. """Project defaults within the manifest."""
  33. revisionExpr = None
  34. remote = None
  35. sync_j = 1
  36. sync_c = False
  37. sync_s = False
  38. class _XmlRemote(object):
  39. def __init__(self,
  40. name,
  41. alias=None,
  42. fetch=None,
  43. manifestUrl=None,
  44. review=None):
  45. self.name = name
  46. self.fetchUrl = fetch
  47. self.manifestUrl = manifestUrl
  48. self.remoteAlias = alias
  49. self.reviewUrl = review
  50. self.resolvedFetchUrl = self._resolveFetchUrl()
  51. def __eq__(self, other):
  52. return self.__dict__ == other.__dict__
  53. def __ne__(self, other):
  54. return self.__dict__ != other.__dict__
  55. def _resolveFetchUrl(self):
  56. url = self.fetchUrl.rstrip('/')
  57. manifestUrl = self.manifestUrl.rstrip('/')
  58. # urljoin will get confused if there is no scheme in the base url
  59. # ie, if manifestUrl is of the form <hostname:port>
  60. if manifestUrl.find(':') != manifestUrl.find('/') - 1:
  61. manifestUrl = 'gopher://' + manifestUrl
  62. url = urlparse.urljoin(manifestUrl, url)
  63. return re.sub(r'^gopher://', '', url)
  64. def ToRemoteSpec(self, projectName):
  65. url = self.resolvedFetchUrl.rstrip('/') + '/' + projectName
  66. remoteName = self.name
  67. if self.remoteAlias:
  68. remoteName = self.remoteAlias
  69. return RemoteSpec(remoteName, url, self.reviewUrl)
  70. class XmlManifest(object):
  71. """manages the repo configuration file"""
  72. def __init__(self, repodir):
  73. self.repodir = os.path.abspath(repodir)
  74. self.topdir = os.path.dirname(self.repodir)
  75. self.manifestFile = os.path.join(self.repodir, MANIFEST_FILE_NAME)
  76. self.globalConfig = GitConfig.ForUser()
  77. self.repoProject = MetaProject(self, 'repo',
  78. gitdir = os.path.join(repodir, 'repo/.git'),
  79. worktree = os.path.join(repodir, 'repo'))
  80. self.manifestProject = MetaProject(self, 'manifests',
  81. gitdir = os.path.join(repodir, 'manifests.git'),
  82. worktree = os.path.join(repodir, 'manifests'))
  83. self._Unload()
  84. def Override(self, name):
  85. """Use a different manifest, just for the current instantiation.
  86. """
  87. path = os.path.join(self.manifestProject.worktree, name)
  88. if not os.path.isfile(path):
  89. raise ManifestParseError('manifest %s not found' % name)
  90. old = self.manifestFile
  91. try:
  92. self.manifestFile = path
  93. self._Unload()
  94. self._Load()
  95. finally:
  96. self.manifestFile = old
  97. def Link(self, name):
  98. """Update the repo metadata to use a different manifest.
  99. """
  100. self.Override(name)
  101. try:
  102. if os.path.exists(self.manifestFile):
  103. os.remove(self.manifestFile)
  104. os.symlink('manifests/%s' % name, self.manifestFile)
  105. except OSError:
  106. raise ManifestParseError('cannot link manifest %s' % name)
  107. def _RemoteToXml(self, r, doc, root):
  108. e = doc.createElement('remote')
  109. root.appendChild(e)
  110. e.setAttribute('name', r.name)
  111. e.setAttribute('fetch', r.fetchUrl)
  112. if r.reviewUrl is not None:
  113. e.setAttribute('review', r.reviewUrl)
  114. def Save(self, fd, peg_rev=False, peg_rev_upstream=True):
  115. """Write the current manifest out to the given file descriptor.
  116. """
  117. mp = self.manifestProject
  118. groups = mp.config.GetString('manifest.groups')
  119. if not groups:
  120. groups = 'all'
  121. groups = [x for x in re.split(r'[,\s]+', groups) if x]
  122. doc = xml.dom.minidom.Document()
  123. root = doc.createElement('manifest')
  124. doc.appendChild(root)
  125. # Save out the notice. There's a little bit of work here to give it the
  126. # right whitespace, which assumes that the notice is automatically indented
  127. # by 4 by minidom.
  128. if self.notice:
  129. notice_element = root.appendChild(doc.createElement('notice'))
  130. notice_lines = self.notice.splitlines()
  131. indented_notice = ('\n'.join(" "*4 + line for line in notice_lines))[4:]
  132. notice_element.appendChild(doc.createTextNode(indented_notice))
  133. d = self.default
  134. sort_remotes = list(self.remotes.keys())
  135. sort_remotes.sort()
  136. for r in sort_remotes:
  137. self._RemoteToXml(self.remotes[r], doc, root)
  138. if self.remotes:
  139. root.appendChild(doc.createTextNode(''))
  140. have_default = False
  141. e = doc.createElement('default')
  142. if d.remote:
  143. have_default = True
  144. e.setAttribute('remote', d.remote.name)
  145. if d.revisionExpr:
  146. have_default = True
  147. e.setAttribute('revision', d.revisionExpr)
  148. if d.sync_j > 1:
  149. have_default = True
  150. e.setAttribute('sync-j', '%d' % d.sync_j)
  151. if d.sync_c:
  152. have_default = True
  153. e.setAttribute('sync-c', 'true')
  154. if d.sync_s:
  155. have_default = True
  156. e.setAttribute('sync-s', 'true')
  157. if have_default:
  158. root.appendChild(e)
  159. root.appendChild(doc.createTextNode(''))
  160. if self._manifest_server:
  161. e = doc.createElement('manifest-server')
  162. e.setAttribute('url', self._manifest_server)
  163. root.appendChild(e)
  164. root.appendChild(doc.createTextNode(''))
  165. def output_projects(parent, parent_node, projects):
  166. for p in projects:
  167. output_project(parent, parent_node, self.projects[p])
  168. def output_project(parent, parent_node, p):
  169. if not p.MatchesGroups(groups):
  170. return
  171. name = p.name
  172. relpath = p.relpath
  173. if parent:
  174. name = self._UnjoinName(parent.name, name)
  175. relpath = self._UnjoinRelpath(parent.relpath, relpath)
  176. e = doc.createElement('project')
  177. parent_node.appendChild(e)
  178. e.setAttribute('name', name)
  179. if relpath != name:
  180. e.setAttribute('path', relpath)
  181. if not d.remote or p.remote.name != d.remote.name:
  182. e.setAttribute('remote', p.remote.name)
  183. if peg_rev:
  184. if self.IsMirror:
  185. value = p.bare_git.rev_parse(p.revisionExpr + '^0')
  186. else:
  187. value = p.work_git.rev_parse(HEAD + '^0')
  188. e.setAttribute('revision', value)
  189. if peg_rev_upstream and value != p.revisionExpr:
  190. # Only save the origin if the origin is not a sha1, and the default
  191. # isn't our value, and the if the default doesn't already have that
  192. # covered.
  193. e.setAttribute('upstream', p.revisionExpr)
  194. elif not d.revisionExpr or p.revisionExpr != d.revisionExpr:
  195. e.setAttribute('revision', p.revisionExpr)
  196. for c in p.copyfiles:
  197. ce = doc.createElement('copyfile')
  198. ce.setAttribute('src', c.src)
  199. ce.setAttribute('dest', c.dest)
  200. e.appendChild(ce)
  201. default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
  202. egroups = [g for g in p.groups if g not in default_groups]
  203. if egroups:
  204. e.setAttribute('groups', ','.join(egroups))
  205. for a in p.annotations:
  206. if a.keep == "true":
  207. ae = doc.createElement('annotation')
  208. ae.setAttribute('name', a.name)
  209. ae.setAttribute('value', a.value)
  210. e.appendChild(ae)
  211. if p.sync_c:
  212. e.setAttribute('sync-c', 'true')
  213. if p.sync_s:
  214. e.setAttribute('sync-s', 'true')
  215. if p.subprojects:
  216. sort_projects = [subp.name for subp in p.subprojects]
  217. sort_projects.sort()
  218. output_projects(p, e, sort_projects)
  219. sort_projects = [key for key in self.projects.keys()
  220. if not self.projects[key].parent]
  221. sort_projects.sort()
  222. output_projects(None, root, sort_projects)
  223. if self._repo_hooks_project:
  224. root.appendChild(doc.createTextNode(''))
  225. e = doc.createElement('repo-hooks')
  226. e.setAttribute('in-project', self._repo_hooks_project.name)
  227. e.setAttribute('enabled-list',
  228. ' '.join(self._repo_hooks_project.enabled_repo_hooks))
  229. root.appendChild(e)
  230. doc.writexml(fd, '', ' ', '\n', 'UTF-8')
  231. @property
  232. def projects(self):
  233. self._Load()
  234. return self._projects
  235. @property
  236. def remotes(self):
  237. self._Load()
  238. return self._remotes
  239. @property
  240. def default(self):
  241. self._Load()
  242. return self._default
  243. @property
  244. def repo_hooks_project(self):
  245. self._Load()
  246. return self._repo_hooks_project
  247. @property
  248. def notice(self):
  249. self._Load()
  250. return self._notice
  251. @property
  252. def manifest_server(self):
  253. self._Load()
  254. return self._manifest_server
  255. @property
  256. def IsMirror(self):
  257. return self.manifestProject.config.GetBoolean('repo.mirror')
  258. def _Unload(self):
  259. self._loaded = False
  260. self._projects = {}
  261. self._remotes = {}
  262. self._default = None
  263. self._repo_hooks_project = None
  264. self._notice = None
  265. self.branch = None
  266. self._manifest_server = None
  267. def _Load(self):
  268. if not self._loaded:
  269. m = self.manifestProject
  270. b = m.GetBranch(m.CurrentBranch).merge
  271. if b is not None and b.startswith(R_HEADS):
  272. b = b[len(R_HEADS):]
  273. self.branch = b
  274. nodes = []
  275. nodes.append(self._ParseManifestXml(self.manifestFile,
  276. self.manifestProject.worktree))
  277. local = os.path.join(self.repodir, LOCAL_MANIFEST_NAME)
  278. if os.path.exists(local):
  279. print('warning: %s is deprecated; put local manifests in %s instead'
  280. % (LOCAL_MANIFEST_NAME, LOCAL_MANIFESTS_DIR_NAME),
  281. file=sys.stderr)
  282. nodes.append(self._ParseManifestXml(local, self.repodir))
  283. local_dir = os.path.abspath(os.path.join(self.repodir, LOCAL_MANIFESTS_DIR_NAME))
  284. try:
  285. for local_file in sorted(os.listdir(local_dir)):
  286. if local_file.endswith('.xml'):
  287. try:
  288. nodes.append(self._ParseManifestXml(local_file, self.repodir))
  289. except ManifestParseError as e:
  290. print('%s' % str(e), file=sys.stderr)
  291. except OSError:
  292. pass
  293. self._ParseManifest(nodes)
  294. if self.IsMirror:
  295. self._AddMetaProjectMirror(self.repoProject)
  296. self._AddMetaProjectMirror(self.manifestProject)
  297. self._loaded = True
  298. def _ParseManifestXml(self, path, include_root):
  299. try:
  300. root = xml.dom.minidom.parse(path)
  301. except (OSError, xml.parsers.expat.ExpatError) as e:
  302. raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
  303. if not root or not root.childNodes:
  304. raise ManifestParseError("no root node in %s" % (path,))
  305. for manifest in root.childNodes:
  306. if manifest.nodeName == 'manifest':
  307. break
  308. else:
  309. raise ManifestParseError("no <manifest> in %s" % (path,))
  310. nodes = []
  311. for node in manifest.childNodes: # pylint:disable=W0631
  312. # We only get here if manifest is initialised
  313. if node.nodeName == 'include':
  314. name = self._reqatt(node, 'name')
  315. fp = os.path.join(include_root, name)
  316. if not os.path.isfile(fp):
  317. raise ManifestParseError, \
  318. "include %s doesn't exist or isn't a file" % \
  319. (name,)
  320. try:
  321. nodes.extend(self._ParseManifestXml(fp, include_root))
  322. # should isolate this to the exact exception, but that's
  323. # tricky. actual parsing implementation may vary.
  324. except (KeyboardInterrupt, RuntimeError, SystemExit):
  325. raise
  326. except Exception as e:
  327. raise ManifestParseError(
  328. "failed parsing included manifest %s: %s", (name, e))
  329. else:
  330. nodes.append(node)
  331. return nodes
  332. def _ParseManifest(self, node_list):
  333. for node in itertools.chain(*node_list):
  334. if node.nodeName == 'remote':
  335. remote = self._ParseRemote(node)
  336. if remote:
  337. if remote.name in self._remotes:
  338. if remote != self._remotes[remote.name]:
  339. raise ManifestParseError(
  340. 'remote %s already exists with different attributes' %
  341. (remote.name))
  342. else:
  343. self._remotes[remote.name] = remote
  344. for node in itertools.chain(*node_list):
  345. if node.nodeName == 'default':
  346. if self._default is not None:
  347. raise ManifestParseError(
  348. 'duplicate default in %s' %
  349. (self.manifestFile))
  350. self._default = self._ParseDefault(node)
  351. if self._default is None:
  352. self._default = _Default()
  353. for node in itertools.chain(*node_list):
  354. if node.nodeName == 'notice':
  355. if self._notice is not None:
  356. raise ManifestParseError(
  357. 'duplicate notice in %s' %
  358. (self.manifestFile))
  359. self._notice = self._ParseNotice(node)
  360. for node in itertools.chain(*node_list):
  361. if node.nodeName == 'manifest-server':
  362. url = self._reqatt(node, 'url')
  363. if self._manifest_server is not None:
  364. raise ManifestParseError(
  365. 'duplicate manifest-server in %s' %
  366. (self.manifestFile))
  367. self._manifest_server = url
  368. def recursively_add_projects(project):
  369. if self._projects.get(project.name):
  370. raise ManifestParseError(
  371. 'duplicate project %s in %s' %
  372. (project.name, self.manifestFile))
  373. self._projects[project.name] = project
  374. for subproject in project.subprojects:
  375. recursively_add_projects(subproject)
  376. for node in itertools.chain(*node_list):
  377. if node.nodeName == 'project':
  378. project = self._ParseProject(node)
  379. recursively_add_projects(project)
  380. if node.nodeName == 'repo-hooks':
  381. # Get the name of the project and the (space-separated) list of enabled.
  382. repo_hooks_project = self._reqatt(node, 'in-project')
  383. enabled_repo_hooks = self._reqatt(node, 'enabled-list').split()
  384. # Only one project can be the hooks project
  385. if self._repo_hooks_project is not None:
  386. raise ManifestParseError(
  387. 'duplicate repo-hooks in %s' %
  388. (self.manifestFile))
  389. # Store a reference to the Project.
  390. try:
  391. self._repo_hooks_project = self._projects[repo_hooks_project]
  392. except KeyError:
  393. raise ManifestParseError(
  394. 'project %s not found for repo-hooks' %
  395. (repo_hooks_project))
  396. # Store the enabled hooks in the Project object.
  397. self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
  398. if node.nodeName == 'remove-project':
  399. name = self._reqatt(node, 'name')
  400. try:
  401. del self._projects[name]
  402. except KeyError:
  403. raise ManifestParseError('remove-project element specifies non-existent '
  404. 'project: %s' % name)
  405. # If the manifest removes the hooks project, treat it as if it deleted
  406. # the repo-hooks element too.
  407. if self._repo_hooks_project and (self._repo_hooks_project.name == name):
  408. self._repo_hooks_project = None
  409. def _AddMetaProjectMirror(self, m):
  410. name = None
  411. m_url = m.GetRemote(m.remote.name).url
  412. if m_url.endswith('/.git'):
  413. raise ManifestParseError, 'refusing to mirror %s' % m_url
  414. if self._default and self._default.remote:
  415. url = self._default.remote.resolvedFetchUrl
  416. if not url.endswith('/'):
  417. url += '/'
  418. if m_url.startswith(url):
  419. remote = self._default.remote
  420. name = m_url[len(url):]
  421. if name is None:
  422. s = m_url.rindex('/') + 1
  423. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  424. remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
  425. name = m_url[s:]
  426. if name.endswith('.git'):
  427. name = name[:-4]
  428. if name not in self._projects:
  429. m.PreSync()
  430. gitdir = os.path.join(self.topdir, '%s.git' % name)
  431. project = Project(manifest = self,
  432. name = name,
  433. remote = remote.ToRemoteSpec(name),
  434. gitdir = gitdir,
  435. worktree = None,
  436. relpath = None,
  437. revisionExpr = m.revisionExpr,
  438. revisionId = None)
  439. self._projects[project.name] = project
  440. def _ParseRemote(self, node):
  441. """
  442. reads a <remote> element from the manifest file
  443. """
  444. name = self._reqatt(node, 'name')
  445. alias = node.getAttribute('alias')
  446. if alias == '':
  447. alias = None
  448. fetch = self._reqatt(node, 'fetch')
  449. review = node.getAttribute('review')
  450. if review == '':
  451. review = None
  452. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  453. return _XmlRemote(name, alias, fetch, manifestUrl, review)
  454. def _ParseDefault(self, node):
  455. """
  456. reads a <default> element from the manifest file
  457. """
  458. d = _Default()
  459. d.remote = self._get_remote(node)
  460. d.revisionExpr = node.getAttribute('revision')
  461. if d.revisionExpr == '':
  462. d.revisionExpr = None
  463. sync_j = node.getAttribute('sync-j')
  464. if sync_j == '' or sync_j is None:
  465. d.sync_j = 1
  466. else:
  467. d.sync_j = int(sync_j)
  468. sync_c = node.getAttribute('sync-c')
  469. if not sync_c:
  470. d.sync_c = False
  471. else:
  472. d.sync_c = sync_c.lower() in ("yes", "true", "1")
  473. sync_s = node.getAttribute('sync-s')
  474. if not sync_s:
  475. d.sync_s = False
  476. else:
  477. d.sync_s = sync_s.lower() in ("yes", "true", "1")
  478. return d
  479. def _ParseNotice(self, node):
  480. """
  481. reads a <notice> element from the manifest file
  482. The <notice> element is distinct from other tags in the XML in that the
  483. data is conveyed between the start and end tag (it's not an empty-element
  484. tag).
  485. The white space (carriage returns, indentation) for the notice element is
  486. relevant and is parsed in a way that is based on how python docstrings work.
  487. In fact, the code is remarkably similar to here:
  488. http://www.python.org/dev/peps/pep-0257/
  489. """
  490. # Get the data out of the node...
  491. notice = node.childNodes[0].data
  492. # Figure out minimum indentation, skipping the first line (the same line
  493. # as the <notice> tag)...
  494. minIndent = sys.maxint
  495. lines = notice.splitlines()
  496. for line in lines[1:]:
  497. lstrippedLine = line.lstrip()
  498. if lstrippedLine:
  499. indent = len(line) - len(lstrippedLine)
  500. minIndent = min(indent, minIndent)
  501. # Strip leading / trailing blank lines and also indentation.
  502. cleanLines = [lines[0].strip()]
  503. for line in lines[1:]:
  504. cleanLines.append(line[minIndent:].rstrip())
  505. # Clear completely blank lines from front and back...
  506. while cleanLines and not cleanLines[0]:
  507. del cleanLines[0]
  508. while cleanLines and not cleanLines[-1]:
  509. del cleanLines[-1]
  510. return '\n'.join(cleanLines)
  511. def _JoinName(self, parent_name, name):
  512. return os.path.join(parent_name, name)
  513. def _UnjoinName(self, parent_name, name):
  514. return os.path.relpath(name, parent_name)
  515. def _ParseProject(self, node, parent = None):
  516. """
  517. reads a <project> element from the manifest file
  518. """
  519. name = self._reqatt(node, 'name')
  520. if parent:
  521. name = self._JoinName(parent.name, name)
  522. remote = self._get_remote(node)
  523. if remote is None:
  524. remote = self._default.remote
  525. if remote is None:
  526. raise ManifestParseError, \
  527. "no remote for project %s within %s" % \
  528. (name, self.manifestFile)
  529. revisionExpr = node.getAttribute('revision')
  530. if not revisionExpr:
  531. revisionExpr = self._default.revisionExpr
  532. if not revisionExpr:
  533. raise ManifestParseError, \
  534. "no revision for project %s within %s" % \
  535. (name, self.manifestFile)
  536. path = node.getAttribute('path')
  537. if not path:
  538. path = name
  539. if path.startswith('/'):
  540. raise ManifestParseError, \
  541. "project %s path cannot be absolute in %s" % \
  542. (name, self.manifestFile)
  543. rebase = node.getAttribute('rebase')
  544. if not rebase:
  545. rebase = True
  546. else:
  547. rebase = rebase.lower() in ("yes", "true", "1")
  548. sync_c = node.getAttribute('sync-c')
  549. if not sync_c:
  550. sync_c = False
  551. else:
  552. sync_c = sync_c.lower() in ("yes", "true", "1")
  553. sync_s = node.getAttribute('sync-s')
  554. if not sync_s:
  555. sync_s = self._default.sync_s
  556. else:
  557. sync_s = sync_s.lower() in ("yes", "true", "1")
  558. upstream = node.getAttribute('upstream')
  559. groups = ''
  560. if node.hasAttribute('groups'):
  561. groups = node.getAttribute('groups')
  562. groups = [x for x in re.split(r'[,\s]+', groups) if x]
  563. if parent is None:
  564. relpath, worktree, gitdir = self.GetProjectPaths(name, path)
  565. else:
  566. relpath, worktree, gitdir = self.GetSubprojectPaths(parent, path)
  567. default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
  568. groups.extend(set(default_groups).difference(groups))
  569. project = Project(manifest = self,
  570. name = name,
  571. remote = remote.ToRemoteSpec(name),
  572. gitdir = gitdir,
  573. worktree = worktree,
  574. relpath = relpath,
  575. revisionExpr = revisionExpr,
  576. revisionId = None,
  577. rebase = rebase,
  578. groups = groups,
  579. sync_c = sync_c,
  580. sync_s = sync_s,
  581. upstream = upstream,
  582. parent = parent)
  583. for n in node.childNodes:
  584. if n.nodeName == 'copyfile':
  585. self._ParseCopyFile(project, n)
  586. if n.nodeName == 'annotation':
  587. self._ParseAnnotation(project, n)
  588. if n.nodeName == 'project':
  589. project.subprojects.append(self._ParseProject(n, parent = project))
  590. return project
  591. def GetProjectPaths(self, name, path):
  592. relpath = path
  593. if self.IsMirror:
  594. worktree = None
  595. gitdir = os.path.join(self.topdir, '%s.git' % name)
  596. else:
  597. worktree = os.path.join(self.topdir, path).replace('\\', '/')
  598. gitdir = os.path.join(self.repodir, 'projects', '%s.git' % path)
  599. return relpath, worktree, gitdir
  600. def GetSubprojectName(self, parent, submodule_path):
  601. return os.path.join(parent.name, submodule_path)
  602. def _JoinRelpath(self, parent_relpath, relpath):
  603. return os.path.join(parent_relpath, relpath)
  604. def _UnjoinRelpath(self, parent_relpath, relpath):
  605. return os.path.relpath(relpath, parent_relpath)
  606. def GetSubprojectPaths(self, parent, path):
  607. relpath = self._JoinRelpath(parent.relpath, path)
  608. gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
  609. if self.IsMirror:
  610. worktree = None
  611. else:
  612. worktree = os.path.join(parent.worktree, path).replace('\\', '/')
  613. return relpath, worktree, gitdir
  614. def _ParseCopyFile(self, project, node):
  615. src = self._reqatt(node, 'src')
  616. dest = self._reqatt(node, 'dest')
  617. if not self.IsMirror:
  618. # src is project relative;
  619. # dest is relative to the top of the tree
  620. project.AddCopyFile(src, dest, os.path.join(self.topdir, dest))
  621. def _ParseAnnotation(self, project, node):
  622. name = self._reqatt(node, 'name')
  623. value = self._reqatt(node, 'value')
  624. try:
  625. keep = self._reqatt(node, 'keep').lower()
  626. except ManifestParseError:
  627. keep = "true"
  628. if keep != "true" and keep != "false":
  629. raise ManifestParseError, "optional \"keep\" attribute must be \"true\" or \"false\""
  630. project.AddAnnotation(name, value, keep)
  631. def _get_remote(self, node):
  632. name = node.getAttribute('remote')
  633. if not name:
  634. return None
  635. v = self._remotes.get(name)
  636. if not v:
  637. raise ManifestParseError, \
  638. "remote %s not defined in %s" % \
  639. (name, self.manifestFile)
  640. return v
  641. def _reqatt(self, node, attname):
  642. """
  643. reads a required attribute from the node.
  644. """
  645. v = node.getAttribute(attname)
  646. if not v:
  647. raise ManifestParseError, \
  648. "no %s in <%s> within %s" % \
  649. (attname, node.nodeName, self.manifestFile)
  650. return v