manifest_xml.py 21 KB

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