manifest_xml.py 41 KB

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