manifest_xml.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  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. def _Unload(self):
  335. self._loaded = False
  336. self._projects = {}
  337. self._paths = {}
  338. self._remotes = {}
  339. self._default = None
  340. self._repo_hooks_project = None
  341. self._notice = None
  342. self.branch = None
  343. self._manifest_server = None
  344. def _Load(self):
  345. if not self._loaded:
  346. m = self.manifestProject
  347. b = m.GetBranch(m.CurrentBranch).merge
  348. if b is not None and b.startswith(R_HEADS):
  349. b = b[len(R_HEADS):]
  350. self.branch = b
  351. nodes = []
  352. nodes.append(self._ParseManifestXml(self.manifestFile,
  353. self.manifestProject.worktree))
  354. local = os.path.join(self.repodir, LOCAL_MANIFEST_NAME)
  355. if os.path.exists(local):
  356. if not self.localManifestWarning:
  357. self.localManifestWarning = True
  358. print('warning: %s is deprecated; put local manifests in `%s` instead'
  359. % (LOCAL_MANIFEST_NAME, os.path.join(self.repodir, LOCAL_MANIFESTS_DIR_NAME)),
  360. file=sys.stderr)
  361. nodes.append(self._ParseManifestXml(local, self.repodir))
  362. local_dir = os.path.abspath(os.path.join(self.repodir, LOCAL_MANIFESTS_DIR_NAME))
  363. try:
  364. for local_file in sorted(os.listdir(local_dir)):
  365. if local_file.endswith('.xml'):
  366. local = os.path.join(local_dir, local_file)
  367. nodes.append(self._ParseManifestXml(local, self.repodir))
  368. except OSError:
  369. pass
  370. try:
  371. self._ParseManifest(nodes)
  372. except ManifestParseError as e:
  373. # There was a problem parsing, unload ourselves in case they catch
  374. # this error and try again later, we will show the correct error
  375. self._Unload()
  376. raise e
  377. if self.IsMirror:
  378. self._AddMetaProjectMirror(self.repoProject)
  379. self._AddMetaProjectMirror(self.manifestProject)
  380. self._loaded = True
  381. def _ParseManifestXml(self, path, include_root):
  382. try:
  383. root = xml.dom.minidom.parse(path)
  384. except (OSError, xml.parsers.expat.ExpatError) as e:
  385. raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
  386. if not root or not root.childNodes:
  387. raise ManifestParseError("no root node in %s" % (path,))
  388. for manifest in root.childNodes:
  389. if manifest.nodeName == 'manifest':
  390. break
  391. else:
  392. raise ManifestParseError("no <manifest> in %s" % (path,))
  393. nodes = []
  394. for node in manifest.childNodes: # pylint:disable=W0631
  395. # We only get here if manifest is initialised
  396. if node.nodeName == 'include':
  397. name = self._reqatt(node, 'name')
  398. fp = os.path.join(include_root, name)
  399. if not os.path.isfile(fp):
  400. raise ManifestParseError("include %s doesn't exist or isn't a file"
  401. % (name,))
  402. try:
  403. nodes.extend(self._ParseManifestXml(fp, include_root))
  404. # should isolate this to the exact exception, but that's
  405. # tricky. actual parsing implementation may vary.
  406. except (KeyboardInterrupt, RuntimeError, SystemExit):
  407. raise
  408. except Exception as e:
  409. raise ManifestParseError(
  410. "failed parsing included manifest %s: %s", (name, e))
  411. else:
  412. nodes.append(node)
  413. return nodes
  414. def _ParseManifest(self, node_list):
  415. for node in itertools.chain(*node_list):
  416. if node.nodeName == 'remote':
  417. remote = self._ParseRemote(node)
  418. if remote:
  419. if remote.name in self._remotes:
  420. if remote != self._remotes[remote.name]:
  421. raise ManifestParseError(
  422. 'remote %s already exists with different attributes' %
  423. (remote.name))
  424. else:
  425. self._remotes[remote.name] = remote
  426. for node in itertools.chain(*node_list):
  427. if node.nodeName == 'default':
  428. new_default = self._ParseDefault(node)
  429. if self._default is None:
  430. self._default = new_default
  431. elif new_default != self._default:
  432. raise ManifestParseError('duplicate default in %s' %
  433. (self.manifestFile))
  434. if self._default is None:
  435. self._default = _Default()
  436. for node in itertools.chain(*node_list):
  437. if node.nodeName == 'notice':
  438. if self._notice is not None:
  439. raise ManifestParseError(
  440. 'duplicate notice in %s' %
  441. (self.manifestFile))
  442. self._notice = self._ParseNotice(node)
  443. for node in itertools.chain(*node_list):
  444. if node.nodeName == 'manifest-server':
  445. url = self._reqatt(node, 'url')
  446. if self._manifest_server is not None:
  447. raise ManifestParseError(
  448. 'duplicate manifest-server in %s' %
  449. (self.manifestFile))
  450. self._manifest_server = url
  451. def recursively_add_projects(project):
  452. projects = self._projects.setdefault(project.name, [])
  453. if project.relpath is None:
  454. raise ManifestParseError(
  455. 'missing path for %s in %s' %
  456. (project.name, self.manifestFile))
  457. if project.relpath in self._paths:
  458. raise ManifestParseError(
  459. 'duplicate path %s in %s' %
  460. (project.relpath, self.manifestFile))
  461. self._paths[project.relpath] = project
  462. projects.append(project)
  463. for subproject in project.subprojects:
  464. recursively_add_projects(subproject)
  465. for node in itertools.chain(*node_list):
  466. if node.nodeName == 'project':
  467. project = self._ParseProject(node)
  468. recursively_add_projects(project)
  469. if node.nodeName == 'extend-project':
  470. name = self._reqatt(node, 'name')
  471. if name not in self._projects:
  472. raise ManifestParseError('extend-project element specifies non-existent '
  473. 'project: %s' % name)
  474. path = node.getAttribute('path')
  475. groups = node.getAttribute('groups')
  476. if groups:
  477. groups = self._ParseGroups(groups)
  478. for p in self._projects[name]:
  479. if path and p.relpath != path:
  480. continue
  481. if groups:
  482. p.groups.extend(groups)
  483. if node.nodeName == 'repo-hooks':
  484. # Get the name of the project and the (space-separated) list of enabled.
  485. repo_hooks_project = self._reqatt(node, 'in-project')
  486. enabled_repo_hooks = self._reqatt(node, 'enabled-list').split()
  487. # Only one project can be the hooks project
  488. if self._repo_hooks_project is not None:
  489. raise ManifestParseError(
  490. 'duplicate repo-hooks in %s' %
  491. (self.manifestFile))
  492. # Store a reference to the Project.
  493. try:
  494. repo_hooks_projects = self._projects[repo_hooks_project]
  495. except KeyError:
  496. raise ManifestParseError(
  497. 'project %s not found for repo-hooks' %
  498. (repo_hooks_project))
  499. if len(repo_hooks_projects) != 1:
  500. raise ManifestParseError(
  501. 'internal error parsing repo-hooks in %s' %
  502. (self.manifestFile))
  503. self._repo_hooks_project = repo_hooks_projects[0]
  504. # Store the enabled hooks in the Project object.
  505. self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
  506. if node.nodeName == 'remove-project':
  507. name = self._reqatt(node, 'name')
  508. if name not in self._projects:
  509. raise ManifestParseError('remove-project element specifies non-existent '
  510. 'project: %s' % name)
  511. for p in self._projects[name]:
  512. del self._paths[p.relpath]
  513. del self._projects[name]
  514. # If the manifest removes the hooks project, treat it as if it deleted
  515. # the repo-hooks element too.
  516. if self._repo_hooks_project and (self._repo_hooks_project.name == name):
  517. self._repo_hooks_project = None
  518. def _AddMetaProjectMirror(self, m):
  519. name = None
  520. m_url = m.GetRemote(m.remote.name).url
  521. if m_url.endswith('/.git'):
  522. raise ManifestParseError('refusing to mirror %s' % m_url)
  523. if self._default and self._default.remote:
  524. url = self._default.remote.resolvedFetchUrl
  525. if not url.endswith('/'):
  526. url += '/'
  527. if m_url.startswith(url):
  528. remote = self._default.remote
  529. name = m_url[len(url):]
  530. if name is None:
  531. s = m_url.rindex('/') + 1
  532. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  533. remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
  534. name = m_url[s:]
  535. if name.endswith('.git'):
  536. name = name[:-4]
  537. if name not in self._projects:
  538. m.PreSync()
  539. gitdir = os.path.join(self.topdir, '%s.git' % name)
  540. project = Project(manifest = self,
  541. name = name,
  542. remote = remote.ToRemoteSpec(name),
  543. gitdir = gitdir,
  544. objdir = gitdir,
  545. worktree = None,
  546. relpath = name or None,
  547. revisionExpr = m.revisionExpr,
  548. revisionId = None)
  549. self._projects[project.name] = [project]
  550. self._paths[project.relpath] = project
  551. def _ParseRemote(self, node):
  552. """
  553. reads a <remote> element from the manifest file
  554. """
  555. name = self._reqatt(node, 'name')
  556. alias = node.getAttribute('alias')
  557. if alias == '':
  558. alias = None
  559. fetch = self._reqatt(node, 'fetch')
  560. pushUrl = node.getAttribute('pushurl')
  561. if pushUrl == '':
  562. pushUrl = None
  563. review = node.getAttribute('review')
  564. if review == '':
  565. review = None
  566. revision = node.getAttribute('revision')
  567. if revision == '':
  568. revision = None
  569. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  570. return _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
  571. def _ParseDefault(self, node):
  572. """
  573. reads a <default> element from the manifest file
  574. """
  575. d = _Default()
  576. d.remote = self._get_remote(node)
  577. d.revisionExpr = node.getAttribute('revision')
  578. if d.revisionExpr == '':
  579. d.revisionExpr = None
  580. d.destBranchExpr = node.getAttribute('dest-branch') or None
  581. sync_j = node.getAttribute('sync-j')
  582. if sync_j == '' or sync_j is None:
  583. d.sync_j = 1
  584. else:
  585. d.sync_j = int(sync_j)
  586. sync_c = node.getAttribute('sync-c')
  587. if not sync_c:
  588. d.sync_c = False
  589. else:
  590. d.sync_c = sync_c.lower() in ("yes", "true", "1")
  591. sync_s = node.getAttribute('sync-s')
  592. if not sync_s:
  593. d.sync_s = False
  594. else:
  595. d.sync_s = sync_s.lower() in ("yes", "true", "1")
  596. return d
  597. def _ParseNotice(self, node):
  598. """
  599. reads a <notice> element from the manifest file
  600. The <notice> element is distinct from other tags in the XML in that the
  601. data is conveyed between the start and end tag (it's not an empty-element
  602. tag).
  603. The white space (carriage returns, indentation) for the notice element is
  604. relevant and is parsed in a way that is based on how python docstrings work.
  605. In fact, the code is remarkably similar to here:
  606. http://www.python.org/dev/peps/pep-0257/
  607. """
  608. # Get the data out of the node...
  609. notice = node.childNodes[0].data
  610. # Figure out minimum indentation, skipping the first line (the same line
  611. # as the <notice> tag)...
  612. minIndent = sys.maxsize
  613. lines = notice.splitlines()
  614. for line in lines[1:]:
  615. lstrippedLine = line.lstrip()
  616. if lstrippedLine:
  617. indent = len(line) - len(lstrippedLine)
  618. minIndent = min(indent, minIndent)
  619. # Strip leading / trailing blank lines and also indentation.
  620. cleanLines = [lines[0].strip()]
  621. for line in lines[1:]:
  622. cleanLines.append(line[minIndent:].rstrip())
  623. # Clear completely blank lines from front and back...
  624. while cleanLines and not cleanLines[0]:
  625. del cleanLines[0]
  626. while cleanLines and not cleanLines[-1]:
  627. del cleanLines[-1]
  628. return '\n'.join(cleanLines)
  629. def _JoinName(self, parent_name, name):
  630. return os.path.join(parent_name, name)
  631. def _UnjoinName(self, parent_name, name):
  632. return os.path.relpath(name, parent_name)
  633. def _ParseProject(self, node, parent = None, **extra_proj_attrs):
  634. """
  635. reads a <project> element from the manifest file
  636. """
  637. name = self._reqatt(node, 'name')
  638. if parent:
  639. name = self._JoinName(parent.name, name)
  640. remote = self._get_remote(node)
  641. if remote is None:
  642. remote = self._default.remote
  643. if remote is None:
  644. raise ManifestParseError("no remote for project %s within %s" %
  645. (name, self.manifestFile))
  646. revisionExpr = node.getAttribute('revision') or remote.revision
  647. if not revisionExpr:
  648. revisionExpr = self._default.revisionExpr
  649. if not revisionExpr:
  650. raise ManifestParseError("no revision for project %s within %s" %
  651. (name, self.manifestFile))
  652. path = node.getAttribute('path')
  653. if not path:
  654. path = name
  655. if path.startswith('/'):
  656. raise ManifestParseError("project %s path cannot be absolute in %s" %
  657. (name, self.manifestFile))
  658. rebase = node.getAttribute('rebase')
  659. if not rebase:
  660. rebase = True
  661. else:
  662. rebase = rebase.lower() in ("yes", "true", "1")
  663. sync_c = node.getAttribute('sync-c')
  664. if not sync_c:
  665. sync_c = False
  666. else:
  667. sync_c = sync_c.lower() in ("yes", "true", "1")
  668. sync_s = node.getAttribute('sync-s')
  669. if not sync_s:
  670. sync_s = self._default.sync_s
  671. else:
  672. sync_s = sync_s.lower() in ("yes", "true", "1")
  673. clone_depth = node.getAttribute('clone-depth')
  674. if clone_depth:
  675. try:
  676. clone_depth = int(clone_depth)
  677. if clone_depth <= 0:
  678. raise ValueError()
  679. except ValueError:
  680. raise ManifestParseError('invalid clone-depth %s in %s' %
  681. (clone_depth, self.manifestFile))
  682. dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
  683. upstream = node.getAttribute('upstream')
  684. groups = ''
  685. if node.hasAttribute('groups'):
  686. groups = node.getAttribute('groups')
  687. groups = self._ParseGroups(groups)
  688. if parent is None:
  689. relpath, worktree, gitdir, objdir = self.GetProjectPaths(name, path)
  690. else:
  691. relpath, worktree, gitdir, objdir = \
  692. self.GetSubprojectPaths(parent, name, path)
  693. default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
  694. groups.extend(set(default_groups).difference(groups))
  695. if self.IsMirror and node.hasAttribute('force-path'):
  696. if node.getAttribute('force-path').lower() in ("yes", "true", "1"):
  697. gitdir = os.path.join(self.topdir, '%s.git' % path)
  698. project = Project(manifest = self,
  699. name = name,
  700. remote = remote.ToRemoteSpec(name),
  701. gitdir = gitdir,
  702. objdir = objdir,
  703. worktree = worktree,
  704. relpath = relpath,
  705. revisionExpr = revisionExpr,
  706. revisionId = None,
  707. rebase = rebase,
  708. groups = groups,
  709. sync_c = sync_c,
  710. sync_s = sync_s,
  711. clone_depth = clone_depth,
  712. upstream = upstream,
  713. parent = parent,
  714. dest_branch = dest_branch,
  715. **extra_proj_attrs)
  716. for n in node.childNodes:
  717. if n.nodeName == 'copyfile':
  718. self._ParseCopyFile(project, n)
  719. if n.nodeName == 'linkfile':
  720. self._ParseLinkFile(project, n)
  721. if n.nodeName == 'annotation':
  722. self._ParseAnnotation(project, n)
  723. if n.nodeName == 'project':
  724. project.subprojects.append(self._ParseProject(n, parent = project))
  725. return project
  726. def GetProjectPaths(self, name, path):
  727. relpath = path
  728. if self.IsMirror:
  729. worktree = None
  730. gitdir = os.path.join(self.topdir, '%s.git' % name)
  731. objdir = gitdir
  732. else:
  733. worktree = os.path.join(self.topdir, path).replace('\\', '/')
  734. gitdir = os.path.join(self.repodir, 'projects', '%s.git' % path)
  735. objdir = os.path.join(self.repodir, 'project-objects', '%s.git' % name)
  736. return relpath, worktree, gitdir, objdir
  737. def GetProjectsWithName(self, name):
  738. return self._projects.get(name, [])
  739. def GetSubprojectName(self, parent, submodule_path):
  740. return os.path.join(parent.name, submodule_path)
  741. def _JoinRelpath(self, parent_relpath, relpath):
  742. return os.path.join(parent_relpath, relpath)
  743. def _UnjoinRelpath(self, parent_relpath, relpath):
  744. return os.path.relpath(relpath, parent_relpath)
  745. def GetSubprojectPaths(self, parent, name, path):
  746. relpath = self._JoinRelpath(parent.relpath, path)
  747. gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
  748. objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
  749. if self.IsMirror:
  750. worktree = None
  751. else:
  752. worktree = os.path.join(parent.worktree, path).replace('\\', '/')
  753. return relpath, worktree, gitdir, objdir
  754. def _ParseCopyFile(self, project, node):
  755. src = self._reqatt(node, 'src')
  756. dest = self._reqatt(node, 'dest')
  757. if not self.IsMirror:
  758. # src is project relative;
  759. # dest is relative to the top of the tree
  760. project.AddCopyFile(src, dest, os.path.join(self.topdir, dest))
  761. def _ParseLinkFile(self, project, node):
  762. src = self._reqatt(node, 'src')
  763. dest = self._reqatt(node, 'dest')
  764. if not self.IsMirror:
  765. # src is project relative;
  766. # dest is relative to the top of the tree
  767. project.AddLinkFile(src, dest, os.path.join(self.topdir, dest))
  768. def _ParseAnnotation(self, project, node):
  769. name = self._reqatt(node, 'name')
  770. value = self._reqatt(node, 'value')
  771. try:
  772. keep = self._reqatt(node, 'keep').lower()
  773. except ManifestParseError:
  774. keep = "true"
  775. if keep != "true" and keep != "false":
  776. raise ManifestParseError('optional "keep" attribute must be '
  777. '"true" or "false"')
  778. project.AddAnnotation(name, value, keep)
  779. def _get_remote(self, node):
  780. name = node.getAttribute('remote')
  781. if not name:
  782. return None
  783. v = self._remotes.get(name)
  784. if not v:
  785. raise ManifestParseError("remote %s not defined in %s" %
  786. (name, self.manifestFile))
  787. return v
  788. def _reqatt(self, node, attname):
  789. """
  790. reads a required attribute from the node.
  791. """
  792. v = node.getAttribute(attname)
  793. if not v:
  794. raise ManifestParseError("no %s in <%s> within %s" %
  795. (attname, node.nodeName, self.manifestFile))
  796. return v
  797. def projectsDiff(self, manifest):
  798. """return the projects differences between two manifests.
  799. The diff will be from self to given manifest.
  800. """
  801. fromProjects = self.paths
  802. toProjects = manifest.paths
  803. fromKeys = sorted(fromProjects.keys())
  804. toKeys = sorted(toProjects.keys())
  805. diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
  806. for proj in fromKeys:
  807. if not proj in toKeys:
  808. diff['removed'].append(fromProjects[proj])
  809. else:
  810. fromProj = fromProjects[proj]
  811. toProj = toProjects[proj]
  812. try:
  813. fromRevId = fromProj.GetCommitRevisionId()
  814. toRevId = toProj.GetCommitRevisionId()
  815. except ManifestInvalidRevisionError:
  816. diff['unreachable'].append((fromProj, toProj))
  817. else:
  818. if fromRevId != toRevId:
  819. diff['changed'].append((fromProj, toProj))
  820. toKeys.remove(proj)
  821. for proj in toKeys:
  822. diff['added'].append(toProjects[proj])
  823. return diff
  824. class GitcManifest(XmlManifest):
  825. def __init__(self, repodir, gitc_client_name):
  826. """Initialize the GitcManifest object."""
  827. super(GitcManifest, self).__init__(repodir)
  828. self.isGitcClient = True
  829. self.gitc_client_name = gitc_client_name
  830. self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
  831. gitc_client_name)
  832. self.manifestFile = os.path.join(self.gitc_client_dir, '.manifest')
  833. def _ParseProject(self, node, parent = None):
  834. """Override _ParseProject and add support for GITC specific attributes."""
  835. return super(GitcManifest, self)._ParseProject(
  836. node, parent=parent, old_revision=node.getAttribute('old-revision'))
  837. def _output_manifest_project_extras(self, p, e):
  838. """Output GITC Specific Project attributes"""
  839. if p.old_revision:
  840. e.setAttribute('old-revision', str(p.old_revision))