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