manifest_xml.py 24 KB

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