manifest_xml.py 20 KB

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