manifest_xml.py 19 KB

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