manifest_xml.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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. if name not in self._projects:
  445. raise ManifestParseError('remove-project element specifies non-existent '
  446. 'project: %s' % name)
  447. for p in self._projects[name]:
  448. del self._paths[p.relpath]
  449. del self._projects[name]
  450. # If the manifest removes the hooks project, treat it as if it deleted
  451. # the repo-hooks element too.
  452. if self._repo_hooks_project and (self._repo_hooks_project.name == name):
  453. self._repo_hooks_project = None
  454. def _AddMetaProjectMirror(self, m):
  455. name = None
  456. m_url = m.GetRemote(m.remote.name).url
  457. if m_url.endswith('/.git'):
  458. raise ManifestParseError('refusing to mirror %s' % m_url)
  459. if self._default and self._default.remote:
  460. url = self._default.remote.resolvedFetchUrl
  461. if not url.endswith('/'):
  462. url += '/'
  463. if m_url.startswith(url):
  464. remote = self._default.remote
  465. name = m_url[len(url):]
  466. if name is None:
  467. s = m_url.rindex('/') + 1
  468. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  469. remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
  470. name = m_url[s:]
  471. if name.endswith('.git'):
  472. name = name[:-4]
  473. if name not in self._projects:
  474. m.PreSync()
  475. gitdir = os.path.join(self.topdir, '%s.git' % name)
  476. project = Project(manifest = self,
  477. name = name,
  478. remote = remote.ToRemoteSpec(name),
  479. gitdir = gitdir,
  480. objdir = gitdir,
  481. worktree = None,
  482. relpath = None,
  483. revisionExpr = m.revisionExpr,
  484. revisionId = None)
  485. self._projects[project.name] = [project]
  486. def _ParseRemote(self, node):
  487. """
  488. reads a <remote> element from the manifest file
  489. """
  490. name = self._reqatt(node, 'name')
  491. alias = node.getAttribute('alias')
  492. if alias == '':
  493. alias = None
  494. fetch = self._reqatt(node, 'fetch')
  495. review = node.getAttribute('review')
  496. if review == '':
  497. review = None
  498. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  499. return _XmlRemote(name, alias, fetch, manifestUrl, review)
  500. def _ParseDefault(self, node):
  501. """
  502. reads a <default> element from the manifest file
  503. """
  504. d = _Default()
  505. d.remote = self._get_remote(node)
  506. d.revisionExpr = node.getAttribute('revision')
  507. if d.revisionExpr == '':
  508. d.revisionExpr = None
  509. d.destBranchExpr = node.getAttribute('dest-branch') or None
  510. sync_j = node.getAttribute('sync-j')
  511. if sync_j == '' or sync_j is None:
  512. d.sync_j = 1
  513. else:
  514. d.sync_j = int(sync_j)
  515. sync_c = node.getAttribute('sync-c')
  516. if not sync_c:
  517. d.sync_c = False
  518. else:
  519. d.sync_c = sync_c.lower() in ("yes", "true", "1")
  520. sync_s = node.getAttribute('sync-s')
  521. if not sync_s:
  522. d.sync_s = False
  523. else:
  524. d.sync_s = sync_s.lower() in ("yes", "true", "1")
  525. return d
  526. def _ParseNotice(self, node):
  527. """
  528. reads a <notice> element from the manifest file
  529. The <notice> element is distinct from other tags in the XML in that the
  530. data is conveyed between the start and end tag (it's not an empty-element
  531. tag).
  532. The white space (carriage returns, indentation) for the notice element is
  533. relevant and is parsed in a way that is based on how python docstrings work.
  534. In fact, the code is remarkably similar to here:
  535. http://www.python.org/dev/peps/pep-0257/
  536. """
  537. # Get the data out of the node...
  538. notice = node.childNodes[0].data
  539. # Figure out minimum indentation, skipping the first line (the same line
  540. # as the <notice> tag)...
  541. minIndent = sys.maxsize
  542. lines = notice.splitlines()
  543. for line in lines[1:]:
  544. lstrippedLine = line.lstrip()
  545. if lstrippedLine:
  546. indent = len(line) - len(lstrippedLine)
  547. minIndent = min(indent, minIndent)
  548. # Strip leading / trailing blank lines and also indentation.
  549. cleanLines = [lines[0].strip()]
  550. for line in lines[1:]:
  551. cleanLines.append(line[minIndent:].rstrip())
  552. # Clear completely blank lines from front and back...
  553. while cleanLines and not cleanLines[0]:
  554. del cleanLines[0]
  555. while cleanLines and not cleanLines[-1]:
  556. del cleanLines[-1]
  557. return '\n'.join(cleanLines)
  558. def _JoinName(self, parent_name, name):
  559. return os.path.join(parent_name, name)
  560. def _UnjoinName(self, parent_name, name):
  561. return os.path.relpath(name, parent_name)
  562. def _ParseProject(self, node, parent = None):
  563. """
  564. reads a <project> element from the manifest file
  565. """
  566. name = self._reqatt(node, 'name')
  567. if parent:
  568. name = self._JoinName(parent.name, name)
  569. remote = self._get_remote(node)
  570. if remote is None:
  571. remote = self._default.remote
  572. if remote is None:
  573. raise ManifestParseError("no remote for project %s within %s" %
  574. (name, self.manifestFile))
  575. revisionExpr = node.getAttribute('revision')
  576. if not revisionExpr:
  577. revisionExpr = self._default.revisionExpr
  578. if not revisionExpr:
  579. raise ManifestParseError("no revision for project %s within %s" %
  580. (name, self.manifestFile))
  581. path = node.getAttribute('path')
  582. if not path:
  583. path = name
  584. if path.startswith('/'):
  585. raise ManifestParseError("project %s path cannot be absolute in %s" %
  586. (name, self.manifestFile))
  587. rebase = node.getAttribute('rebase')
  588. if not rebase:
  589. rebase = True
  590. else:
  591. rebase = rebase.lower() in ("yes", "true", "1")
  592. sync_c = node.getAttribute('sync-c')
  593. if not sync_c:
  594. sync_c = False
  595. else:
  596. sync_c = sync_c.lower() in ("yes", "true", "1")
  597. sync_s = node.getAttribute('sync-s')
  598. if not sync_s:
  599. sync_s = self._default.sync_s
  600. else:
  601. sync_s = sync_s.lower() in ("yes", "true", "1")
  602. clone_depth = node.getAttribute('clone-depth')
  603. if clone_depth:
  604. try:
  605. clone_depth = int(clone_depth)
  606. if clone_depth <= 0:
  607. raise ValueError()
  608. except ValueError:
  609. raise ManifestParseError('invalid clone-depth %s in %s' %
  610. (clone_depth, self.manifestFile))
  611. dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
  612. upstream = node.getAttribute('upstream')
  613. groups = ''
  614. if node.hasAttribute('groups'):
  615. groups = node.getAttribute('groups')
  616. groups = [x for x in re.split(r'[,\s]+', groups) if x]
  617. if parent is None:
  618. relpath, worktree, gitdir, objdir = self.GetProjectPaths(name, path)
  619. else:
  620. relpath, worktree, gitdir, objdir = \
  621. self.GetSubprojectPaths(parent, name, path)
  622. default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
  623. groups.extend(set(default_groups).difference(groups))
  624. if self.IsMirror and node.hasAttribute('force-path'):
  625. if node.getAttribute('force-path').lower() in ("yes", "true", "1"):
  626. gitdir = os.path.join(self.topdir, '%s.git' % path)
  627. project = Project(manifest = self,
  628. name = name,
  629. remote = remote.ToRemoteSpec(name),
  630. gitdir = gitdir,
  631. objdir = objdir,
  632. worktree = worktree,
  633. relpath = relpath,
  634. revisionExpr = revisionExpr,
  635. revisionId = None,
  636. rebase = rebase,
  637. groups = groups,
  638. sync_c = sync_c,
  639. sync_s = sync_s,
  640. clone_depth = clone_depth,
  641. upstream = upstream,
  642. parent = parent,
  643. dest_branch = dest_branch)
  644. for n in node.childNodes:
  645. if n.nodeName == 'copyfile':
  646. self._ParseCopyFile(project, n)
  647. if n.nodeName == 'annotation':
  648. self._ParseAnnotation(project, n)
  649. if n.nodeName == 'project':
  650. project.subprojects.append(self._ParseProject(n, parent = project))
  651. return project
  652. def GetProjectPaths(self, name, path):
  653. relpath = path
  654. if self.IsMirror:
  655. worktree = None
  656. gitdir = os.path.join(self.topdir, '%s.git' % name)
  657. objdir = gitdir
  658. else:
  659. worktree = os.path.join(self.topdir, path).replace('\\', '/')
  660. gitdir = os.path.join(self.repodir, 'projects', '%s.git' % path)
  661. objdir = os.path.join(self.repodir, 'project-objects', '%s.git' % name)
  662. return relpath, worktree, gitdir, objdir
  663. def GetProjectsWithName(self, name):
  664. return self._projects.get(name, [])
  665. def GetSubprojectName(self, parent, submodule_path):
  666. return os.path.join(parent.name, submodule_path)
  667. def _JoinRelpath(self, parent_relpath, relpath):
  668. return os.path.join(parent_relpath, relpath)
  669. def _UnjoinRelpath(self, parent_relpath, relpath):
  670. return os.path.relpath(relpath, parent_relpath)
  671. def GetSubprojectPaths(self, parent, name, path):
  672. relpath = self._JoinRelpath(parent.relpath, path)
  673. gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
  674. objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
  675. if self.IsMirror:
  676. worktree = None
  677. else:
  678. worktree = os.path.join(parent.worktree, path).replace('\\', '/')
  679. return relpath, worktree, gitdir, objdir
  680. def _ParseCopyFile(self, project, node):
  681. src = self._reqatt(node, 'src')
  682. dest = self._reqatt(node, 'dest')
  683. if not self.IsMirror:
  684. # src is project relative;
  685. # dest is relative to the top of the tree
  686. project.AddCopyFile(src, dest, os.path.join(self.topdir, dest))
  687. def _ParseAnnotation(self, project, node):
  688. name = self._reqatt(node, 'name')
  689. value = self._reqatt(node, 'value')
  690. try:
  691. keep = self._reqatt(node, 'keep').lower()
  692. except ManifestParseError:
  693. keep = "true"
  694. if keep != "true" and keep != "false":
  695. raise ManifestParseError('optional "keep" attribute must be '
  696. '"true" or "false"')
  697. project.AddAnnotation(name, value, keep)
  698. def _get_remote(self, node):
  699. name = node.getAttribute('remote')
  700. if not name:
  701. return None
  702. v = self._remotes.get(name)
  703. if not v:
  704. raise ManifestParseError("remote %s not defined in %s" %
  705. (name, self.manifestFile))
  706. return v
  707. def _reqatt(self, node, attname):
  708. """
  709. reads a required attribute from the node.
  710. """
  711. v = node.getAttribute(attname)
  712. if not v:
  713. raise ManifestParseError("no %s in <%s> within %s" %
  714. (attname, node.nodeName, self.manifestFile))
  715. return v