manifest_xml.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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. self.manifestProject.worktree))
  241. local = os.path.join(self.repodir, LOCAL_MANIFEST_NAME)
  242. if os.path.exists(local):
  243. nodes.append(self._ParseManifestXml(local, self.repodir))
  244. self._ParseManifest(nodes)
  245. if self.IsMirror:
  246. self._AddMetaProjectMirror(self.repoProject)
  247. self._AddMetaProjectMirror(self.manifestProject)
  248. self._loaded = True
  249. def _ParseManifestXml(self, path, include_root):
  250. root = xml.dom.minidom.parse(path)
  251. if not root or not root.childNodes:
  252. raise ManifestParseError("no root node in %s" % (path,))
  253. config = root.childNodes[0]
  254. if config.nodeName != 'manifest':
  255. raise ManifestParseError("no <manifest> in %s" % (path,))
  256. nodes = []
  257. for node in config.childNodes:
  258. if node.nodeName == 'include':
  259. name = self._reqatt(node, 'name')
  260. fp = os.path.join(include_root, name)
  261. if not os.path.isfile(fp):
  262. raise ManifestParseError, \
  263. "include %s doesn't exist or isn't a file" % \
  264. (name,)
  265. try:
  266. nodes.extend(self._ParseManifestXml(fp, include_root))
  267. # should isolate this to the exact exception, but that's
  268. # tricky. actual parsing implementation may vary.
  269. except (KeyboardInterrupt, RuntimeError, SystemExit):
  270. raise
  271. except Exception, e:
  272. raise ManifestParseError(
  273. "failed parsing included manifest %s: %s", (name, e))
  274. else:
  275. nodes.append(node)
  276. return nodes
  277. def _ParseManifest(self, node_list):
  278. for node in itertools.chain(*node_list):
  279. if node.nodeName == 'remote':
  280. remote = self._ParseRemote(node)
  281. if self._remotes.get(remote.name):
  282. raise ManifestParseError(
  283. 'duplicate remote %s in %s' %
  284. (remote.name, self.manifestFile))
  285. self._remotes[remote.name] = remote
  286. for node in itertools.chain(*node_list):
  287. if node.nodeName == 'default':
  288. if self._default is not None:
  289. raise ManifestParseError(
  290. 'duplicate default in %s' %
  291. (self.manifestFile))
  292. self._default = self._ParseDefault(node)
  293. if self._default is None:
  294. self._default = _Default()
  295. for node in itertools.chain(*node_list):
  296. if node.nodeName == 'notice':
  297. if self._notice is not None:
  298. raise ManifestParseError(
  299. 'duplicate notice in %s' %
  300. (self.manifestFile))
  301. self._notice = self._ParseNotice(node)
  302. for node in itertools.chain(*node_list):
  303. if node.nodeName == 'manifest-server':
  304. url = self._reqatt(node, 'url')
  305. if self._manifest_server is not None:
  306. raise ManifestParseError(
  307. 'duplicate manifest-server in %s' %
  308. (self.manifestFile))
  309. self._manifest_server = url
  310. for node in itertools.chain(*node_list):
  311. if node.nodeName == 'project':
  312. project = self._ParseProject(node)
  313. if self._projects.get(project.name):
  314. raise ManifestParseError(
  315. 'duplicate project %s in %s' %
  316. (project.name, self.manifestFile))
  317. self._projects[project.name] = project
  318. if node.nodeName == 'repo-hooks':
  319. # Get the name of the project and the (space-separated) list of enabled.
  320. repo_hooks_project = self._reqatt(node, 'in-project')
  321. enabled_repo_hooks = self._reqatt(node, 'enabled-list').split()
  322. # Only one project can be the hooks project
  323. if self._repo_hooks_project is not None:
  324. raise ManifestParseError(
  325. 'duplicate repo-hooks in %s' %
  326. (self.manifestFile))
  327. # Store a reference to the Project.
  328. try:
  329. self._repo_hooks_project = self._projects[repo_hooks_project]
  330. except KeyError:
  331. raise ManifestParseError(
  332. 'project %s not found for repo-hooks' %
  333. (repo_hooks_project))
  334. # Store the enabled hooks in the Project object.
  335. self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
  336. if node.nodeName == 'remove-project':
  337. name = self._reqatt(node, 'name')
  338. try:
  339. del self._projects[name]
  340. except KeyError:
  341. raise ManifestParseError(
  342. 'project %s not found' %
  343. (name))
  344. # If the manifest removes the hooks project, treat it as if it deleted
  345. # the repo-hooks element too.
  346. if self._repo_hooks_project and (self._repo_hooks_project.name == name):
  347. self._repo_hooks_project = None
  348. def _AddMetaProjectMirror(self, m):
  349. name = None
  350. m_url = m.GetRemote(m.remote.name).url
  351. if m_url.endswith('/.git'):
  352. raise ManifestParseError, 'refusing to mirror %s' % m_url
  353. if self._default and self._default.remote:
  354. url = self._default.remote.resolvedFetchUrl
  355. if not url.endswith('/'):
  356. url += '/'
  357. if m_url.startswith(url):
  358. remote = self._default.remote
  359. name = m_url[len(url):]
  360. if name is None:
  361. s = m_url.rindex('/') + 1
  362. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  363. remote = _XmlRemote('origin', m_url[:s], manifestUrl)
  364. name = m_url[s:]
  365. if name.endswith('.git'):
  366. name = name[:-4]
  367. if name not in self._projects:
  368. m.PreSync()
  369. gitdir = os.path.join(self.topdir, '%s.git' % name)
  370. project = Project(manifest = self,
  371. name = name,
  372. remote = remote.ToRemoteSpec(name),
  373. gitdir = gitdir,
  374. worktree = None,
  375. relpath = None,
  376. revisionExpr = m.revisionExpr,
  377. revisionId = None)
  378. self._projects[project.name] = project
  379. def _ParseRemote(self, node):
  380. """
  381. reads a <remote> element from the manifest file
  382. """
  383. name = self._reqatt(node, 'name')
  384. fetch = self._reqatt(node, 'fetch')
  385. review = node.getAttribute('review')
  386. if review == '':
  387. review = None
  388. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  389. return _XmlRemote(name, fetch, manifestUrl, review)
  390. def _ParseDefault(self, node):
  391. """
  392. reads a <default> element from the manifest file
  393. """
  394. d = _Default()
  395. d.remote = self._get_remote(node)
  396. d.revisionExpr = node.getAttribute('revision')
  397. if d.revisionExpr == '':
  398. d.revisionExpr = None
  399. sync_j = node.getAttribute('sync-j')
  400. if sync_j == '' or sync_j is None:
  401. d.sync_j = 1
  402. else:
  403. d.sync_j = int(sync_j)
  404. sync_c = node.getAttribute('sync-c')
  405. if not sync_c:
  406. d.sync_c = False
  407. else:
  408. d.sync_c = sync_c.lower() in ("yes", "true", "1")
  409. return d
  410. def _ParseNotice(self, node):
  411. """
  412. reads a <notice> element from the manifest file
  413. The <notice> element is distinct from other tags in the XML in that the
  414. data is conveyed between the start and end tag (it's not an empty-element
  415. tag).
  416. The white space (carriage returns, indentation) for the notice element is
  417. relevant and is parsed in a way that is based on how python docstrings work.
  418. In fact, the code is remarkably similar to here:
  419. http://www.python.org/dev/peps/pep-0257/
  420. """
  421. # Get the data out of the node...
  422. notice = node.childNodes[0].data
  423. # Figure out minimum indentation, skipping the first line (the same line
  424. # as the <notice> tag)...
  425. minIndent = sys.maxint
  426. lines = notice.splitlines()
  427. for line in lines[1:]:
  428. lstrippedLine = line.lstrip()
  429. if lstrippedLine:
  430. indent = len(line) - len(lstrippedLine)
  431. minIndent = min(indent, minIndent)
  432. # Strip leading / trailing blank lines and also indentation.
  433. cleanLines = [lines[0].strip()]
  434. for line in lines[1:]:
  435. cleanLines.append(line[minIndent:].rstrip())
  436. # Clear completely blank lines from front and back...
  437. while cleanLines and not cleanLines[0]:
  438. del cleanLines[0]
  439. while cleanLines and not cleanLines[-1]:
  440. del cleanLines[-1]
  441. return '\n'.join(cleanLines)
  442. def _ParseProject(self, node):
  443. """
  444. reads a <project> element from the manifest file
  445. """
  446. name = self._reqatt(node, 'name')
  447. remote = self._get_remote(node)
  448. if remote is None:
  449. remote = self._default.remote
  450. if remote is None:
  451. raise ManifestParseError, \
  452. "no remote for project %s within %s" % \
  453. (name, self.manifestFile)
  454. revisionExpr = node.getAttribute('revision')
  455. if not revisionExpr:
  456. revisionExpr = self._default.revisionExpr
  457. if not revisionExpr:
  458. raise ManifestParseError, \
  459. "no revision for project %s within %s" % \
  460. (name, self.manifestFile)
  461. path = node.getAttribute('path')
  462. if not path:
  463. path = name
  464. if path.startswith('/'):
  465. raise ManifestParseError, \
  466. "project %s path cannot be absolute in %s" % \
  467. (name, self.manifestFile)
  468. rebase = node.getAttribute('rebase')
  469. if not rebase:
  470. rebase = True
  471. else:
  472. rebase = rebase.lower() in ("yes", "true", "1")
  473. sync_c = node.getAttribute('sync-c')
  474. if not sync_c:
  475. sync_c = False
  476. else:
  477. sync_c = sync_c.lower() in ("yes", "true", "1")
  478. groups = ''
  479. if node.hasAttribute('groups'):
  480. groups = node.getAttribute('groups')
  481. groups = [x for x in re.split('[,\s]+', groups) if x]
  482. if 'default' not in groups:
  483. groups.append('default')
  484. if self.IsMirror:
  485. relpath = None
  486. worktree = None
  487. gitdir = os.path.join(self.topdir, '%s.git' % name)
  488. else:
  489. worktree = os.path.join(self.topdir, path).replace('\\', '/')
  490. gitdir = os.path.join(self.repodir, 'projects/%s.git' % path)
  491. project = Project(manifest = self,
  492. name = name,
  493. remote = remote.ToRemoteSpec(name),
  494. gitdir = gitdir,
  495. worktree = worktree,
  496. relpath = path,
  497. revisionExpr = revisionExpr,
  498. revisionId = None,
  499. rebase = rebase,
  500. groups = groups,
  501. sync_c = sync_c)
  502. for n in node.childNodes:
  503. if n.nodeName == 'copyfile':
  504. self._ParseCopyFile(project, n)
  505. if n.nodeName == 'annotation':
  506. self._ParseAnnotation(project, n)
  507. return project
  508. def _ParseCopyFile(self, project, node):
  509. src = self._reqatt(node, 'src')
  510. dest = self._reqatt(node, 'dest')
  511. if not self.IsMirror:
  512. # src is project relative;
  513. # dest is relative to the top of the tree
  514. project.AddCopyFile(src, dest, os.path.join(self.topdir, dest))
  515. def _ParseAnnotation(self, project, node):
  516. name = self._reqatt(node, 'name')
  517. value = self._reqatt(node, 'value')
  518. try:
  519. keep = self._reqatt(node, 'keep').lower()
  520. except ManifestParseError:
  521. keep = "true"
  522. if keep != "true" and keep != "false":
  523. raise ManifestParseError, "optional \"keep\" attribute must be \"true\" or \"false\""
  524. project.AddAnnotation(name, value, keep)
  525. def _get_remote(self, node):
  526. name = node.getAttribute('remote')
  527. if not name:
  528. return None
  529. v = self._remotes.get(name)
  530. if not v:
  531. raise ManifestParseError, \
  532. "remote %s not defined in %s" % \
  533. (name, self.manifestFile)
  534. return v
  535. def _reqatt(self, node, attname):
  536. """
  537. reads a required attribute from the node.
  538. """
  539. v = node.getAttribute(attname)
  540. if not v:
  541. raise ManifestParseError, \
  542. "no %s in <%s> within %s" % \
  543. (attname, node.nodeName, self.manifestFile)
  544. return v