manifest_xml.py 17 KB

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