manifest_xml.py 32 KB

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