manifest_xml.py 24 KB

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