manifest_xml.py 27 KB

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