manifest_xml.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  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. from __future__ import print_function
  16. import itertools
  17. import os
  18. import re
  19. import sys
  20. import xml.dom.minidom
  21. from pyversion import is_python3
  22. if is_python3():
  23. import urllib.parse
  24. else:
  25. import imp
  26. import urlparse
  27. urllib = imp.new_module('urllib')
  28. urllib.parse = urlparse
  29. from git_config import GitConfig
  30. from git_refs import R_HEADS, HEAD
  31. from project import RemoteSpec, Project, MetaProject
  32. from error import ManifestParseError, ManifestInvalidRevisionError
  33. MANIFEST_FILE_NAME = 'manifest.xml'
  34. LOCAL_MANIFEST_NAME = 'local_manifest.xml'
  35. LOCAL_MANIFESTS_DIR_NAME = 'local_manifests'
  36. urllib.parse.uses_relative.extend(['ssh', 'git'])
  37. urllib.parse.uses_netloc.extend(['ssh', 'git'])
  38. class _Default(object):
  39. """Project defaults within the manifest."""
  40. revisionExpr = None
  41. destBranchExpr = None
  42. remote = None
  43. sync_j = 1
  44. sync_c = False
  45. sync_s = False
  46. def __eq__(self, other):
  47. return self.__dict__ == other.__dict__
  48. def __ne__(self, other):
  49. return self.__dict__ != other.__dict__
  50. class _XmlRemote(object):
  51. def __init__(self,
  52. name,
  53. alias=None,
  54. fetch=None,
  55. manifestUrl=None,
  56. review=None,
  57. revision=None,
  58. projecthookName=None,
  59. projecthookRevision=None):
  60. self.name = name
  61. self.fetchUrl = fetch
  62. self.manifestUrl = manifestUrl
  63. self.remoteAlias = alias
  64. self.reviewUrl = review
  65. self.revision = revision
  66. self.resolvedFetchUrl = self._resolveFetchUrl()
  67. self.projecthookName = projecthookName
  68. self.projecthookRevision = projecthookRevision
  69. def __eq__(self, other):
  70. return self.__dict__ == other.__dict__
  71. def __ne__(self, other):
  72. return self.__dict__ != other.__dict__
  73. def _resolveFetchUrl(self):
  74. url = self.fetchUrl.rstrip('/')
  75. manifestUrl = self.manifestUrl.rstrip('/')
  76. # urljoin will gets confused over quite a few things. The ones we care
  77. # about here are:
  78. # * no scheme in the base url, like <hostname:port>
  79. # * persistent-https://
  80. # * rpc://
  81. # We handle this by replacing these with obscure protocols
  82. # and then replacing them with the original when we are done.
  83. # gopher -> <none>
  84. # wais -> persistent-https
  85. # nntp -> rpc
  86. if manifestUrl.find(':') != manifestUrl.find('/') - 1:
  87. manifestUrl = 'gopher://' + manifestUrl
  88. manifestUrl = re.sub(r'^persistent-https://', 'wais://', manifestUrl)
  89. manifestUrl = re.sub(r'^rpc://', 'nntp://', manifestUrl)
  90. url = urllib.parse.urljoin(manifestUrl, url)
  91. url = re.sub(r'^gopher://', '', url)
  92. url = re.sub(r'^wais://', 'persistent-https://', url)
  93. url = re.sub(r'^nntp://', 'rpc://', url)
  94. return url
  95. def ToRemoteSpec(self, projectName):
  96. url = self.resolvedFetchUrl.rstrip('/') + '/' + projectName
  97. remoteName = self.name
  98. if self.remoteAlias:
  99. remoteName = self.remoteAlias
  100. return RemoteSpec(remoteName, url, self.reviewUrl)
  101. class XmlManifest(object):
  102. """manages the repo configuration file"""
  103. def __init__(self, repodir):
  104. self.repodir = os.path.abspath(repodir)
  105. self.topdir = os.path.dirname(self.repodir)
  106. self.manifestFile = os.path.join(self.repodir, MANIFEST_FILE_NAME)
  107. self.globalConfig = GitConfig.ForUser()
  108. self.localManifestWarning = False
  109. self.repoProject = MetaProject(self, 'repo',
  110. gitdir = os.path.join(repodir, 'repo/.git'),
  111. worktree = os.path.join(repodir, 'repo'))
  112. self.manifestProject = MetaProject(self, 'manifests',
  113. gitdir = os.path.join(repodir, 'manifests.git'),
  114. worktree = os.path.join(repodir, 'manifests'))
  115. self._Unload()
  116. def Override(self, name):
  117. """Use a different manifest, just for the current instantiation.
  118. """
  119. path = os.path.join(self.manifestProject.worktree, name)
  120. if not os.path.isfile(path):
  121. raise ManifestParseError('manifest %s not found' % name)
  122. old = self.manifestFile
  123. try:
  124. self.manifestFile = path
  125. self._Unload()
  126. self._Load()
  127. finally:
  128. self.manifestFile = old
  129. def Link(self, name):
  130. """Update the repo metadata to use a different manifest.
  131. """
  132. self.Override(name)
  133. try:
  134. if os.path.lexists(self.manifestFile):
  135. os.remove(self.manifestFile)
  136. os.symlink('manifests/%s' % name, self.manifestFile)
  137. except OSError as e:
  138. raise ManifestParseError('cannot link manifest %s: %s' % (name, str(e)))
  139. def _RemoteToXml(self, r, doc, root):
  140. e = doc.createElement('remote')
  141. root.appendChild(e)
  142. e.setAttribute('name', r.name)
  143. e.setAttribute('fetch', r.fetchUrl)
  144. if r.remoteAlias is not None:
  145. e.setAttribute('alias', r.remoteAlias)
  146. if r.reviewUrl is not None:
  147. e.setAttribute('review', r.reviewUrl)
  148. if r.revision is not None:
  149. e.setAttribute('revision', r.revision)
  150. if r.projecthookName is not None:
  151. ph = doc.createElement('projecthook')
  152. ph.setAttribute('name', r.projecthookName)
  153. ph.setAttribute('revision', r.projecthookRevision)
  154. e.appendChild(ph)
  155. def _ParseGroups(self, groups):
  156. return [x for x in re.split(r'[,\s]+', groups) if x]
  157. def Save(self, fd, peg_rev=False, peg_rev_upstream=True):
  158. """Write the current manifest out to the given file descriptor.
  159. """
  160. mp = self.manifestProject
  161. groups = mp.config.GetString('manifest.groups')
  162. if groups:
  163. groups = self._ParseGroups(groups)
  164. doc = xml.dom.minidom.Document()
  165. root = doc.createElement('manifest')
  166. doc.appendChild(root)
  167. # Save out the notice. There's a little bit of work here to give it the
  168. # right whitespace, which assumes that the notice is automatically indented
  169. # by 4 by minidom.
  170. if self.notice:
  171. notice_element = root.appendChild(doc.createElement('notice'))
  172. notice_lines = self.notice.splitlines()
  173. indented_notice = ('\n'.join(" "*4 + line for line in notice_lines))[4:]
  174. notice_element.appendChild(doc.createTextNode(indented_notice))
  175. d = self.default
  176. for r in sorted(self.remotes):
  177. self._RemoteToXml(self.remotes[r], doc, root)
  178. if self.remotes:
  179. root.appendChild(doc.createTextNode(''))
  180. have_default = False
  181. e = doc.createElement('default')
  182. if d.remote:
  183. have_default = True
  184. e.setAttribute('remote', d.remote.name)
  185. if d.revisionExpr:
  186. have_default = True
  187. e.setAttribute('revision', d.revisionExpr)
  188. if d.sync_j > 1:
  189. have_default = True
  190. e.setAttribute('sync-j', '%d' % d.sync_j)
  191. if d.sync_c:
  192. have_default = True
  193. e.setAttribute('sync-c', 'true')
  194. if d.sync_s:
  195. have_default = True
  196. e.setAttribute('sync-s', 'true')
  197. if have_default:
  198. root.appendChild(e)
  199. root.appendChild(doc.createTextNode(''))
  200. if self._manifest_server:
  201. e = doc.createElement('manifest-server')
  202. e.setAttribute('url', self._manifest_server)
  203. root.appendChild(e)
  204. root.appendChild(doc.createTextNode(''))
  205. def output_projects(parent, parent_node, projects):
  206. for project_name in projects:
  207. for project in self._projects[project_name]:
  208. output_project(parent, parent_node, project)
  209. def output_project(parent, parent_node, p):
  210. if not p.MatchesGroups(groups):
  211. return
  212. name = p.name
  213. relpath = p.relpath
  214. if parent:
  215. name = self._UnjoinName(parent.name, name)
  216. relpath = self._UnjoinRelpath(parent.relpath, relpath)
  217. e = doc.createElement('project')
  218. parent_node.appendChild(e)
  219. e.setAttribute('name', name)
  220. if relpath != name:
  221. e.setAttribute('path', relpath)
  222. remoteName = None
  223. if d.remote:
  224. remoteName = d.remote.remoteAlias or d.remote.name
  225. if not d.remote or p.remote.name != remoteName:
  226. remoteName = p.remote.name
  227. e.setAttribute('remote', remoteName)
  228. if peg_rev:
  229. if self.IsMirror:
  230. value = p.bare_git.rev_parse(p.revisionExpr + '^0')
  231. else:
  232. value = p.work_git.rev_parse(HEAD + '^0')
  233. e.setAttribute('revision', value)
  234. if peg_rev_upstream and value != p.revisionExpr:
  235. # Only save the origin if the origin is not a sha1, and the default
  236. # isn't our value, and the if the default doesn't already have that
  237. # covered.
  238. e.setAttribute('upstream', p.revisionExpr)
  239. else:
  240. revision = self.remotes[remoteName].revision or d.revisionExpr
  241. if not revision or revision != p.revisionExpr:
  242. e.setAttribute('revision', p.revisionExpr)
  243. if p.upstream and p.upstream != p.revisionExpr:
  244. e.setAttribute('upstream', p.upstream)
  245. for c in p.copyfiles:
  246. ce = doc.createElement('copyfile')
  247. ce.setAttribute('src', c.src)
  248. ce.setAttribute('dest', c.dest)
  249. e.appendChild(ce)
  250. for l in p.linkfiles:
  251. le = doc.createElement('linkfile')
  252. le.setAttribute('src', l.src)
  253. le.setAttribute('dest', l.dest)
  254. e.appendChild(le)
  255. default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
  256. egroups = [g for g in p.groups if g not in default_groups]
  257. if egroups:
  258. e.setAttribute('groups', ','.join(egroups))
  259. for a in p.annotations:
  260. if a.keep == "true":
  261. ae = doc.createElement('annotation')
  262. ae.setAttribute('name', a.name)
  263. ae.setAttribute('value', a.value)
  264. e.appendChild(ae)
  265. if p.sync_c:
  266. e.setAttribute('sync-c', 'true')
  267. if p.sync_s:
  268. e.setAttribute('sync-s', 'true')
  269. if p.subprojects:
  270. subprojects = set(subp.name for subp in p.subprojects)
  271. output_projects(p, e, list(sorted(subprojects)))
  272. projects = set(p.name for p in self._paths.values() if not p.parent)
  273. output_projects(None, root, list(sorted(projects)))
  274. if self._repo_hooks_project:
  275. root.appendChild(doc.createTextNode(''))
  276. e = doc.createElement('repo-hooks')
  277. e.setAttribute('in-project', self._repo_hooks_project.name)
  278. e.setAttribute('enabled-list',
  279. ' '.join(self._repo_hooks_project.enabled_repo_hooks))
  280. root.appendChild(e)
  281. doc.writexml(fd, '', ' ', '\n', 'UTF-8')
  282. @property
  283. def paths(self):
  284. self._Load()
  285. return self._paths
  286. @property
  287. def projects(self):
  288. self._Load()
  289. return list(self._paths.values())
  290. @property
  291. def remotes(self):
  292. self._Load()
  293. return self._remotes
  294. @property
  295. def default(self):
  296. self._Load()
  297. return self._default
  298. @property
  299. def repo_hooks_project(self):
  300. self._Load()
  301. return self._repo_hooks_project
  302. @property
  303. def notice(self):
  304. self._Load()
  305. return self._notice
  306. @property
  307. def manifest_server(self):
  308. self._Load()
  309. return self._manifest_server
  310. @property
  311. def IsMirror(self):
  312. return self.manifestProject.config.GetBoolean('repo.mirror')
  313. @property
  314. def IsArchive(self):
  315. return self.manifestProject.config.GetBoolean('repo.archive')
  316. def _Unload(self):
  317. self._loaded = False
  318. self._projects = {}
  319. self._paths = {}
  320. self._remotes = {}
  321. self._default = None
  322. self._repo_hooks_project = None
  323. self._notice = None
  324. self.branch = None
  325. self._manifest_server = None
  326. def _Load(self):
  327. if not self._loaded:
  328. m = self.manifestProject
  329. b = m.GetBranch(m.CurrentBranch).merge
  330. if b is not None and b.startswith(R_HEADS):
  331. b = b[len(R_HEADS):]
  332. self.branch = b
  333. nodes = []
  334. nodes.append(self._ParseManifestXml(self.manifestFile,
  335. self.manifestProject.worktree))
  336. local = os.path.join(self.repodir, LOCAL_MANIFEST_NAME)
  337. if os.path.exists(local):
  338. if not self.localManifestWarning:
  339. self.localManifestWarning = True
  340. print('warning: %s is deprecated; put local manifests in `%s` instead'
  341. % (LOCAL_MANIFEST_NAME, os.path.join(self.repodir, LOCAL_MANIFESTS_DIR_NAME)),
  342. file=sys.stderr)
  343. nodes.append(self._ParseManifestXml(local, self.repodir))
  344. local_dir = os.path.abspath(os.path.join(self.repodir, LOCAL_MANIFESTS_DIR_NAME))
  345. try:
  346. for local_file in sorted(os.listdir(local_dir)):
  347. if local_file.endswith('.xml'):
  348. local = os.path.join(local_dir, local_file)
  349. nodes.append(self._ParseManifestXml(local, self.repodir))
  350. except OSError:
  351. pass
  352. try:
  353. self._ParseManifest(nodes)
  354. except ManifestParseError as e:
  355. # There was a problem parsing, unload ourselves in case they catch
  356. # this error and try again later, we will show the correct error
  357. self._Unload()
  358. raise e
  359. if self.IsMirror:
  360. self._AddMetaProjectMirror(self.repoProject)
  361. self._AddMetaProjectMirror(self.manifestProject)
  362. self._loaded = True
  363. def _ParseManifestXml(self, path, include_root):
  364. try:
  365. root = xml.dom.minidom.parse(path)
  366. except (OSError, xml.parsers.expat.ExpatError) as e:
  367. raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
  368. if not root or not root.childNodes:
  369. raise ManifestParseError("no root node in %s" % (path,))
  370. for manifest in root.childNodes:
  371. if manifest.nodeName == 'manifest':
  372. break
  373. else:
  374. raise ManifestParseError("no <manifest> in %s" % (path,))
  375. nodes = []
  376. for node in manifest.childNodes: # pylint:disable=W0631
  377. # We only get here if manifest is initialised
  378. if node.nodeName == 'include':
  379. name = self._reqatt(node, 'name')
  380. fp = os.path.join(include_root, name)
  381. if not os.path.isfile(fp):
  382. raise ManifestParseError("include %s doesn't exist or isn't a file"
  383. % (name,))
  384. try:
  385. nodes.extend(self._ParseManifestXml(fp, include_root))
  386. # should isolate this to the exact exception, but that's
  387. # tricky. actual parsing implementation may vary.
  388. except (KeyboardInterrupt, RuntimeError, SystemExit):
  389. raise
  390. except Exception as e:
  391. raise ManifestParseError(
  392. "failed parsing included manifest %s: %s", (name, e))
  393. else:
  394. nodes.append(node)
  395. return nodes
  396. def _ParseManifest(self, node_list):
  397. for node in itertools.chain(*node_list):
  398. if node.nodeName == 'remote':
  399. remote = self._ParseRemote(node)
  400. if remote:
  401. if remote.name in self._remotes:
  402. if remote != self._remotes[remote.name]:
  403. raise ManifestParseError(
  404. 'remote %s already exists with different attributes' %
  405. (remote.name))
  406. else:
  407. self._remotes[remote.name] = remote
  408. for node in itertools.chain(*node_list):
  409. if node.nodeName == 'default':
  410. new_default = self._ParseDefault(node)
  411. if self._default is None:
  412. self._default = new_default
  413. elif new_default != self._default:
  414. raise ManifestParseError('duplicate default in %s' %
  415. (self.manifestFile))
  416. if self._default is None:
  417. self._default = _Default()
  418. for node in itertools.chain(*node_list):
  419. if node.nodeName == 'notice':
  420. if self._notice is not None:
  421. raise ManifestParseError(
  422. 'duplicate notice in %s' %
  423. (self.manifestFile))
  424. self._notice = self._ParseNotice(node)
  425. for node in itertools.chain(*node_list):
  426. if node.nodeName == 'manifest-server':
  427. url = self._reqatt(node, 'url')
  428. if self._manifest_server is not None:
  429. raise ManifestParseError(
  430. 'duplicate manifest-server in %s' %
  431. (self.manifestFile))
  432. self._manifest_server = url
  433. def recursively_add_projects(project):
  434. projects = self._projects.setdefault(project.name, [])
  435. if project.relpath is None:
  436. raise ManifestParseError(
  437. 'missing path for %s in %s' %
  438. (project.name, self.manifestFile))
  439. if project.relpath in self._paths:
  440. raise ManifestParseError(
  441. 'duplicate path %s in %s' %
  442. (project.relpath, self.manifestFile))
  443. self._paths[project.relpath] = project
  444. projects.append(project)
  445. for subproject in project.subprojects:
  446. recursively_add_projects(subproject)
  447. for node in itertools.chain(*node_list):
  448. if node.nodeName == 'project':
  449. project = self._ParseProject(node)
  450. recursively_add_projects(project)
  451. if node.nodeName == 'extend-project':
  452. name = self._reqatt(node, 'name')
  453. if name not in self._projects:
  454. raise ManifestParseError('extend-project element specifies non-existent '
  455. 'project: %s' % name)
  456. path = node.getAttribute('path')
  457. groups = node.getAttribute('groups')
  458. if groups:
  459. groups = self._ParseGroups(groups)
  460. for p in self._projects[name]:
  461. if path and p.relpath != path:
  462. continue
  463. if groups:
  464. p.groups.extend(groups)
  465. if node.nodeName == 'repo-hooks':
  466. # Get the name of the project and the (space-separated) list of enabled.
  467. repo_hooks_project = self._reqatt(node, 'in-project')
  468. enabled_repo_hooks = self._reqatt(node, 'enabled-list').split()
  469. # Only one project can be the hooks project
  470. if self._repo_hooks_project is not None:
  471. raise ManifestParseError(
  472. 'duplicate repo-hooks in %s' %
  473. (self.manifestFile))
  474. # Store a reference to the Project.
  475. try:
  476. repo_hooks_projects = self._projects[repo_hooks_project]
  477. except KeyError:
  478. raise ManifestParseError(
  479. 'project %s not found for repo-hooks' %
  480. (repo_hooks_project))
  481. if len(repo_hooks_projects) != 1:
  482. raise ManifestParseError(
  483. 'internal error parsing repo-hooks in %s' %
  484. (self.manifestFile))
  485. self._repo_hooks_project = repo_hooks_projects[0]
  486. # Store the enabled hooks in the Project object.
  487. self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
  488. if node.nodeName == 'remove-project':
  489. name = self._reqatt(node, 'name')
  490. if name not in self._projects:
  491. raise ManifestParseError('remove-project element specifies non-existent '
  492. 'project: %s' % name)
  493. for p in self._projects[name]:
  494. del self._paths[p.relpath]
  495. del self._projects[name]
  496. # If the manifest removes the hooks project, treat it as if it deleted
  497. # the repo-hooks element too.
  498. if self._repo_hooks_project and (self._repo_hooks_project.name == name):
  499. self._repo_hooks_project = None
  500. def _AddMetaProjectMirror(self, m):
  501. name = None
  502. m_url = m.GetRemote(m.remote.name).url
  503. if m_url.endswith('/.git'):
  504. raise ManifestParseError('refusing to mirror %s' % m_url)
  505. if self._default and self._default.remote:
  506. url = self._default.remote.resolvedFetchUrl
  507. if not url.endswith('/'):
  508. url += '/'
  509. if m_url.startswith(url):
  510. remote = self._default.remote
  511. name = m_url[len(url):]
  512. if name is None:
  513. s = m_url.rindex('/') + 1
  514. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  515. remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
  516. name = m_url[s:]
  517. if name.endswith('.git'):
  518. name = name[:-4]
  519. if name not in self._projects:
  520. m.PreSync()
  521. gitdir = os.path.join(self.topdir, '%s.git' % name)
  522. project = Project(manifest = self,
  523. name = name,
  524. remote = remote.ToRemoteSpec(name),
  525. gitdir = gitdir,
  526. objdir = gitdir,
  527. worktree = None,
  528. relpath = name or None,
  529. revisionExpr = m.revisionExpr,
  530. revisionId = None)
  531. self._projects[project.name] = [project]
  532. self._paths[project.relpath] = project
  533. def _ParseRemote(self, node):
  534. """
  535. reads a <remote> element from the manifest file
  536. """
  537. name = self._reqatt(node, 'name')
  538. alias = node.getAttribute('alias')
  539. if alias == '':
  540. alias = None
  541. fetch = self._reqatt(node, 'fetch')
  542. review = node.getAttribute('review')
  543. if review == '':
  544. review = None
  545. revision = node.getAttribute('revision')
  546. if revision == '':
  547. revision = None
  548. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  549. projecthookName = None
  550. projecthookRevision = None
  551. for n in node.childNodes:
  552. if n.nodeName == 'projecthook':
  553. projecthookName, projecthookRevision = self._ParseProjectHooks(n)
  554. break
  555. return _XmlRemote(name, alias, fetch, manifestUrl, review, revision, projecthookName, projecthookRevision)
  556. def _ParseDefault(self, node):
  557. """
  558. reads a <default> element from the manifest file
  559. """
  560. d = _Default()
  561. d.remote = self._get_remote(node)
  562. d.revisionExpr = node.getAttribute('revision')
  563. if d.revisionExpr == '':
  564. d.revisionExpr = None
  565. d.destBranchExpr = node.getAttribute('dest-branch') or None
  566. sync_j = node.getAttribute('sync-j')
  567. if sync_j == '' or sync_j is None:
  568. d.sync_j = 1
  569. else:
  570. d.sync_j = int(sync_j)
  571. sync_c = node.getAttribute('sync-c')
  572. if not sync_c:
  573. d.sync_c = False
  574. else:
  575. d.sync_c = sync_c.lower() in ("yes", "true", "1")
  576. sync_s = node.getAttribute('sync-s')
  577. if not sync_s:
  578. d.sync_s = False
  579. else:
  580. d.sync_s = sync_s.lower() in ("yes", "true", "1")
  581. return d
  582. def _ParseNotice(self, node):
  583. """
  584. reads a <notice> element from the manifest file
  585. The <notice> element is distinct from other tags in the XML in that the
  586. data is conveyed between the start and end tag (it's not an empty-element
  587. tag).
  588. The white space (carriage returns, indentation) for the notice element is
  589. relevant and is parsed in a way that is based on how python docstrings work.
  590. In fact, the code is remarkably similar to here:
  591. http://www.python.org/dev/peps/pep-0257/
  592. """
  593. # Get the data out of the node...
  594. notice = node.childNodes[0].data
  595. # Figure out minimum indentation, skipping the first line (the same line
  596. # as the <notice> tag)...
  597. minIndent = sys.maxsize
  598. lines = notice.splitlines()
  599. for line in lines[1:]:
  600. lstrippedLine = line.lstrip()
  601. if lstrippedLine:
  602. indent = len(line) - len(lstrippedLine)
  603. minIndent = min(indent, minIndent)
  604. # Strip leading / trailing blank lines and also indentation.
  605. cleanLines = [lines[0].strip()]
  606. for line in lines[1:]:
  607. cleanLines.append(line[minIndent:].rstrip())
  608. # Clear completely blank lines from front and back...
  609. while cleanLines and not cleanLines[0]:
  610. del cleanLines[0]
  611. while cleanLines and not cleanLines[-1]:
  612. del cleanLines[-1]
  613. return '\n'.join(cleanLines)
  614. def _JoinName(self, parent_name, name):
  615. return os.path.join(parent_name, name)
  616. def _UnjoinName(self, parent_name, name):
  617. return os.path.relpath(name, parent_name)
  618. def _ParseProject(self, node, parent = None):
  619. """
  620. reads a <project> element from the manifest file
  621. """
  622. name = self._reqatt(node, 'name')
  623. if parent:
  624. name = self._JoinName(parent.name, name)
  625. remote = self._get_remote(node)
  626. if remote is None:
  627. remote = self._default.remote
  628. if remote is None:
  629. raise ManifestParseError("no remote for project %s within %s" %
  630. (name, self.manifestFile))
  631. revisionExpr = node.getAttribute('revision') or remote.revision
  632. if not revisionExpr:
  633. revisionExpr = self._default.revisionExpr
  634. if not revisionExpr:
  635. raise ManifestParseError("no revision for project %s within %s" %
  636. (name, self.manifestFile))
  637. path = node.getAttribute('path')
  638. if not path:
  639. path = name
  640. if path.startswith('/'):
  641. raise ManifestParseError("project %s path cannot be absolute in %s" %
  642. (name, self.manifestFile))
  643. rebase = node.getAttribute('rebase')
  644. if not rebase:
  645. rebase = True
  646. else:
  647. rebase = rebase.lower() in ("yes", "true", "1")
  648. sync_c = node.getAttribute('sync-c')
  649. if not sync_c:
  650. sync_c = False
  651. else:
  652. sync_c = sync_c.lower() in ("yes", "true", "1")
  653. sync_s = node.getAttribute('sync-s')
  654. if not sync_s:
  655. sync_s = self._default.sync_s
  656. else:
  657. sync_s = sync_s.lower() in ("yes", "true", "1")
  658. clone_depth = node.getAttribute('clone-depth')
  659. if clone_depth:
  660. try:
  661. clone_depth = int(clone_depth)
  662. if clone_depth <= 0:
  663. raise ValueError()
  664. except ValueError:
  665. raise ManifestParseError('invalid clone-depth %s in %s' %
  666. (clone_depth, self.manifestFile))
  667. dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
  668. upstream = node.getAttribute('upstream')
  669. groups = ''
  670. if node.hasAttribute('groups'):
  671. groups = node.getAttribute('groups')
  672. groups = self._ParseGroups(groups)
  673. if parent is None:
  674. relpath, worktree, gitdir, objdir = self.GetProjectPaths(name, path)
  675. else:
  676. relpath, worktree, gitdir, objdir = \
  677. self.GetSubprojectPaths(parent, name, path)
  678. default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
  679. groups.extend(set(default_groups).difference(groups))
  680. if self.IsMirror and node.hasAttribute('force-path'):
  681. if node.getAttribute('force-path').lower() in ("yes", "true", "1"):
  682. gitdir = os.path.join(self.topdir, '%s.git' % path)
  683. project = Project(manifest = self,
  684. name = name,
  685. remote = remote.ToRemoteSpec(name),
  686. gitdir = gitdir,
  687. objdir = objdir,
  688. worktree = worktree,
  689. relpath = relpath,
  690. revisionExpr = revisionExpr,
  691. revisionId = None,
  692. rebase = rebase,
  693. groups = groups,
  694. sync_c = sync_c,
  695. sync_s = sync_s,
  696. clone_depth = clone_depth,
  697. upstream = upstream,
  698. parent = parent,
  699. dest_branch = dest_branch)
  700. for n in node.childNodes:
  701. if n.nodeName == 'copyfile':
  702. self._ParseCopyFile(project, n)
  703. if n.nodeName == 'linkfile':
  704. self._ParseLinkFile(project, n)
  705. if n.nodeName == 'annotation':
  706. self._ParseAnnotation(project, n)
  707. if n.nodeName == 'project':
  708. project.subprojects.append(self._ParseProject(n, parent = project))
  709. return project
  710. def GetProjectPaths(self, name, path):
  711. relpath = path
  712. if self.IsMirror:
  713. worktree = None
  714. gitdir = os.path.join(self.topdir, '%s.git' % name)
  715. objdir = gitdir
  716. else:
  717. worktree = os.path.join(self.topdir, path).replace('\\', '/')
  718. gitdir = os.path.join(self.repodir, 'projects', '%s.git' % path)
  719. objdir = os.path.join(self.repodir, 'project-objects', '%s.git' % name)
  720. return relpath, worktree, gitdir, objdir
  721. def GetProjectsWithName(self, name):
  722. return self._projects.get(name, [])
  723. def GetSubprojectName(self, parent, submodule_path):
  724. return os.path.join(parent.name, submodule_path)
  725. def _JoinRelpath(self, parent_relpath, relpath):
  726. return os.path.join(parent_relpath, relpath)
  727. def _UnjoinRelpath(self, parent_relpath, relpath):
  728. return os.path.relpath(relpath, parent_relpath)
  729. def GetSubprojectPaths(self, parent, name, path):
  730. relpath = self._JoinRelpath(parent.relpath, path)
  731. gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
  732. objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
  733. if self.IsMirror:
  734. worktree = None
  735. else:
  736. worktree = os.path.join(parent.worktree, path).replace('\\', '/')
  737. return relpath, worktree, gitdir, objdir
  738. def _ParseCopyFile(self, project, node):
  739. src = self._reqatt(node, 'src')
  740. dest = self._reqatt(node, 'dest')
  741. if not self.IsMirror:
  742. # src is project relative;
  743. # dest is relative to the top of the tree
  744. project.AddCopyFile(src, dest, os.path.join(self.topdir, dest))
  745. def _ParseLinkFile(self, project, node):
  746. src = self._reqatt(node, 'src')
  747. dest = self._reqatt(node, 'dest')
  748. if not self.IsMirror:
  749. # src is project relative;
  750. # dest is relative to the top of the tree
  751. project.AddLinkFile(src, dest, os.path.join(self.topdir, dest))
  752. def _ParseAnnotation(self, project, node):
  753. name = self._reqatt(node, 'name')
  754. value = self._reqatt(node, 'value')
  755. try:
  756. keep = self._reqatt(node, 'keep').lower()
  757. except ManifestParseError:
  758. keep = "true"
  759. if keep != "true" and keep != "false":
  760. raise ManifestParseError('optional "keep" attribute must be '
  761. '"true" or "false"')
  762. project.AddAnnotation(name, value, keep)
  763. def _get_remote(self, node):
  764. name = node.getAttribute('remote')
  765. if not name:
  766. return None
  767. v = self._remotes.get(name)
  768. if not v:
  769. raise ManifestParseError("remote %s not defined in %s" %
  770. (name, self.manifestFile))
  771. return v
  772. def _reqatt(self, node, attname):
  773. """
  774. reads a required attribute from the node.
  775. """
  776. v = node.getAttribute(attname)
  777. if not v:
  778. raise ManifestParseError("no %s in <%s> within %s" %
  779. (attname, node.nodeName, self.manifestFile))
  780. return v
  781. def projectsDiff(self, manifest):
  782. """return the projects differences between two manifests.
  783. The diff will be from self to given manifest.
  784. """
  785. fromProjects = self.paths
  786. toProjects = manifest.paths
  787. fromKeys = sorted(fromProjects.keys())
  788. toKeys = sorted(toProjects.keys())
  789. diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
  790. for proj in fromKeys:
  791. if not proj in toKeys:
  792. diff['removed'].append(fromProjects[proj])
  793. else:
  794. fromProj = fromProjects[proj]
  795. toProj = toProjects[proj]
  796. try:
  797. fromRevId = fromProj.GetCommitRevisionId()
  798. toRevId = toProj.GetCommitRevisionId()
  799. except ManifestInvalidRevisionError:
  800. diff['unreachable'].append((fromProj, toProj))
  801. else:
  802. if fromRevId != toRevId:
  803. diff['changed'].append((fromProj, toProj))
  804. toKeys.remove(proj)
  805. for proj in toKeys:
  806. diff['added'].append(toProjects[proj])
  807. return diff
  808. def _ParseProjectHooks(self, node):
  809. name = self._reqatt(node, 'name')
  810. revision = self._reqatt(node, 'revision')
  811. return name, revision