manifest_xml.py 26 KB

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