manifest_xml.py 26 KB

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