manifest_xml.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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 _ParseManifestObject(self, path):
  251. root = xml.dom.minidom.parse(path)
  252. if not root or not root.childNodes:
  253. raise ManifestParseError("no root node in %s" % (path,))
  254. config = root.childNodes[0]
  255. if config.nodeName != 'manifest':
  256. raise ManifestParseError("no <manifest> in %s" % (path,))
  257. return config
  258. def _ParseManifest(self, is_root_file):
  259. config = self._ParseManifestObject(self.manifestFile)
  260. for node in config.childNodes:
  261. if node.nodeName == 'include':
  262. name = self._reqatt(node, 'name')
  263. fp = os.path.join(self.manifestProject.worktree, name)
  264. if not os.path.isfile(fp):
  265. raise ManifestParseError, \
  266. "include %s doesn't exist or isn't a file" % \
  267. (name,)
  268. try:
  269. subconfig = self._ParseManifestObject(fp)
  270. # should isolate this to the exact exception, but that's
  271. # tricky. actual parsing implementation may vary.
  272. except (KeyboardInterrupt, RuntimeError, SystemExit):
  273. raise
  274. except Exception, e:
  275. raise ManifestParseError(
  276. "failed parsing included manifest %s: %s", (name, e))
  277. for sub_node in subconfig.childNodes:
  278. config.appendChild(sub_node.cloneNode(True))
  279. for node in config.childNodes:
  280. if node.nodeName == 'remove-project':
  281. name = self._reqatt(node, 'name')
  282. try:
  283. del self._projects[name]
  284. except KeyError:
  285. raise ManifestParseError(
  286. 'project %s not found' %
  287. (name))
  288. # If the manifest removes the hooks project, treat it as if it deleted
  289. # the repo-hooks element too.
  290. if self._repo_hooks_project and (self._repo_hooks_project.name == name):
  291. self._repo_hooks_project = None
  292. for node in config.childNodes:
  293. if node.nodeName == 'remote':
  294. remote = self._ParseRemote(node)
  295. if self._remotes.get(remote.name):
  296. raise ManifestParseError(
  297. 'duplicate remote %s in %s' %
  298. (remote.name, self.manifestFile))
  299. self._remotes[remote.name] = remote
  300. for node in config.childNodes:
  301. if node.nodeName == 'default':
  302. if self._default is not None:
  303. raise ManifestParseError(
  304. 'duplicate default in %s' %
  305. (self.manifestFile))
  306. self._default = self._ParseDefault(node)
  307. if self._default is None:
  308. self._default = _Default()
  309. for node in config.childNodes:
  310. if node.nodeName == 'notice':
  311. if self._notice is not None:
  312. raise ManifestParseError(
  313. 'duplicate notice in %s' %
  314. (self.manifestFile))
  315. self._notice = self._ParseNotice(node)
  316. for node in config.childNodes:
  317. if node.nodeName == 'manifest-server':
  318. url = self._reqatt(node, 'url')
  319. if self._manifest_server is not None:
  320. raise ManifestParseError(
  321. 'duplicate manifest-server in %s' %
  322. (self.manifestFile))
  323. self._manifest_server = url
  324. for node in config.childNodes:
  325. if node.nodeName == 'project':
  326. project = self._ParseProject(node)
  327. if self._projects.get(project.name):
  328. raise ManifestParseError(
  329. 'duplicate project %s in %s' %
  330. (project.name, self.manifestFile))
  331. self._projects[project.name] = project
  332. for node in config.childNodes:
  333. if node.nodeName == 'repo-hooks':
  334. # Get the name of the project and the (space-separated) list of enabled.
  335. repo_hooks_project = self._reqatt(node, 'in-project')
  336. enabled_repo_hooks = self._reqatt(node, 'enabled-list').split()
  337. # Only one project can be the hooks project
  338. if self._repo_hooks_project is not None:
  339. raise ManifestParseError(
  340. 'duplicate repo-hooks in %s' %
  341. (self.manifestFile))
  342. # Store a reference to the Project.
  343. try:
  344. self._repo_hooks_project = self._projects[repo_hooks_project]
  345. except KeyError:
  346. raise ManifestParseError(
  347. 'project %s not found for repo-hooks' %
  348. (repo_hooks_project))
  349. # Store the enabled hooks in the Project object.
  350. self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
  351. def _AddMetaProjectMirror(self, m):
  352. name = None
  353. m_url = m.GetRemote(m.remote.name).url
  354. if m_url.endswith('/.git'):
  355. raise ManifestParseError, 'refusing to mirror %s' % m_url
  356. if self._default and self._default.remote:
  357. url = self._default.remote.resolvedFetchUrl
  358. if not url.endswith('/'):
  359. url += '/'
  360. if m_url.startswith(url):
  361. remote = self._default.remote
  362. name = m_url[len(url):]
  363. if name is None:
  364. s = m_url.rindex('/') + 1
  365. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  366. remote = _XmlRemote('origin', m_url[:s], manifestUrl)
  367. name = m_url[s:]
  368. if name.endswith('.git'):
  369. name = name[:-4]
  370. if name not in self._projects:
  371. m.PreSync()
  372. gitdir = os.path.join(self.topdir, '%s.git' % name)
  373. project = Project(manifest = self,
  374. name = name,
  375. remote = remote.ToRemoteSpec(name),
  376. gitdir = gitdir,
  377. worktree = None,
  378. relpath = None,
  379. revisionExpr = m.revisionExpr,
  380. revisionId = None)
  381. self._projects[project.name] = project
  382. def _ParseRemote(self, node):
  383. """
  384. reads a <remote> element from the manifest file
  385. """
  386. name = self._reqatt(node, 'name')
  387. fetch = self._reqatt(node, 'fetch')
  388. review = node.getAttribute('review')
  389. if review == '':
  390. review = None
  391. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  392. return _XmlRemote(name, fetch, manifestUrl, review)
  393. def _ParseDefault(self, node):
  394. """
  395. reads a <default> element from the manifest file
  396. """
  397. d = _Default()
  398. d.remote = self._get_remote(node)
  399. d.revisionExpr = node.getAttribute('revision')
  400. if d.revisionExpr == '':
  401. d.revisionExpr = None
  402. sync_j = node.getAttribute('sync-j')
  403. if sync_j == '' or sync_j is None:
  404. d.sync_j = 1
  405. else:
  406. d.sync_j = int(sync_j)
  407. sync_c = node.getAttribute('sync-c')
  408. if not sync_c:
  409. d.sync_c = False
  410. else:
  411. d.sync_c = sync_c.lower() in ("yes", "true", "1")
  412. return d
  413. def _ParseNotice(self, node):
  414. """
  415. reads a <notice> element from the manifest file
  416. The <notice> element is distinct from other tags in the XML in that the
  417. data is conveyed between the start and end tag (it's not an empty-element
  418. tag).
  419. The white space (carriage returns, indentation) for the notice element is
  420. relevant and is parsed in a way that is based on how python docstrings work.
  421. In fact, the code is remarkably similar to here:
  422. http://www.python.org/dev/peps/pep-0257/
  423. """
  424. # Get the data out of the node...
  425. notice = node.childNodes[0].data
  426. # Figure out minimum indentation, skipping the first line (the same line
  427. # as the <notice> tag)...
  428. minIndent = sys.maxint
  429. lines = notice.splitlines()
  430. for line in lines[1:]:
  431. lstrippedLine = line.lstrip()
  432. if lstrippedLine:
  433. indent = len(line) - len(lstrippedLine)
  434. minIndent = min(indent, minIndent)
  435. # Strip leading / trailing blank lines and also indentation.
  436. cleanLines = [lines[0].strip()]
  437. for line in lines[1:]:
  438. cleanLines.append(line[minIndent:].rstrip())
  439. # Clear completely blank lines from front and back...
  440. while cleanLines and not cleanLines[0]:
  441. del cleanLines[0]
  442. while cleanLines and not cleanLines[-1]:
  443. del cleanLines[-1]
  444. return '\n'.join(cleanLines)
  445. def _ParseProject(self, node):
  446. """
  447. reads a <project> element from the manifest file
  448. """
  449. name = self._reqatt(node, 'name')
  450. remote = self._get_remote(node)
  451. if remote is None:
  452. remote = self._default.remote
  453. if remote is None:
  454. raise ManifestParseError, \
  455. "no remote for project %s within %s" % \
  456. (name, self.manifestFile)
  457. revisionExpr = node.getAttribute('revision')
  458. if not revisionExpr:
  459. revisionExpr = self._default.revisionExpr
  460. if not revisionExpr:
  461. raise ManifestParseError, \
  462. "no revision for project %s within %s" % \
  463. (name, self.manifestFile)
  464. path = node.getAttribute('path')
  465. if not path:
  466. path = name
  467. if path.startswith('/'):
  468. raise ManifestParseError, \
  469. "project %s path cannot be absolute in %s" % \
  470. (name, self.manifestFile)
  471. rebase = node.getAttribute('rebase')
  472. if not rebase:
  473. rebase = True
  474. else:
  475. rebase = rebase.lower() in ("yes", "true", "1")
  476. sync_c = node.getAttribute('sync-c')
  477. if not sync_c:
  478. sync_c = False
  479. else:
  480. sync_c = sync_c.lower() in ("yes", "true", "1")
  481. groups = ''
  482. if node.hasAttribute('groups'):
  483. groups = node.getAttribute('groups')
  484. groups = [x for x in re.split('[,\s]+', groups) if x]
  485. if 'default' not in groups:
  486. groups.append('default')
  487. if self.IsMirror:
  488. relpath = None
  489. worktree = None
  490. gitdir = os.path.join(self.topdir, '%s.git' % name)
  491. else:
  492. worktree = os.path.join(self.topdir, path).replace('\\', '/')
  493. gitdir = os.path.join(self.repodir, 'projects/%s.git' % path)
  494. project = Project(manifest = self,
  495. name = name,
  496. remote = remote.ToRemoteSpec(name),
  497. gitdir = gitdir,
  498. worktree = worktree,
  499. relpath = path,
  500. revisionExpr = revisionExpr,
  501. revisionId = None,
  502. rebase = rebase,
  503. groups = groups,
  504. sync_c = sync_c)
  505. for n in node.childNodes:
  506. if n.nodeName == 'copyfile':
  507. self._ParseCopyFile(project, n)
  508. if n.nodeName == 'annotation':
  509. self._ParseAnnotation(project, n)
  510. return project
  511. def _ParseCopyFile(self, project, node):
  512. src = self._reqatt(node, 'src')
  513. dest = self._reqatt(node, 'dest')
  514. if not self.IsMirror:
  515. # src is project relative;
  516. # dest is relative to the top of the tree
  517. project.AddCopyFile(src, dest, os.path.join(self.topdir, dest))
  518. def _ParseAnnotation(self, project, node):
  519. name = self._reqatt(node, 'name')
  520. value = self._reqatt(node, 'value')
  521. try:
  522. keep = self._reqatt(node, 'keep').lower()
  523. except ManifestParseError:
  524. keep = "true"
  525. if keep != "true" and keep != "false":
  526. raise ManifestParseError, "optional \"keep\" attribute must be \"true\" or \"false\""
  527. project.AddAnnotation(name, value, keep)
  528. def _get_remote(self, node):
  529. name = node.getAttribute('remote')
  530. if not name:
  531. return None
  532. v = self._remotes.get(name)
  533. if not v:
  534. raise ManifestParseError, \
  535. "remote %s not defined in %s" % \
  536. (name, self.manifestFile)
  537. return v
  538. def _reqatt(self, node, attname):
  539. """
  540. reads a required attribute from the node.
  541. """
  542. v = node.getAttribute(attname)
  543. if not v:
  544. raise ManifestParseError, \
  545. "no %s in <%s> within %s" % \
  546. (attname, node.nodeName, self.manifestFile)
  547. return v