manifest_xml.py 27 KB

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