manifest_xml.py 19 KB

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