manifest_xml.py 37 KB

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