manifest_xml.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  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. import itertools
  16. import os
  17. import re
  18. import sys
  19. import urlparse
  20. import xml.dom.minidom
  21. from git_config import GitConfig
  22. from git_refs import R_HEADS, HEAD
  23. from project import RemoteSpec, Project, MetaProject
  24. from error import ManifestParseError
  25. MANIFEST_FILE_NAME = 'manifest.xml'
  26. LOCAL_MANIFEST_NAME = 'local_manifest.xml'
  27. urlparse.uses_relative.extend(['ssh', 'git'])
  28. urlparse.uses_netloc.extend(['ssh', 'git'])
  29. class _Default(object):
  30. """Project defaults within the manifest."""
  31. revisionExpr = None
  32. remote = None
  33. sync_j = 1
  34. sync_c = False
  35. class _XmlRemote(object):
  36. def __init__(self,
  37. name,
  38. alias=None,
  39. fetch=None,
  40. manifestUrl=None,
  41. review=None):
  42. self.name = name
  43. self.fetchUrl = fetch
  44. self.manifestUrl = manifestUrl
  45. self.remoteAlias = alias
  46. self.reviewUrl = review
  47. self.resolvedFetchUrl = self._resolveFetchUrl()
  48. def _resolveFetchUrl(self):
  49. url = self.fetchUrl.rstrip('/')
  50. manifestUrl = self.manifestUrl.rstrip('/')
  51. # urljoin will get confused if there is no scheme in the base url
  52. # ie, if manifestUrl is of the form <hostname:port>
  53. if manifestUrl.find(':') != manifestUrl.find('/') - 1:
  54. manifestUrl = 'gopher://' + manifestUrl
  55. url = urlparse.urljoin(manifestUrl, url)
  56. return re.sub(r'^gopher://', '', url)
  57. def ToRemoteSpec(self, projectName):
  58. url = self.resolvedFetchUrl.rstrip('/') + '/' + projectName
  59. remoteName = self.name
  60. if self.remoteAlias:
  61. remoteName = self.remoteAlias
  62. return RemoteSpec(remoteName, url, self.reviewUrl)
  63. class XmlManifest(object):
  64. """manages the repo configuration file"""
  65. def __init__(self, repodir):
  66. self.repodir = os.path.abspath(repodir)
  67. self.topdir = os.path.dirname(self.repodir)
  68. self.manifestFile = os.path.join(self.repodir, MANIFEST_FILE_NAME)
  69. self.globalConfig = GitConfig.ForUser()
  70. self.repoProject = MetaProject(self, 'repo',
  71. gitdir = os.path.join(repodir, 'repo/.git'),
  72. worktree = os.path.join(repodir, 'repo'))
  73. self.manifestProject = MetaProject(self, 'manifests',
  74. gitdir = os.path.join(repodir, 'manifests.git'),
  75. worktree = os.path.join(repodir, 'manifests'))
  76. self._Unload()
  77. def Override(self, name):
  78. """Use a different manifest, just for the current instantiation.
  79. """
  80. path = os.path.join(self.manifestProject.worktree, name)
  81. if not os.path.isfile(path):
  82. raise ManifestParseError('manifest %s not found' % name)
  83. old = self.manifestFile
  84. try:
  85. self.manifestFile = path
  86. self._Unload()
  87. self._Load()
  88. finally:
  89. self.manifestFile = old
  90. def Link(self, name):
  91. """Update the repo metadata to use a different manifest.
  92. """
  93. self.Override(name)
  94. try:
  95. if os.path.exists(self.manifestFile):
  96. os.remove(self.manifestFile)
  97. os.symlink('manifests/%s' % name, self.manifestFile)
  98. except OSError:
  99. raise ManifestParseError('cannot link manifest %s' % name)
  100. def _RemoteToXml(self, r, doc, root):
  101. e = doc.createElement('remote')
  102. root.appendChild(e)
  103. e.setAttribute('name', r.name)
  104. e.setAttribute('fetch', r.fetchUrl)
  105. if r.reviewUrl is not None:
  106. e.setAttribute('review', r.reviewUrl)
  107. def Save(self, fd, peg_rev=False, peg_rev_upstream=True):
  108. """Write the current manifest out to the given file descriptor.
  109. """
  110. mp = self.manifestProject
  111. groups = mp.config.GetString('manifest.groups')
  112. if not groups:
  113. groups = 'all'
  114. groups = [x for x in re.split(r'[,\s]+', groups) if x]
  115. doc = xml.dom.minidom.Document()
  116. root = doc.createElement('manifest')
  117. doc.appendChild(root)
  118. # Save out the notice. There's a little bit of work here to give it the
  119. # right whitespace, which assumes that the notice is automatically indented
  120. # by 4 by minidom.
  121. if self.notice:
  122. notice_element = root.appendChild(doc.createElement('notice'))
  123. notice_lines = self.notice.splitlines()
  124. indented_notice = ('\n'.join(" "*4 + line for line in notice_lines))[4:]
  125. notice_element.appendChild(doc.createTextNode(indented_notice))
  126. d = self.default
  127. sort_remotes = list(self.remotes.keys())
  128. sort_remotes.sort()
  129. for r in sort_remotes:
  130. self._RemoteToXml(self.remotes[r], doc, root)
  131. if self.remotes:
  132. root.appendChild(doc.createTextNode(''))
  133. have_default = False
  134. e = doc.createElement('default')
  135. if d.remote:
  136. have_default = True
  137. e.setAttribute('remote', d.remote.name)
  138. if d.revisionExpr:
  139. have_default = True
  140. e.setAttribute('revision', d.revisionExpr)
  141. if d.sync_j > 1:
  142. have_default = True
  143. e.setAttribute('sync-j', '%d' % d.sync_j)
  144. if d.sync_c:
  145. have_default = True
  146. e.setAttribute('sync-c', 'true')
  147. if have_default:
  148. root.appendChild(e)
  149. root.appendChild(doc.createTextNode(''))
  150. if self._manifest_server:
  151. e = doc.createElement('manifest-server')
  152. e.setAttribute('url', self._manifest_server)
  153. root.appendChild(e)
  154. root.appendChild(doc.createTextNode(''))
  155. sort_projects = list(self.projects.keys())
  156. sort_projects.sort()
  157. for p in sort_projects:
  158. p = self.projects[p]
  159. if not p.MatchesGroups(groups):
  160. continue
  161. e = doc.createElement('project')
  162. root.appendChild(e)
  163. e.setAttribute('name', p.name)
  164. if p.relpath != p.name:
  165. e.setAttribute('path', p.relpath)
  166. if not d.remote or p.remote.name != d.remote.name:
  167. e.setAttribute('remote', p.remote.name)
  168. if peg_rev:
  169. if self.IsMirror:
  170. value = p.bare_git.rev_parse(p.revisionExpr + '^0')
  171. else:
  172. value = p.work_git.rev_parse(HEAD + '^0')
  173. e.setAttribute('revision', value)
  174. if peg_rev_upstream and value != p.revisionExpr:
  175. # Only save the origin if the origin is not a sha1, and the default
  176. # isn't our value, and the if the default doesn't already have that
  177. # covered.
  178. e.setAttribute('upstream', p.revisionExpr)
  179. elif not d.revisionExpr or p.revisionExpr != d.revisionExpr:
  180. e.setAttribute('revision', p.revisionExpr)
  181. for c in p.copyfiles:
  182. ce = doc.createElement('copyfile')
  183. ce.setAttribute('src', c.src)
  184. ce.setAttribute('dest', c.dest)
  185. e.appendChild(ce)
  186. default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
  187. egroups = [g for g in p.groups if g not in default_groups]
  188. if egroups:
  189. e.setAttribute('groups', ','.join(egroups))
  190. for a in p.annotations:
  191. if a.keep == "true":
  192. ae = doc.createElement('annotation')
  193. ae.setAttribute('name', a.name)
  194. ae.setAttribute('value', a.value)
  195. e.appendChild(ae)
  196. if p.sync_c:
  197. e.setAttribute('sync-c', 'true')
  198. if self._repo_hooks_project:
  199. root.appendChild(doc.createTextNode(''))
  200. e = doc.createElement('repo-hooks')
  201. e.setAttribute('in-project', self._repo_hooks_project.name)
  202. e.setAttribute('enabled-list',
  203. ' '.join(self._repo_hooks_project.enabled_repo_hooks))
  204. root.appendChild(e)
  205. doc.writexml(fd, '', ' ', '\n', 'UTF-8')
  206. @property
  207. def projects(self):
  208. self._Load()
  209. return self._projects
  210. @property
  211. def remotes(self):
  212. self._Load()
  213. return self._remotes
  214. @property
  215. def default(self):
  216. self._Load()
  217. return self._default
  218. @property
  219. def repo_hooks_project(self):
  220. self._Load()
  221. return self._repo_hooks_project
  222. @property
  223. def notice(self):
  224. self._Load()
  225. return self._notice
  226. @property
  227. def manifest_server(self):
  228. self._Load()
  229. return self._manifest_server
  230. @property
  231. def IsMirror(self):
  232. return self.manifestProject.config.GetBoolean('repo.mirror')
  233. def _Unload(self):
  234. self._loaded = False
  235. self._projects = {}
  236. self._remotes = {}
  237. self._default = None
  238. self._repo_hooks_project = None
  239. self._notice = None
  240. self.branch = None
  241. self._manifest_server = None
  242. def _Load(self):
  243. if not self._loaded:
  244. m = self.manifestProject
  245. b = m.GetBranch(m.CurrentBranch).merge
  246. if b is not None and b.startswith(R_HEADS):
  247. b = b[len(R_HEADS):]
  248. self.branch = b
  249. nodes = []
  250. nodes.append(self._ParseManifestXml(self.manifestFile,
  251. self.manifestProject.worktree))
  252. local = os.path.join(self.repodir, LOCAL_MANIFEST_NAME)
  253. if os.path.exists(local):
  254. nodes.append(self._ParseManifestXml(local, self.repodir))
  255. self._ParseManifest(nodes)
  256. if self.IsMirror:
  257. self._AddMetaProjectMirror(self.repoProject)
  258. self._AddMetaProjectMirror(self.manifestProject)
  259. self._loaded = True
  260. def _ParseManifestXml(self, path, include_root):
  261. root = xml.dom.minidom.parse(path)
  262. if not root or not root.childNodes:
  263. raise ManifestParseError("no root node in %s" % (path,))
  264. for manifest in root.childNodes:
  265. if manifest.nodeName == 'manifest':
  266. break
  267. else:
  268. raise ManifestParseError("no <manifest> in %s" % (path,))
  269. nodes = []
  270. for node in manifest.childNodes: # pylint:disable=W0631
  271. # We only get here if manifest is initialised
  272. if node.nodeName == 'include':
  273. name = self._reqatt(node, 'name')
  274. fp = os.path.join(include_root, name)
  275. if not os.path.isfile(fp):
  276. raise ManifestParseError, \
  277. "include %s doesn't exist or isn't a file" % \
  278. (name,)
  279. try:
  280. nodes.extend(self._ParseManifestXml(fp, include_root))
  281. # should isolate this to the exact exception, but that's
  282. # tricky. actual parsing implementation may vary.
  283. except (KeyboardInterrupt, RuntimeError, SystemExit):
  284. raise
  285. except Exception as e:
  286. raise ManifestParseError(
  287. "failed parsing included manifest %s: %s", (name, e))
  288. else:
  289. nodes.append(node)
  290. return nodes
  291. def _ParseManifest(self, node_list):
  292. for node in itertools.chain(*node_list):
  293. if node.nodeName == 'remote':
  294. remote = self._ParseRemote(node)
  295. if self._remotes.get(remote.name):
  296. raise ManifestParseError(
  297. 'duplicate remote %s in %s' %
  298. (remote.name, self.manifestFile))
  299. self._remotes[remote.name] = remote
  300. for node in itertools.chain(*node_list):
  301. if node.nodeName == 'default':
  302. if self._default is not None:
  303. raise ManifestParseError(
  304. 'duplicate default in %s' %
  305. (self.manifestFile))
  306. self._default = self._ParseDefault(node)
  307. if self._default is None:
  308. self._default = _Default()
  309. for node in itertools.chain(*node_list):
  310. if node.nodeName == 'notice':
  311. if self._notice is not None:
  312. raise ManifestParseError(
  313. 'duplicate notice in %s' %
  314. (self.manifestFile))
  315. self._notice = self._ParseNotice(node)
  316. for node in itertools.chain(*node_list):
  317. if node.nodeName == 'manifest-server':
  318. url = self._reqatt(node, 'url')
  319. if self._manifest_server is not None:
  320. raise ManifestParseError(
  321. 'duplicate manifest-server in %s' %
  322. (self.manifestFile))
  323. self._manifest_server = url
  324. for node in itertools.chain(*node_list):
  325. if node.nodeName == 'project':
  326. project = self._ParseProject(node)
  327. if self._projects.get(project.name):
  328. raise ManifestParseError(
  329. 'duplicate project %s in %s' %
  330. (project.name, self.manifestFile))
  331. self._projects[project.name] = project
  332. if node.nodeName == 'repo-hooks':
  333. # Get the name of the project and the (space-separated) list of enabled.
  334. repo_hooks_project = self._reqatt(node, 'in-project')
  335. enabled_repo_hooks = self._reqatt(node, 'enabled-list').split()
  336. # Only one project can be the hooks project
  337. if self._repo_hooks_project is not None:
  338. raise ManifestParseError(
  339. 'duplicate repo-hooks in %s' %
  340. (self.manifestFile))
  341. # Store a reference to the Project.
  342. try:
  343. self._repo_hooks_project = self._projects[repo_hooks_project]
  344. except KeyError:
  345. raise ManifestParseError(
  346. 'project %s not found for repo-hooks' %
  347. (repo_hooks_project))
  348. # Store the enabled hooks in the Project object.
  349. self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
  350. if node.nodeName == 'remove-project':
  351. name = self._reqatt(node, 'name')
  352. try:
  353. del self._projects[name]
  354. except KeyError:
  355. raise ManifestParseError(
  356. 'project %s not found' %
  357. (name))
  358. # If the manifest removes the hooks project, treat it as if it deleted
  359. # the repo-hooks element too.
  360. if self._repo_hooks_project and (self._repo_hooks_project.name == name):
  361. self._repo_hooks_project = None
  362. def _AddMetaProjectMirror(self, m):
  363. name = None
  364. m_url = m.GetRemote(m.remote.name).url
  365. if m_url.endswith('/.git'):
  366. raise ManifestParseError, 'refusing to mirror %s' % m_url
  367. if self._default and self._default.remote:
  368. url = self._default.remote.resolvedFetchUrl
  369. if not url.endswith('/'):
  370. url += '/'
  371. if m_url.startswith(url):
  372. remote = self._default.remote
  373. name = m_url[len(url):]
  374. if name is None:
  375. s = m_url.rindex('/') + 1
  376. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  377. remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
  378. name = m_url[s:]
  379. if name.endswith('.git'):
  380. name = name[:-4]
  381. if name not in self._projects:
  382. m.PreSync()
  383. gitdir = os.path.join(self.topdir, '%s.git' % name)
  384. project = Project(manifest = self,
  385. name = name,
  386. remote = remote.ToRemoteSpec(name),
  387. gitdir = gitdir,
  388. worktree = None,
  389. relpath = None,
  390. revisionExpr = m.revisionExpr,
  391. revisionId = None)
  392. self._projects[project.name] = project
  393. def _ParseRemote(self, node):
  394. """
  395. reads a <remote> element from the manifest file
  396. """
  397. name = self._reqatt(node, 'name')
  398. alias = node.getAttribute('alias')
  399. if alias == '':
  400. alias = None
  401. fetch = self._reqatt(node, 'fetch')
  402. review = node.getAttribute('review')
  403. if review == '':
  404. review = None
  405. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  406. return _XmlRemote(name, alias, fetch, manifestUrl, review)
  407. def _ParseDefault(self, node):
  408. """
  409. reads a <default> element from the manifest file
  410. """
  411. d = _Default()
  412. d.remote = self._get_remote(node)
  413. d.revisionExpr = node.getAttribute('revision')
  414. if d.revisionExpr == '':
  415. d.revisionExpr = None
  416. sync_j = node.getAttribute('sync-j')
  417. if sync_j == '' or sync_j is None:
  418. d.sync_j = 1
  419. else:
  420. d.sync_j = int(sync_j)
  421. sync_c = node.getAttribute('sync-c')
  422. if not sync_c:
  423. d.sync_c = False
  424. else:
  425. d.sync_c = sync_c.lower() in ("yes", "true", "1")
  426. return d
  427. def _ParseNotice(self, node):
  428. """
  429. reads a <notice> element from the manifest file
  430. The <notice> element is distinct from other tags in the XML in that the
  431. data is conveyed between the start and end tag (it's not an empty-element
  432. tag).
  433. The white space (carriage returns, indentation) for the notice element is
  434. relevant and is parsed in a way that is based on how python docstrings work.
  435. In fact, the code is remarkably similar to here:
  436. http://www.python.org/dev/peps/pep-0257/
  437. """
  438. # Get the data out of the node...
  439. notice = node.childNodes[0].data
  440. # Figure out minimum indentation, skipping the first line (the same line
  441. # as the <notice> tag)...
  442. minIndent = sys.maxint
  443. lines = notice.splitlines()
  444. for line in lines[1:]:
  445. lstrippedLine = line.lstrip()
  446. if lstrippedLine:
  447. indent = len(line) - len(lstrippedLine)
  448. minIndent = min(indent, minIndent)
  449. # Strip leading / trailing blank lines and also indentation.
  450. cleanLines = [lines[0].strip()]
  451. for line in lines[1:]:
  452. cleanLines.append(line[minIndent:].rstrip())
  453. # Clear completely blank lines from front and back...
  454. while cleanLines and not cleanLines[0]:
  455. del cleanLines[0]
  456. while cleanLines and not cleanLines[-1]:
  457. del cleanLines[-1]
  458. return '\n'.join(cleanLines)
  459. def _ParseProject(self, node):
  460. """
  461. reads a <project> element from the manifest file
  462. """
  463. name = self._reqatt(node, 'name')
  464. remote = self._get_remote(node)
  465. if remote is None:
  466. remote = self._default.remote
  467. if remote is None:
  468. raise ManifestParseError, \
  469. "no remote for project %s within %s" % \
  470. (name, self.manifestFile)
  471. revisionExpr = node.getAttribute('revision')
  472. if not revisionExpr:
  473. revisionExpr = self._default.revisionExpr
  474. if not revisionExpr:
  475. raise ManifestParseError, \
  476. "no revision for project %s within %s" % \
  477. (name, self.manifestFile)
  478. path = node.getAttribute('path')
  479. if not path:
  480. path = name
  481. if path.startswith('/'):
  482. raise ManifestParseError, \
  483. "project %s path cannot be absolute in %s" % \
  484. (name, self.manifestFile)
  485. rebase = node.getAttribute('rebase')
  486. if not rebase:
  487. rebase = True
  488. else:
  489. rebase = rebase.lower() in ("yes", "true", "1")
  490. sync_c = node.getAttribute('sync-c')
  491. if not sync_c:
  492. sync_c = False
  493. else:
  494. sync_c = sync_c.lower() in ("yes", "true", "1")
  495. upstream = node.getAttribute('upstream')
  496. groups = ''
  497. if node.hasAttribute('groups'):
  498. groups = node.getAttribute('groups')
  499. groups = [x for x in re.split('[,\s]+', groups) if x]
  500. default_groups = ['all', 'name:%s' % name, 'path:%s' % path]
  501. groups.extend(set(default_groups).difference(groups))
  502. if self.IsMirror:
  503. worktree = None
  504. gitdir = os.path.join(self.topdir, '%s.git' % name)
  505. else:
  506. worktree = os.path.join(self.topdir, path).replace('\\', '/')
  507. gitdir = os.path.join(self.repodir, 'projects/%s.git' % path)
  508. project = Project(manifest = self,
  509. name = name,
  510. remote = remote.ToRemoteSpec(name),
  511. gitdir = gitdir,
  512. worktree = worktree,
  513. relpath = path,
  514. revisionExpr = revisionExpr,
  515. revisionId = None,
  516. rebase = rebase,
  517. groups = groups,
  518. sync_c = sync_c,
  519. upstream = upstream)
  520. for n in node.childNodes:
  521. if n.nodeName == 'copyfile':
  522. self._ParseCopyFile(project, n)
  523. if n.nodeName == 'annotation':
  524. self._ParseAnnotation(project, n)
  525. return project
  526. def _ParseCopyFile(self, project, node):
  527. src = self._reqatt(node, 'src')
  528. dest = self._reqatt(node, 'dest')
  529. if not self.IsMirror:
  530. # src is project relative;
  531. # dest is relative to the top of the tree
  532. project.AddCopyFile(src, dest, os.path.join(self.topdir, dest))
  533. def _ParseAnnotation(self, project, node):
  534. name = self._reqatt(node, 'name')
  535. value = self._reqatt(node, 'value')
  536. try:
  537. keep = self._reqatt(node, 'keep').lower()
  538. except ManifestParseError:
  539. keep = "true"
  540. if keep != "true" and keep != "false":
  541. raise ManifestParseError, "optional \"keep\" attribute must be \"true\" or \"false\""
  542. project.AddAnnotation(name, value, keep)
  543. def _get_remote(self, node):
  544. name = node.getAttribute('remote')
  545. if not name:
  546. return None
  547. v = self._remotes.get(name)
  548. if not v:
  549. raise ManifestParseError, \
  550. "remote %s not defined in %s" % \
  551. (name, self.manifestFile)
  552. return v
  553. def _reqatt(self, node, attname):
  554. """
  555. reads a required attribute from the node.
  556. """
  557. v = node.getAttribute(attname)
  558. if not v:
  559. raise ManifestParseError, \
  560. "no %s in <%s> within %s" % \
  561. (attname, node.nodeName, self.manifestFile)
  562. return v