manifest_xml.py 26 KB

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