manifest_xml.py 17 KB

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