manifest_xml.py 33 KB

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