manifest_xml.py 29 KB

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