manifest_xml.py 16 KB

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