manifest_xml.py 16 KB

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