manifest_xml.py 32 KB

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