manifest_xml.py 15 KB

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