manifest_xml.py 29 KB

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