manifest_xml.py 34 KB

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