manifest_xml.py 20 KB

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