manifest_xml.py 33 KB

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