manifest_xml.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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 project_name in projects:
  181. for project in self._projects[project_name]:
  182. output_project(parent, parent_node, project)
  183. def output_project(parent, parent_node, p):
  184. if not p.MatchesGroups(groups):
  185. return
  186. name = p.name
  187. relpath = p.relpath
  188. if parent:
  189. name = self._UnjoinName(parent.name, name)
  190. relpath = self._UnjoinRelpath(parent.relpath, relpath)
  191. e = doc.createElement('project')
  192. parent_node.appendChild(e)
  193. e.setAttribute('name', name)
  194. if relpath != name:
  195. e.setAttribute('path', relpath)
  196. remoteName = d.remote.remoteAlias or d.remote.name
  197. if not d.remote or p.remote.name != remoteName:
  198. e.setAttribute('remote', p.remote.name)
  199. if peg_rev:
  200. if self.IsMirror:
  201. value = p.bare_git.rev_parse(p.revisionExpr + '^0')
  202. else:
  203. value = p.work_git.rev_parse(HEAD + '^0')
  204. e.setAttribute('revision', value)
  205. if peg_rev_upstream and value != p.revisionExpr:
  206. # Only save the origin if the origin is not a sha1, and the default
  207. # isn't our value, and the if the default doesn't already have that
  208. # covered.
  209. e.setAttribute('upstream', p.revisionExpr)
  210. elif not d.revisionExpr or p.revisionExpr != d.revisionExpr:
  211. e.setAttribute('revision', p.revisionExpr)
  212. for c in p.copyfiles:
  213. ce = doc.createElement('copyfile')
  214. ce.setAttribute('src', c.src)
  215. ce.setAttribute('dest', c.dest)
  216. e.appendChild(ce)
  217. default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
  218. egroups = [g for g in p.groups if g not in default_groups]
  219. if egroups:
  220. e.setAttribute('groups', ','.join(egroups))
  221. for a in p.annotations:
  222. if a.keep == "true":
  223. ae = doc.createElement('annotation')
  224. ae.setAttribute('name', a.name)
  225. ae.setAttribute('value', a.value)
  226. e.appendChild(ae)
  227. if p.sync_c:
  228. e.setAttribute('sync-c', 'true')
  229. if p.sync_s:
  230. e.setAttribute('sync-s', 'true')
  231. if p.subprojects:
  232. subprojects = set(subp.name for subp in p.subprojects)
  233. output_projects(p, e, list(sorted(subprojects)))
  234. projects = set(p.name for p in self._paths.values() if not p.parent)
  235. output_projects(None, root, list(sorted(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 paths(self):
  246. self._Load()
  247. return self._paths
  248. @property
  249. def projects(self):
  250. self._Load()
  251. return self._paths.values()
  252. @property
  253. def remotes(self):
  254. self._Load()
  255. return self._remotes
  256. @property
  257. def default(self):
  258. self._Load()
  259. return self._default
  260. @property
  261. def repo_hooks_project(self):
  262. self._Load()
  263. return self._repo_hooks_project
  264. @property
  265. def notice(self):
  266. self._Load()
  267. return self._notice
  268. @property
  269. def manifest_server(self):
  270. self._Load()
  271. return self._manifest_server
  272. @property
  273. def IsMirror(self):
  274. return self.manifestProject.config.GetBoolean('repo.mirror')
  275. def _Unload(self):
  276. self._loaded = False
  277. self._projects = {}
  278. self._paths = {}
  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. if self._default is not None:
  370. raise ManifestParseError(
  371. 'duplicate default in %s' %
  372. (self.manifestFile))
  373. self._default = self._ParseDefault(node)
  374. if self._default is None:
  375. self._default = _Default()
  376. for node in itertools.chain(*node_list):
  377. if node.nodeName == 'notice':
  378. if self._notice is not None:
  379. raise ManifestParseError(
  380. 'duplicate notice in %s' %
  381. (self.manifestFile))
  382. self._notice = self._ParseNotice(node)
  383. for node in itertools.chain(*node_list):
  384. if node.nodeName == 'manifest-server':
  385. url = self._reqatt(node, 'url')
  386. if self._manifest_server is not None:
  387. raise ManifestParseError(
  388. 'duplicate manifest-server in %s' %
  389. (self.manifestFile))
  390. self._manifest_server = url
  391. def recursively_add_projects(project):
  392. projects = self._projects.setdefault(project.name, [])
  393. if project.relpath is None:
  394. raise ManifestParseError(
  395. 'missing path for %s in %s' %
  396. (project.name, self.manifestFile))
  397. if project.relpath in self._paths:
  398. raise ManifestParseError(
  399. 'duplicate path %s in %s' %
  400. (project.relpath, self.manifestFile))
  401. self._paths[project.relpath] = project
  402. projects.append(project)
  403. for subproject in project.subprojects:
  404. recursively_add_projects(subproject)
  405. for node in itertools.chain(*node_list):
  406. if node.nodeName == 'project':
  407. project = self._ParseProject(node)
  408. recursively_add_projects(project)
  409. if node.nodeName == 'repo-hooks':
  410. # Get the name of the project and the (space-separated) list of enabled.
  411. repo_hooks_project = self._reqatt(node, 'in-project')
  412. enabled_repo_hooks = self._reqatt(node, 'enabled-list').split()
  413. # Only one project can be the hooks project
  414. if self._repo_hooks_project is not None:
  415. raise ManifestParseError(
  416. 'duplicate repo-hooks in %s' %
  417. (self.manifestFile))
  418. # Store a reference to the Project.
  419. try:
  420. repo_hooks_projects = self._projects[repo_hooks_project]
  421. except KeyError:
  422. raise ManifestParseError(
  423. 'project %s not found for repo-hooks' %
  424. (repo_hooks_project))
  425. if len(repo_hooks_projects) != 1:
  426. raise ManifestParseError(
  427. 'internal error parsing repo-hooks in %s' %
  428. (self.manifestFile))
  429. self._repo_hooks_project = repo_hooks_projects[0]
  430. # Store the enabled hooks in the Project object.
  431. self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
  432. if node.nodeName == 'remove-project':
  433. name = self._reqatt(node, 'name')
  434. try:
  435. del self._projects[name]
  436. except KeyError:
  437. raise ManifestParseError('remove-project element specifies non-existent '
  438. 'project: %s' % name)
  439. # If the manifest removes the hooks project, treat it as if it deleted
  440. # the repo-hooks element too.
  441. if self._repo_hooks_project and (self._repo_hooks_project.name == name):
  442. self._repo_hooks_project = None
  443. def _AddMetaProjectMirror(self, m):
  444. name = None
  445. m_url = m.GetRemote(m.remote.name).url
  446. if m_url.endswith('/.git'):
  447. raise ManifestParseError('refusing to mirror %s' % m_url)
  448. if self._default and self._default.remote:
  449. url = self._default.remote.resolvedFetchUrl
  450. if not url.endswith('/'):
  451. url += '/'
  452. if m_url.startswith(url):
  453. remote = self._default.remote
  454. name = m_url[len(url):]
  455. if name is None:
  456. s = m_url.rindex('/') + 1
  457. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  458. remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
  459. name = m_url[s:]
  460. if name.endswith('.git'):
  461. name = name[:-4]
  462. if name not in self._projects:
  463. m.PreSync()
  464. gitdir = os.path.join(self.topdir, '%s.git' % name)
  465. project = Project(manifest = self,
  466. name = name,
  467. remote = remote.ToRemoteSpec(name),
  468. gitdir = gitdir,
  469. objdir = gitdir,
  470. worktree = None,
  471. relpath = None,
  472. revisionExpr = m.revisionExpr,
  473. revisionId = None)
  474. self._projects[project.name] = [project]
  475. def _ParseRemote(self, node):
  476. """
  477. reads a <remote> element from the manifest file
  478. """
  479. name = self._reqatt(node, 'name')
  480. alias = node.getAttribute('alias')
  481. if alias == '':
  482. alias = None
  483. fetch = self._reqatt(node, 'fetch')
  484. review = node.getAttribute('review')
  485. if review == '':
  486. review = None
  487. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  488. return _XmlRemote(name, alias, fetch, manifestUrl, review)
  489. def _ParseDefault(self, node):
  490. """
  491. reads a <default> element from the manifest file
  492. """
  493. d = _Default()
  494. d.remote = self._get_remote(node)
  495. d.revisionExpr = node.getAttribute('revision')
  496. if d.revisionExpr == '':
  497. d.revisionExpr = None
  498. d.destBranchExpr = node.getAttribute('dest-branch') or None
  499. sync_j = node.getAttribute('sync-j')
  500. if sync_j == '' or sync_j is None:
  501. d.sync_j = 1
  502. else:
  503. d.sync_j = int(sync_j)
  504. sync_c = node.getAttribute('sync-c')
  505. if not sync_c:
  506. d.sync_c = False
  507. else:
  508. d.sync_c = sync_c.lower() in ("yes", "true", "1")
  509. sync_s = node.getAttribute('sync-s')
  510. if not sync_s:
  511. d.sync_s = False
  512. else:
  513. d.sync_s = sync_s.lower() in ("yes", "true", "1")
  514. return d
  515. def _ParseNotice(self, node):
  516. """
  517. reads a <notice> element from the manifest file
  518. The <notice> element is distinct from other tags in the XML in that the
  519. data is conveyed between the start and end tag (it's not an empty-element
  520. tag).
  521. The white space (carriage returns, indentation) for the notice element is
  522. relevant and is parsed in a way that is based on how python docstrings work.
  523. In fact, the code is remarkably similar to here:
  524. http://www.python.org/dev/peps/pep-0257/
  525. """
  526. # Get the data out of the node...
  527. notice = node.childNodes[0].data
  528. # Figure out minimum indentation, skipping the first line (the same line
  529. # as the <notice> tag)...
  530. minIndent = sys.maxsize
  531. lines = notice.splitlines()
  532. for line in lines[1:]:
  533. lstrippedLine = line.lstrip()
  534. if lstrippedLine:
  535. indent = len(line) - len(lstrippedLine)
  536. minIndent = min(indent, minIndent)
  537. # Strip leading / trailing blank lines and also indentation.
  538. cleanLines = [lines[0].strip()]
  539. for line in lines[1:]:
  540. cleanLines.append(line[minIndent:].rstrip())
  541. # Clear completely blank lines from front and back...
  542. while cleanLines and not cleanLines[0]:
  543. del cleanLines[0]
  544. while cleanLines and not cleanLines[-1]:
  545. del cleanLines[-1]
  546. return '\n'.join(cleanLines)
  547. def _JoinName(self, parent_name, name):
  548. return os.path.join(parent_name, name)
  549. def _UnjoinName(self, parent_name, name):
  550. return os.path.relpath(name, parent_name)
  551. def _ParseProject(self, node, parent = None):
  552. """
  553. reads a <project> element from the manifest file
  554. """
  555. name = self._reqatt(node, 'name')
  556. if parent:
  557. name = self._JoinName(parent.name, name)
  558. remote = self._get_remote(node)
  559. if remote is None:
  560. remote = self._default.remote
  561. if remote is None:
  562. raise ManifestParseError("no remote for project %s within %s" %
  563. (name, self.manifestFile))
  564. revisionExpr = node.getAttribute('revision')
  565. if not revisionExpr:
  566. revisionExpr = self._default.revisionExpr
  567. if not revisionExpr:
  568. raise ManifestParseError("no revision for project %s within %s" %
  569. (name, self.manifestFile))
  570. path = node.getAttribute('path')
  571. if not path:
  572. path = name
  573. if path.startswith('/'):
  574. raise ManifestParseError("project %s path cannot be absolute in %s" %
  575. (name, self.manifestFile))
  576. rebase = node.getAttribute('rebase')
  577. if not rebase:
  578. rebase = True
  579. else:
  580. rebase = rebase.lower() in ("yes", "true", "1")
  581. sync_c = node.getAttribute('sync-c')
  582. if not sync_c:
  583. sync_c = False
  584. else:
  585. sync_c = sync_c.lower() in ("yes", "true", "1")
  586. sync_s = node.getAttribute('sync-s')
  587. if not sync_s:
  588. sync_s = self._default.sync_s
  589. else:
  590. sync_s = sync_s.lower() in ("yes", "true", "1")
  591. clone_depth = node.getAttribute('clone-depth')
  592. if clone_depth:
  593. try:
  594. clone_depth = int(clone_depth)
  595. if clone_depth <= 0:
  596. raise ValueError()
  597. except ValueError:
  598. raise ManifestParseError('invalid clone-depth %s in %s' %
  599. (clone_depth, self.manifestFile))
  600. dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
  601. upstream = node.getAttribute('upstream')
  602. groups = ''
  603. if node.hasAttribute('groups'):
  604. groups = node.getAttribute('groups')
  605. groups = [x for x in re.split(r'[,\s]+', groups) if x]
  606. if parent is None:
  607. relpath, worktree, gitdir, objdir = self.GetProjectPaths(name, path)
  608. else:
  609. relpath, worktree, gitdir, objdir = \
  610. self.GetSubprojectPaths(parent, name, path)
  611. default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
  612. groups.extend(set(default_groups).difference(groups))
  613. if self.IsMirror and node.hasAttribute('force-path'):
  614. if node.getAttribute('force-path').lower() in ("yes", "true", "1"):
  615. gitdir = os.path.join(self.topdir, '%s.git' % path)
  616. project = Project(manifest = self,
  617. name = name,
  618. remote = remote.ToRemoteSpec(name),
  619. gitdir = gitdir,
  620. objdir = objdir,
  621. worktree = worktree,
  622. relpath = relpath,
  623. revisionExpr = revisionExpr,
  624. revisionId = None,
  625. rebase = rebase,
  626. groups = groups,
  627. sync_c = sync_c,
  628. sync_s = sync_s,
  629. clone_depth = clone_depth,
  630. upstream = upstream,
  631. parent = parent,
  632. dest_branch = dest_branch)
  633. for n in node.childNodes:
  634. if n.nodeName == 'copyfile':
  635. self._ParseCopyFile(project, n)
  636. if n.nodeName == 'annotation':
  637. self._ParseAnnotation(project, n)
  638. if n.nodeName == 'project':
  639. project.subprojects.append(self._ParseProject(n, parent = project))
  640. return project
  641. def GetProjectPaths(self, name, path):
  642. relpath = path
  643. if self.IsMirror:
  644. worktree = None
  645. gitdir = os.path.join(self.topdir, '%s.git' % name)
  646. objdir = gitdir
  647. else:
  648. worktree = os.path.join(self.topdir, path).replace('\\', '/')
  649. gitdir = os.path.join(self.repodir, 'projects', '%s.git' % path)
  650. objdir = os.path.join(self.repodir, 'project-objects', '%s.git' % name)
  651. return relpath, worktree, gitdir, objdir
  652. def GetProjectsWithName(self, name):
  653. return self._projects.get(name, [])
  654. def GetSubprojectName(self, parent, submodule_path):
  655. return os.path.join(parent.name, submodule_path)
  656. def _JoinRelpath(self, parent_relpath, relpath):
  657. return os.path.join(parent_relpath, relpath)
  658. def _UnjoinRelpath(self, parent_relpath, relpath):
  659. return os.path.relpath(relpath, parent_relpath)
  660. def GetSubprojectPaths(self, parent, name, path):
  661. relpath = self._JoinRelpath(parent.relpath, path)
  662. gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
  663. objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
  664. if self.IsMirror:
  665. worktree = None
  666. else:
  667. worktree = os.path.join(parent.worktree, path).replace('\\', '/')
  668. return relpath, worktree, gitdir, objdir
  669. def _ParseCopyFile(self, project, node):
  670. src = self._reqatt(node, 'src')
  671. dest = self._reqatt(node, 'dest')
  672. if not self.IsMirror:
  673. # src is project relative;
  674. # dest is relative to the top of the tree
  675. project.AddCopyFile(src, dest, os.path.join(self.topdir, dest))
  676. def _ParseAnnotation(self, project, node):
  677. name = self._reqatt(node, 'name')
  678. value = self._reqatt(node, 'value')
  679. try:
  680. keep = self._reqatt(node, 'keep').lower()
  681. except ManifestParseError:
  682. keep = "true"
  683. if keep != "true" and keep != "false":
  684. raise ManifestParseError('optional "keep" attribute must be '
  685. '"true" or "false"')
  686. project.AddAnnotation(name, value, keep)
  687. def _get_remote(self, node):
  688. name = node.getAttribute('remote')
  689. if not name:
  690. return None
  691. v = self._remotes.get(name)
  692. if not v:
  693. raise ManifestParseError("remote %s not defined in %s" %
  694. (name, self.manifestFile))
  695. return v
  696. def _reqatt(self, node, attname):
  697. """
  698. reads a required attribute from the node.
  699. """
  700. v = node.getAttribute(attname)
  701. if not v:
  702. raise ManifestParseError("no %s in <%s> within %s" %
  703. (attname, node.nodeName, self.manifestFile))
  704. return v