manifest_xml.py 18 KB

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