manifest_xml.py 20 KB

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