manifest_xml.py 26 KB

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