manifest_xml.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  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 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, 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. try:
  293. local = os.path.join(local_dir, local_file)
  294. nodes.append(self._ParseManifestXml(local, self.repodir))
  295. except ManifestParseError as e:
  296. print('%s' % str(e), file=sys.stderr)
  297. except OSError:
  298. pass
  299. try:
  300. self._ParseManifest(nodes)
  301. except ManifestParseError as e:
  302. # There was a problem parsing, unload ourselves in case they catch
  303. # this error and try again later, we will show the correct error
  304. self._Unload()
  305. raise e
  306. if self.IsMirror:
  307. self._AddMetaProjectMirror(self.repoProject)
  308. self._AddMetaProjectMirror(self.manifestProject)
  309. self._loaded = True
  310. def _ParseManifestXml(self, path, include_root):
  311. try:
  312. root = xml.dom.minidom.parse(path)
  313. except (OSError, xml.parsers.expat.ExpatError) as e:
  314. raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
  315. if not root or not root.childNodes:
  316. raise ManifestParseError("no root node in %s" % (path,))
  317. for manifest in root.childNodes:
  318. if manifest.nodeName == 'manifest':
  319. break
  320. else:
  321. raise ManifestParseError("no <manifest> in %s" % (path,))
  322. nodes = []
  323. for node in manifest.childNodes: # pylint:disable=W0631
  324. # We only get here if manifest is initialised
  325. if node.nodeName == 'include':
  326. name = self._reqatt(node, 'name')
  327. fp = os.path.join(include_root, name)
  328. if not os.path.isfile(fp):
  329. raise ManifestParseError, \
  330. "include %s doesn't exist or isn't a file" % \
  331. (name,)
  332. try:
  333. nodes.extend(self._ParseManifestXml(fp, include_root))
  334. # should isolate this to the exact exception, but that's
  335. # tricky. actual parsing implementation may vary.
  336. except (KeyboardInterrupt, RuntimeError, SystemExit):
  337. raise
  338. except Exception as e:
  339. raise ManifestParseError(
  340. "failed parsing included manifest %s: %s", (name, e))
  341. else:
  342. nodes.append(node)
  343. return nodes
  344. def _ParseManifest(self, node_list):
  345. for node in itertools.chain(*node_list):
  346. if node.nodeName == 'remote':
  347. remote = self._ParseRemote(node)
  348. if remote:
  349. if remote.name in self._remotes:
  350. if remote != self._remotes[remote.name]:
  351. raise ManifestParseError(
  352. 'remote %s already exists with different attributes' %
  353. (remote.name))
  354. else:
  355. self._remotes[remote.name] = remote
  356. for node in itertools.chain(*node_list):
  357. if node.nodeName == 'default':
  358. if self._default is not None:
  359. raise ManifestParseError(
  360. 'duplicate default in %s' %
  361. (self.manifestFile))
  362. self._default = self._ParseDefault(node)
  363. if self._default is None:
  364. self._default = _Default()
  365. for node in itertools.chain(*node_list):
  366. if node.nodeName == 'notice':
  367. if self._notice is not None:
  368. raise ManifestParseError(
  369. 'duplicate notice in %s' %
  370. (self.manifestFile))
  371. self._notice = self._ParseNotice(node)
  372. for node in itertools.chain(*node_list):
  373. if node.nodeName == 'manifest-server':
  374. url = self._reqatt(node, 'url')
  375. if self._manifest_server is not None:
  376. raise ManifestParseError(
  377. 'duplicate manifest-server in %s' %
  378. (self.manifestFile))
  379. self._manifest_server = url
  380. def recursively_add_projects(project):
  381. if self._projects.get(project.name):
  382. raise ManifestParseError(
  383. 'duplicate project %s in %s' %
  384. (project.name, self.manifestFile))
  385. self._projects[project.name] = project
  386. for subproject in project.subprojects:
  387. recursively_add_projects(subproject)
  388. for node in itertools.chain(*node_list):
  389. if node.nodeName == 'project':
  390. project = self._ParseProject(node)
  391. recursively_add_projects(project)
  392. if node.nodeName == 'repo-hooks':
  393. # Get the name of the project and the (space-separated) list of enabled.
  394. repo_hooks_project = self._reqatt(node, 'in-project')
  395. enabled_repo_hooks = self._reqatt(node, 'enabled-list').split()
  396. # Only one project can be the hooks project
  397. if self._repo_hooks_project is not None:
  398. raise ManifestParseError(
  399. 'duplicate repo-hooks in %s' %
  400. (self.manifestFile))
  401. # Store a reference to the Project.
  402. try:
  403. self._repo_hooks_project = self._projects[repo_hooks_project]
  404. except KeyError:
  405. raise ManifestParseError(
  406. 'project %s not found for repo-hooks' %
  407. (repo_hooks_project))
  408. # Store the enabled hooks in the Project object.
  409. self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
  410. if node.nodeName == 'remove-project':
  411. name = self._reqatt(node, 'name')
  412. try:
  413. del self._projects[name]
  414. except KeyError:
  415. raise ManifestParseError('remove-project element specifies non-existent '
  416. 'project: %s' % name)
  417. # If the manifest removes the hooks project, treat it as if it deleted
  418. # the repo-hooks element too.
  419. if self._repo_hooks_project and (self._repo_hooks_project.name == name):
  420. self._repo_hooks_project = None
  421. def _AddMetaProjectMirror(self, m):
  422. name = None
  423. m_url = m.GetRemote(m.remote.name).url
  424. if m_url.endswith('/.git'):
  425. raise ManifestParseError, 'refusing to mirror %s' % m_url
  426. if self._default and self._default.remote:
  427. url = self._default.remote.resolvedFetchUrl
  428. if not url.endswith('/'):
  429. url += '/'
  430. if m_url.startswith(url):
  431. remote = self._default.remote
  432. name = m_url[len(url):]
  433. if name is None:
  434. s = m_url.rindex('/') + 1
  435. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  436. remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
  437. name = m_url[s:]
  438. if name.endswith('.git'):
  439. name = name[:-4]
  440. if name not in self._projects:
  441. m.PreSync()
  442. gitdir = os.path.join(self.topdir, '%s.git' % name)
  443. project = Project(manifest = self,
  444. name = name,
  445. remote = remote.ToRemoteSpec(name),
  446. gitdir = gitdir,
  447. worktree = None,
  448. relpath = None,
  449. revisionExpr = m.revisionExpr,
  450. revisionId = None)
  451. self._projects[project.name] = project
  452. def _ParseRemote(self, node):
  453. """
  454. reads a <remote> element from the manifest file
  455. """
  456. name = self._reqatt(node, 'name')
  457. alias = node.getAttribute('alias')
  458. if alias == '':
  459. alias = None
  460. fetch = self._reqatt(node, 'fetch')
  461. review = node.getAttribute('review')
  462. if review == '':
  463. review = None
  464. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  465. return _XmlRemote(name, alias, fetch, manifestUrl, review)
  466. def _ParseDefault(self, node):
  467. """
  468. reads a <default> element from the manifest file
  469. """
  470. d = _Default()
  471. d.remote = self._get_remote(node)
  472. d.revisionExpr = node.getAttribute('revision')
  473. if d.revisionExpr == '':
  474. d.revisionExpr = None
  475. sync_j = node.getAttribute('sync-j')
  476. if sync_j == '' or sync_j is None:
  477. d.sync_j = 1
  478. else:
  479. d.sync_j = int(sync_j)
  480. sync_c = node.getAttribute('sync-c')
  481. if not sync_c:
  482. d.sync_c = False
  483. else:
  484. d.sync_c = sync_c.lower() in ("yes", "true", "1")
  485. sync_s = node.getAttribute('sync-s')
  486. if not sync_s:
  487. d.sync_s = False
  488. else:
  489. d.sync_s = sync_s.lower() in ("yes", "true", "1")
  490. return d
  491. def _ParseNotice(self, node):
  492. """
  493. reads a <notice> element from the manifest file
  494. The <notice> element is distinct from other tags in the XML in that the
  495. data is conveyed between the start and end tag (it's not an empty-element
  496. tag).
  497. The white space (carriage returns, indentation) for the notice element is
  498. relevant and is parsed in a way that is based on how python docstrings work.
  499. In fact, the code is remarkably similar to here:
  500. http://www.python.org/dev/peps/pep-0257/
  501. """
  502. # Get the data out of the node...
  503. notice = node.childNodes[0].data
  504. # Figure out minimum indentation, skipping the first line (the same line
  505. # as the <notice> tag)...
  506. minIndent = sys.maxint
  507. lines = notice.splitlines()
  508. for line in lines[1:]:
  509. lstrippedLine = line.lstrip()
  510. if lstrippedLine:
  511. indent = len(line) - len(lstrippedLine)
  512. minIndent = min(indent, minIndent)
  513. # Strip leading / trailing blank lines and also indentation.
  514. cleanLines = [lines[0].strip()]
  515. for line in lines[1:]:
  516. cleanLines.append(line[minIndent:].rstrip())
  517. # Clear completely blank lines from front and back...
  518. while cleanLines and not cleanLines[0]:
  519. del cleanLines[0]
  520. while cleanLines and not cleanLines[-1]:
  521. del cleanLines[-1]
  522. return '\n'.join(cleanLines)
  523. def _JoinName(self, parent_name, name):
  524. return os.path.join(parent_name, name)
  525. def _UnjoinName(self, parent_name, name):
  526. return os.path.relpath(name, parent_name)
  527. def _ParseProject(self, node, parent = None):
  528. """
  529. reads a <project> element from the manifest file
  530. """
  531. name = self._reqatt(node, 'name')
  532. if parent:
  533. name = self._JoinName(parent.name, name)
  534. remote = self._get_remote(node)
  535. if remote is None:
  536. remote = self._default.remote
  537. if remote is None:
  538. raise ManifestParseError, \
  539. "no remote for project %s within %s" % \
  540. (name, self.manifestFile)
  541. revisionExpr = node.getAttribute('revision')
  542. if not revisionExpr:
  543. revisionExpr = self._default.revisionExpr
  544. if not revisionExpr:
  545. raise ManifestParseError, \
  546. "no revision for project %s within %s" % \
  547. (name, self.manifestFile)
  548. path = node.getAttribute('path')
  549. if not path:
  550. path = name
  551. if path.startswith('/'):
  552. raise ManifestParseError, \
  553. "project %s path cannot be absolute in %s" % \
  554. (name, self.manifestFile)
  555. rebase = node.getAttribute('rebase')
  556. if not rebase:
  557. rebase = True
  558. else:
  559. rebase = rebase.lower() in ("yes", "true", "1")
  560. sync_c = node.getAttribute('sync-c')
  561. if not sync_c:
  562. sync_c = False
  563. else:
  564. sync_c = sync_c.lower() in ("yes", "true", "1")
  565. sync_s = node.getAttribute('sync-s')
  566. if not sync_s:
  567. sync_s = self._default.sync_s
  568. else:
  569. sync_s = sync_s.lower() in ("yes", "true", "1")
  570. upstream = node.getAttribute('upstream')
  571. groups = ''
  572. if node.hasAttribute('groups'):
  573. groups = node.getAttribute('groups')
  574. groups = [x for x in re.split(r'[,\s]+', groups) if x]
  575. if parent is None:
  576. relpath, worktree, gitdir = self.GetProjectPaths(name, path)
  577. else:
  578. relpath, worktree, gitdir = self.GetSubprojectPaths(parent, path)
  579. default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
  580. groups.extend(set(default_groups).difference(groups))
  581. project = Project(manifest = self,
  582. name = name,
  583. remote = remote.ToRemoteSpec(name),
  584. gitdir = gitdir,
  585. worktree = worktree,
  586. relpath = relpath,
  587. revisionExpr = revisionExpr,
  588. revisionId = None,
  589. rebase = rebase,
  590. groups = groups,
  591. sync_c = sync_c,
  592. sync_s = sync_s,
  593. upstream = upstream,
  594. parent = parent)
  595. for n in node.childNodes:
  596. if n.nodeName == 'copyfile':
  597. self._ParseCopyFile(project, n)
  598. if n.nodeName == 'annotation':
  599. self._ParseAnnotation(project, n)
  600. if n.nodeName == 'project':
  601. project.subprojects.append(self._ParseProject(n, parent = project))
  602. return project
  603. def GetProjectPaths(self, name, path):
  604. relpath = path
  605. if self.IsMirror:
  606. worktree = None
  607. gitdir = os.path.join(self.topdir, '%s.git' % name)
  608. else:
  609. worktree = os.path.join(self.topdir, path).replace('\\', '/')
  610. gitdir = os.path.join(self.repodir, 'projects', '%s.git' % path)
  611. return relpath, worktree, gitdir
  612. def GetSubprojectName(self, parent, submodule_path):
  613. return os.path.join(parent.name, submodule_path)
  614. def _JoinRelpath(self, parent_relpath, relpath):
  615. return os.path.join(parent_relpath, relpath)
  616. def _UnjoinRelpath(self, parent_relpath, relpath):
  617. return os.path.relpath(relpath, parent_relpath)
  618. def GetSubprojectPaths(self, parent, path):
  619. relpath = self._JoinRelpath(parent.relpath, path)
  620. gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
  621. if self.IsMirror:
  622. worktree = None
  623. else:
  624. worktree = os.path.join(parent.worktree, path).replace('\\', '/')
  625. return relpath, worktree, gitdir
  626. def _ParseCopyFile(self, project, node):
  627. src = self._reqatt(node, 'src')
  628. dest = self._reqatt(node, 'dest')
  629. if not self.IsMirror:
  630. # src is project relative;
  631. # dest is relative to the top of the tree
  632. project.AddCopyFile(src, dest, os.path.join(self.topdir, dest))
  633. def _ParseAnnotation(self, project, node):
  634. name = self._reqatt(node, 'name')
  635. value = self._reqatt(node, 'value')
  636. try:
  637. keep = self._reqatt(node, 'keep').lower()
  638. except ManifestParseError:
  639. keep = "true"
  640. if keep != "true" and keep != "false":
  641. raise ManifestParseError, "optional \"keep\" attribute must be \"true\" or \"false\""
  642. project.AddAnnotation(name, value, keep)
  643. def _get_remote(self, node):
  644. name = node.getAttribute('remote')
  645. if not name:
  646. return None
  647. v = self._remotes.get(name)
  648. if not v:
  649. raise ManifestParseError, \
  650. "remote %s not defined in %s" % \
  651. (name, self.manifestFile)
  652. return v
  653. def _reqatt(self, node, attname):
  654. """
  655. reads a required attribute from the node.
  656. """
  657. v = node.getAttribute(attname)
  658. if not v:
  659. raise ManifestParseError, \
  660. "no %s in <%s> within %s" % \
  661. (attname, node.nodeName, self.manifestFile)
  662. return v