manifest_xml.py 18 KB

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