manifest_xml.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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. doc.writexml(fd, '', ' ', '\n', 'UTF-8')
  148. @property
  149. def projects(self):
  150. self._Load()
  151. return self._projects
  152. @property
  153. def remotes(self):
  154. self._Load()
  155. return self._remotes
  156. @property
  157. def default(self):
  158. self._Load()
  159. return self._default
  160. @property
  161. def notice(self):
  162. self._Load()
  163. return self._notice
  164. @property
  165. def manifest_server(self):
  166. self._Load()
  167. return self._manifest_server
  168. @property
  169. def IsMirror(self):
  170. return self.manifestProject.config.GetBoolean('repo.mirror')
  171. def _Unload(self):
  172. self._loaded = False
  173. self._projects = {}
  174. self._remotes = {}
  175. self._default = None
  176. self._notice = None
  177. self.branch = None
  178. self._manifest_server = None
  179. def _Load(self):
  180. if not self._loaded:
  181. m = self.manifestProject
  182. b = m.GetBranch(m.CurrentBranch).merge
  183. if b is not None and b.startswith(R_HEADS):
  184. b = b[len(R_HEADS):]
  185. self.branch = b
  186. self._ParseManifest(True)
  187. local = os.path.join(self.repodir, LOCAL_MANIFEST_NAME)
  188. if os.path.exists(local):
  189. try:
  190. real = self.manifestFile
  191. self.manifestFile = local
  192. self._ParseManifest(False)
  193. finally:
  194. self.manifestFile = real
  195. if self.IsMirror:
  196. self._AddMetaProjectMirror(self.repoProject)
  197. self._AddMetaProjectMirror(self.manifestProject)
  198. self._loaded = True
  199. def _ParseManifest(self, is_root_file):
  200. root = xml.dom.minidom.parse(self.manifestFile)
  201. if not root or not root.childNodes:
  202. raise ManifestParseError, \
  203. "no root node in %s" % \
  204. self.manifestFile
  205. config = root.childNodes[0]
  206. if config.nodeName != 'manifest':
  207. raise ManifestParseError, \
  208. "no <manifest> in %s" % \
  209. self.manifestFile
  210. for node in config.childNodes:
  211. if node.nodeName == 'remove-project':
  212. name = self._reqatt(node, 'name')
  213. try:
  214. del self._projects[name]
  215. except KeyError:
  216. raise ManifestParseError, \
  217. 'project %s not found' % \
  218. (name)
  219. for node in config.childNodes:
  220. if node.nodeName == 'remote':
  221. remote = self._ParseRemote(node)
  222. if self._remotes.get(remote.name):
  223. raise ManifestParseError, \
  224. 'duplicate remote %s in %s' % \
  225. (remote.name, self.manifestFile)
  226. self._remotes[remote.name] = remote
  227. for node in config.childNodes:
  228. if node.nodeName == 'default':
  229. if self._default is not None:
  230. raise ManifestParseError, \
  231. 'duplicate default in %s' % \
  232. (self.manifestFile)
  233. self._default = self._ParseDefault(node)
  234. if self._default is None:
  235. self._default = _Default()
  236. for node in config.childNodes:
  237. if node.nodeName == 'notice':
  238. if self._notice is not None:
  239. raise ManifestParseError, \
  240. 'duplicate notice in %s' % \
  241. (self.manifestFile)
  242. self._notice = self._ParseNotice(node)
  243. for node in config.childNodes:
  244. if node.nodeName == 'manifest-server':
  245. url = self._reqatt(node, 'url')
  246. if self._manifest_server is not None:
  247. raise ManifestParseError, \
  248. 'duplicate manifest-server in %s' % \
  249. (self.manifestFile)
  250. self._manifest_server = url
  251. for node in config.childNodes:
  252. if node.nodeName == 'project':
  253. project = self._ParseProject(node)
  254. if self._projects.get(project.name):
  255. raise ManifestParseError, \
  256. 'duplicate project %s in %s' % \
  257. (project.name, self.manifestFile)
  258. self._projects[project.name] = project
  259. def _AddMetaProjectMirror(self, m):
  260. name = None
  261. m_url = m.GetRemote(m.remote.name).url
  262. if m_url.endswith('/.git'):
  263. raise ManifestParseError, 'refusing to mirror %s' % m_url
  264. if self._default and self._default.remote:
  265. url = self._default.remote.fetchUrl
  266. if not url.endswith('/'):
  267. url += '/'
  268. if m_url.startswith(url):
  269. remote = self._default.remote
  270. name = m_url[len(url):]
  271. if name is None:
  272. s = m_url.rindex('/') + 1
  273. remote = _XmlRemote('origin', m_url[:s])
  274. name = m_url[s:]
  275. if name.endswith('.git'):
  276. name = name[:-4]
  277. if name not in self._projects:
  278. m.PreSync()
  279. gitdir = os.path.join(self.topdir, '%s.git' % name)
  280. project = Project(manifest = self,
  281. name = name,
  282. remote = remote.ToRemoteSpec(name),
  283. gitdir = gitdir,
  284. worktree = None,
  285. relpath = None,
  286. revisionExpr = m.revisionExpr,
  287. revisionId = None)
  288. self._projects[project.name] = project
  289. def _ParseRemote(self, node):
  290. """
  291. reads a <remote> element from the manifest file
  292. """
  293. name = self._reqatt(node, 'name')
  294. fetch = self._reqatt(node, 'fetch')
  295. review = node.getAttribute('review')
  296. if review == '':
  297. review = None
  298. return _XmlRemote(name, fetch, review)
  299. def _ParseDefault(self, node):
  300. """
  301. reads a <default> element from the manifest file
  302. """
  303. d = _Default()
  304. d.remote = self._get_remote(node)
  305. d.revisionExpr = node.getAttribute('revision')
  306. if d.revisionExpr == '':
  307. d.revisionExpr = None
  308. return d
  309. def _ParseNotice(self, node):
  310. """
  311. reads a <notice> element from the manifest file
  312. The <notice> element is distinct from other tags in the XML in that the
  313. data is conveyed between the start and end tag (it's not an empty-element
  314. tag).
  315. The white space (carriage returns, indentation) for the notice element is
  316. relevant and is parsed in a way that is based on how python docstrings work.
  317. In fact, the code is remarkably similar to here:
  318. http://www.python.org/dev/peps/pep-0257/
  319. """
  320. # Get the data out of the node...
  321. notice = node.childNodes[0].data
  322. # Figure out minimum indentation, skipping the first line (the same line
  323. # as the <notice> tag)...
  324. minIndent = sys.maxint
  325. lines = notice.splitlines()
  326. for line in lines[1:]:
  327. lstrippedLine = line.lstrip()
  328. if lstrippedLine:
  329. indent = len(line) - len(lstrippedLine)
  330. minIndent = min(indent, minIndent)
  331. # Strip leading / trailing blank lines and also indentation.
  332. cleanLines = [lines[0].strip()]
  333. for line in lines[1:]:
  334. cleanLines.append(line[minIndent:].rstrip())
  335. # Clear completely blank lines from front and back...
  336. while cleanLines and not cleanLines[0]:
  337. del cleanLines[0]
  338. while cleanLines and not cleanLines[-1]:
  339. del cleanLines[-1]
  340. return '\n'.join(cleanLines)
  341. def _ParseProject(self, node):
  342. """
  343. reads a <project> element from the manifest file
  344. """
  345. name = self._reqatt(node, 'name')
  346. remote = self._get_remote(node)
  347. if remote is None:
  348. remote = self._default.remote
  349. if remote is None:
  350. raise ManifestParseError, \
  351. "no remote for project %s within %s" % \
  352. (name, self.manifestFile)
  353. revisionExpr = node.getAttribute('revision')
  354. if not revisionExpr:
  355. revisionExpr = self._default.revisionExpr
  356. if not revisionExpr:
  357. raise ManifestParseError, \
  358. "no revision for project %s within %s" % \
  359. (name, self.manifestFile)
  360. path = node.getAttribute('path')
  361. if not path:
  362. path = name
  363. if path.startswith('/'):
  364. raise ManifestParseError, \
  365. "project %s path cannot be absolute in %s" % \
  366. (name, self.manifestFile)
  367. if self.IsMirror:
  368. relpath = None
  369. worktree = None
  370. gitdir = os.path.join(self.topdir, '%s.git' % name)
  371. else:
  372. worktree = os.path.join(self.topdir, path).replace('\\', '/')
  373. gitdir = os.path.join(self.repodir, 'projects/%s.git' % path)
  374. project = Project(manifest = self,
  375. name = name,
  376. remote = remote.ToRemoteSpec(name),
  377. gitdir = gitdir,
  378. worktree = worktree,
  379. relpath = path,
  380. revisionExpr = revisionExpr,
  381. revisionId = None)
  382. for n in node.childNodes:
  383. if n.nodeName == 'copyfile':
  384. self._ParseCopyFile(project, n)
  385. return project
  386. def _ParseCopyFile(self, project, node):
  387. src = self._reqatt(node, 'src')
  388. dest = self._reqatt(node, 'dest')
  389. if not self.IsMirror:
  390. # src is project relative;
  391. # dest is relative to the top of the tree
  392. project.AddCopyFile(src, dest, os.path.join(self.topdir, dest))
  393. def _get_remote(self, node):
  394. name = node.getAttribute('remote')
  395. if not name:
  396. return None
  397. v = self._remotes.get(name)
  398. if not v:
  399. raise ManifestParseError, \
  400. "remote %s not defined in %s" % \
  401. (name, self.manifestFile)
  402. return v
  403. def _reqatt(self, node, attname):
  404. """
  405. reads a required attribute from the node.
  406. """
  407. v = node.getAttribute(attname)
  408. if not v:
  409. raise ManifestParseError, \
  410. "no %s in <%s> within %s" % \
  411. (attname, node.nodeName, self.manifestFile)
  412. return v