manifest_xml.py 26 KB

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