manifest_xml.py 25 KB

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