manifest_xml.py 25 KB

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