manifest_xml.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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 CloneFilter(self):
  424. if self.manifestProject.config.GetBoolean('repo.partialclone'):
  425. return self.manifestProject.config.GetString('repo.clonefilter')
  426. return None
  427. @property
  428. def IsMirror(self):
  429. return self.manifestProject.config.GetBoolean('repo.mirror')
  430. @property
  431. def UseGitWorktrees(self):
  432. return self.manifestProject.config.GetBoolean('repo.worktree')
  433. @property
  434. def IsArchive(self):
  435. return self.manifestProject.config.GetBoolean('repo.archive')
  436. @property
  437. def HasSubmodules(self):
  438. return self.manifestProject.config.GetBoolean('repo.submodules')
  439. def _Unload(self):
  440. self._loaded = False
  441. self._projects = {}
  442. self._paths = {}
  443. self._remotes = {}
  444. self._default = None
  445. self._repo_hooks_project = None
  446. self._notice = None
  447. self.branch = None
  448. self._manifest_server = None
  449. def _Load(self):
  450. if not self._loaded:
  451. m = self.manifestProject
  452. b = m.GetBranch(m.CurrentBranch).merge
  453. if b is not None and b.startswith(R_HEADS):
  454. b = b[len(R_HEADS):]
  455. self.branch = b
  456. nodes = []
  457. nodes.append(self._ParseManifestXml(self.manifestFile,
  458. self.manifestProject.worktree))
  459. if self._load_local_manifests:
  460. local = os.path.join(self.repodir, LOCAL_MANIFEST_NAME)
  461. if os.path.exists(local):
  462. if not self.localManifestWarning:
  463. self.localManifestWarning = True
  464. print('warning: %s is deprecated; put local manifests '
  465. 'in `%s` instead' % (LOCAL_MANIFEST_NAME,
  466. os.path.join(self.repodir, LOCAL_MANIFESTS_DIR_NAME)),
  467. file=sys.stderr)
  468. nodes.append(self._ParseManifestXml(local, self.repodir))
  469. local_dir = os.path.abspath(os.path.join(self.repodir,
  470. LOCAL_MANIFESTS_DIR_NAME))
  471. try:
  472. for local_file in sorted(platform_utils.listdir(local_dir)):
  473. if local_file.endswith('.xml'):
  474. local = os.path.join(local_dir, local_file)
  475. nodes.append(self._ParseManifestXml(local, self.repodir))
  476. except OSError:
  477. pass
  478. try:
  479. self._ParseManifest(nodes)
  480. except ManifestParseError as e:
  481. # There was a problem parsing, unload ourselves in case they catch
  482. # this error and try again later, we will show the correct error
  483. self._Unload()
  484. raise e
  485. if self.IsMirror:
  486. self._AddMetaProjectMirror(self.repoProject)
  487. self._AddMetaProjectMirror(self.manifestProject)
  488. self._loaded = True
  489. def _ParseManifestXml(self, path, include_root):
  490. try:
  491. root = xml.dom.minidom.parse(path)
  492. except (OSError, xml.parsers.expat.ExpatError) as e:
  493. raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
  494. if not root or not root.childNodes:
  495. raise ManifestParseError("no root node in %s" % (path,))
  496. for manifest in root.childNodes:
  497. if manifest.nodeName == 'manifest':
  498. break
  499. else:
  500. raise ManifestParseError("no <manifest> in %s" % (path,))
  501. nodes = []
  502. for node in manifest.childNodes:
  503. if node.nodeName == 'include':
  504. name = self._reqatt(node, 'name')
  505. fp = os.path.join(include_root, name)
  506. if not os.path.isfile(fp):
  507. raise ManifestParseError("include %s doesn't exist or isn't a file"
  508. % (name,))
  509. try:
  510. nodes.extend(self._ParseManifestXml(fp, include_root))
  511. # should isolate this to the exact exception, but that's
  512. # tricky. actual parsing implementation may vary.
  513. except (KeyboardInterrupt, RuntimeError, SystemExit):
  514. raise
  515. except Exception as e:
  516. raise ManifestParseError(
  517. "failed parsing included manifest %s: %s" % (name, e))
  518. else:
  519. nodes.append(node)
  520. return nodes
  521. def _ParseManifest(self, node_list):
  522. for node in itertools.chain(*node_list):
  523. if node.nodeName == 'remote':
  524. remote = self._ParseRemote(node)
  525. if remote:
  526. if remote.name in self._remotes:
  527. if remote != self._remotes[remote.name]:
  528. raise ManifestParseError(
  529. 'remote %s already exists with different attributes' %
  530. (remote.name))
  531. else:
  532. self._remotes[remote.name] = remote
  533. for node in itertools.chain(*node_list):
  534. if node.nodeName == 'default':
  535. new_default = self._ParseDefault(node)
  536. if self._default is None:
  537. self._default = new_default
  538. elif new_default != self._default:
  539. raise ManifestParseError('duplicate default in %s' %
  540. (self.manifestFile))
  541. if self._default is None:
  542. self._default = _Default()
  543. for node in itertools.chain(*node_list):
  544. if node.nodeName == 'notice':
  545. if self._notice is not None:
  546. raise ManifestParseError(
  547. 'duplicate notice in %s' %
  548. (self.manifestFile))
  549. self._notice = self._ParseNotice(node)
  550. for node in itertools.chain(*node_list):
  551. if node.nodeName == 'manifest-server':
  552. url = self._reqatt(node, 'url')
  553. if self._manifest_server is not None:
  554. raise ManifestParseError(
  555. 'duplicate manifest-server in %s' %
  556. (self.manifestFile))
  557. self._manifest_server = url
  558. def recursively_add_projects(project):
  559. projects = self._projects.setdefault(project.name, [])
  560. if project.relpath is None:
  561. raise ManifestParseError(
  562. 'missing path for %s in %s' %
  563. (project.name, self.manifestFile))
  564. if project.relpath in self._paths:
  565. raise ManifestParseError(
  566. 'duplicate path %s in %s' %
  567. (project.relpath, self.manifestFile))
  568. self._paths[project.relpath] = project
  569. projects.append(project)
  570. for subproject in project.subprojects:
  571. recursively_add_projects(subproject)
  572. for node in itertools.chain(*node_list):
  573. if node.nodeName == 'project':
  574. project = self._ParseProject(node)
  575. recursively_add_projects(project)
  576. if node.nodeName == 'extend-project':
  577. name = self._reqatt(node, 'name')
  578. if name not in self._projects:
  579. raise ManifestParseError('extend-project element specifies non-existent '
  580. 'project: %s' % name)
  581. path = node.getAttribute('path')
  582. groups = node.getAttribute('groups')
  583. if groups:
  584. groups = self._ParseGroups(groups)
  585. revision = node.getAttribute('revision')
  586. remote = node.getAttribute('remote')
  587. if remote:
  588. remote = self._get_remote(node)
  589. for p in self._projects[name]:
  590. if path and p.relpath != path:
  591. continue
  592. if groups:
  593. p.groups.extend(groups)
  594. if revision:
  595. p.revisionExpr = revision
  596. if remote:
  597. p.remote = remote.ToRemoteSpec(name)
  598. if node.nodeName == 'repo-hooks':
  599. # Get the name of the project and the (space-separated) list of enabled.
  600. repo_hooks_project = self._reqatt(node, 'in-project')
  601. enabled_repo_hooks = self._reqatt(node, 'enabled-list').split()
  602. # Only one project can be the hooks project
  603. if self._repo_hooks_project is not None:
  604. raise ManifestParseError(
  605. 'duplicate repo-hooks in %s' %
  606. (self.manifestFile))
  607. # Store a reference to the Project.
  608. try:
  609. repo_hooks_projects = self._projects[repo_hooks_project]
  610. except KeyError:
  611. raise ManifestParseError(
  612. 'project %s not found for repo-hooks' %
  613. (repo_hooks_project))
  614. if len(repo_hooks_projects) != 1:
  615. raise ManifestParseError(
  616. 'internal error parsing repo-hooks in %s' %
  617. (self.manifestFile))
  618. self._repo_hooks_project = repo_hooks_projects[0]
  619. # Store the enabled hooks in the Project object.
  620. self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
  621. if node.nodeName == 'remove-project':
  622. name = self._reqatt(node, 'name')
  623. if name not in self._projects:
  624. raise ManifestParseError('remove-project element specifies non-existent '
  625. 'project: %s' % name)
  626. for p in self._projects[name]:
  627. del self._paths[p.relpath]
  628. del self._projects[name]
  629. # If the manifest removes the hooks project, treat it as if it deleted
  630. # the repo-hooks element too.
  631. if self._repo_hooks_project and (self._repo_hooks_project.name == name):
  632. self._repo_hooks_project = None
  633. def _AddMetaProjectMirror(self, m):
  634. name = None
  635. m_url = m.GetRemote(m.remote.name).url
  636. if m_url.endswith('/.git'):
  637. raise ManifestParseError('refusing to mirror %s' % m_url)
  638. if self._default and self._default.remote:
  639. url = self._default.remote.resolvedFetchUrl
  640. if not url.endswith('/'):
  641. url += '/'
  642. if m_url.startswith(url):
  643. remote = self._default.remote
  644. name = m_url[len(url):]
  645. if name is None:
  646. s = m_url.rindex('/') + 1
  647. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  648. remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
  649. name = m_url[s:]
  650. if name.endswith('.git'):
  651. name = name[:-4]
  652. if name not in self._projects:
  653. m.PreSync()
  654. gitdir = os.path.join(self.topdir, '%s.git' % name)
  655. project = Project(manifest=self,
  656. name=name,
  657. remote=remote.ToRemoteSpec(name),
  658. gitdir=gitdir,
  659. objdir=gitdir,
  660. worktree=None,
  661. relpath=name or None,
  662. revisionExpr=m.revisionExpr,
  663. revisionId=None)
  664. self._projects[project.name] = [project]
  665. self._paths[project.relpath] = project
  666. def _ParseRemote(self, node):
  667. """
  668. reads a <remote> element from the manifest file
  669. """
  670. name = self._reqatt(node, 'name')
  671. alias = node.getAttribute('alias')
  672. if alias == '':
  673. alias = None
  674. fetch = self._reqatt(node, 'fetch')
  675. pushUrl = node.getAttribute('pushurl')
  676. if pushUrl == '':
  677. pushUrl = None
  678. review = node.getAttribute('review')
  679. if review == '':
  680. review = None
  681. revision = node.getAttribute('revision')
  682. if revision == '':
  683. revision = None
  684. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  685. return _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
  686. def _ParseDefault(self, node):
  687. """
  688. reads a <default> element from the manifest file
  689. """
  690. d = _Default()
  691. d.remote = self._get_remote(node)
  692. d.revisionExpr = node.getAttribute('revision')
  693. if d.revisionExpr == '':
  694. d.revisionExpr = None
  695. d.destBranchExpr = node.getAttribute('dest-branch') or None
  696. d.upstreamExpr = node.getAttribute('upstream') or None
  697. d.sync_j = XmlInt(node, 'sync-j', 1)
  698. if d.sync_j <= 0:
  699. raise ManifestParseError('%s: sync-j must be greater than 0, not "%s"' %
  700. (self.manifestFile, d.sync_j))
  701. d.sync_c = XmlBool(node, 'sync-c', False)
  702. d.sync_s = XmlBool(node, 'sync-s', False)
  703. d.sync_tags = XmlBool(node, 'sync-tags', True)
  704. return d
  705. def _ParseNotice(self, node):
  706. """
  707. reads a <notice> element from the manifest file
  708. The <notice> element is distinct from other tags in the XML in that the
  709. data is conveyed between the start and end tag (it's not an empty-element
  710. tag).
  711. The white space (carriage returns, indentation) for the notice element is
  712. relevant and is parsed in a way that is based on how python docstrings work.
  713. In fact, the code is remarkably similar to here:
  714. http://www.python.org/dev/peps/pep-0257/
  715. """
  716. # Get the data out of the node...
  717. notice = node.childNodes[0].data
  718. # Figure out minimum indentation, skipping the first line (the same line
  719. # as the <notice> tag)...
  720. minIndent = sys.maxsize
  721. lines = notice.splitlines()
  722. for line in lines[1:]:
  723. lstrippedLine = line.lstrip()
  724. if lstrippedLine:
  725. indent = len(line) - len(lstrippedLine)
  726. minIndent = min(indent, minIndent)
  727. # Strip leading / trailing blank lines and also indentation.
  728. cleanLines = [lines[0].strip()]
  729. for line in lines[1:]:
  730. cleanLines.append(line[minIndent:].rstrip())
  731. # Clear completely blank lines from front and back...
  732. while cleanLines and not cleanLines[0]:
  733. del cleanLines[0]
  734. while cleanLines and not cleanLines[-1]:
  735. del cleanLines[-1]
  736. return '\n'.join(cleanLines)
  737. def _JoinName(self, parent_name, name):
  738. return os.path.join(parent_name, name)
  739. def _UnjoinName(self, parent_name, name):
  740. return os.path.relpath(name, parent_name)
  741. def _ParseProject(self, node, parent=None, **extra_proj_attrs):
  742. """
  743. reads a <project> element from the manifest file
  744. """
  745. name = self._reqatt(node, 'name')
  746. if parent:
  747. name = self._JoinName(parent.name, name)
  748. remote = self._get_remote(node)
  749. if remote is None:
  750. remote = self._default.remote
  751. if remote is None:
  752. raise ManifestParseError("no remote for project %s within %s" %
  753. (name, self.manifestFile))
  754. revisionExpr = node.getAttribute('revision') or remote.revision
  755. if not revisionExpr:
  756. revisionExpr = self._default.revisionExpr
  757. if not revisionExpr:
  758. raise ManifestParseError("no revision for project %s within %s" %
  759. (name, self.manifestFile))
  760. path = node.getAttribute('path')
  761. if not path:
  762. path = name
  763. if path.startswith('/'):
  764. raise ManifestParseError("project %s path cannot be absolute in %s" %
  765. (name, self.manifestFile))
  766. rebase = XmlBool(node, 'rebase', True)
  767. sync_c = XmlBool(node, 'sync-c', False)
  768. sync_s = XmlBool(node, 'sync-s', self._default.sync_s)
  769. sync_tags = XmlBool(node, 'sync-tags', self._default.sync_tags)
  770. clone_depth = XmlInt(node, 'clone-depth')
  771. if clone_depth is not None and clone_depth <= 0:
  772. raise ManifestParseError('%s: clone-depth must be greater than 0, not "%s"' %
  773. (self.manifestFile, clone_depth))
  774. dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
  775. upstream = node.getAttribute('upstream') or self._default.upstreamExpr
  776. groups = ''
  777. if node.hasAttribute('groups'):
  778. groups = node.getAttribute('groups')
  779. groups = self._ParseGroups(groups)
  780. if parent is None:
  781. relpath, worktree, gitdir, objdir, use_git_worktrees = \
  782. self.GetProjectPaths(name, path)
  783. else:
  784. use_git_worktrees = False
  785. relpath, worktree, gitdir, objdir = \
  786. self.GetSubprojectPaths(parent, name, path)
  787. default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
  788. groups.extend(set(default_groups).difference(groups))
  789. if self.IsMirror and node.hasAttribute('force-path'):
  790. if XmlBool(node, 'force-path', False):
  791. gitdir = os.path.join(self.topdir, '%s.git' % path)
  792. project = Project(manifest=self,
  793. name=name,
  794. remote=remote.ToRemoteSpec(name),
  795. gitdir=gitdir,
  796. objdir=objdir,
  797. worktree=worktree,
  798. relpath=relpath,
  799. revisionExpr=revisionExpr,
  800. revisionId=None,
  801. rebase=rebase,
  802. groups=groups,
  803. sync_c=sync_c,
  804. sync_s=sync_s,
  805. sync_tags=sync_tags,
  806. clone_depth=clone_depth,
  807. upstream=upstream,
  808. parent=parent,
  809. dest_branch=dest_branch,
  810. use_git_worktrees=use_git_worktrees,
  811. **extra_proj_attrs)
  812. for n in node.childNodes:
  813. if n.nodeName == 'copyfile':
  814. self._ParseCopyFile(project, n)
  815. if n.nodeName == 'linkfile':
  816. self._ParseLinkFile(project, n)
  817. if n.nodeName == 'annotation':
  818. self._ParseAnnotation(project, n)
  819. if n.nodeName == 'project':
  820. project.subprojects.append(self._ParseProject(n, parent=project))
  821. return project
  822. def GetProjectPaths(self, name, path):
  823. use_git_worktrees = False
  824. relpath = path
  825. if self.IsMirror:
  826. worktree = None
  827. gitdir = os.path.join(self.topdir, '%s.git' % name)
  828. objdir = gitdir
  829. else:
  830. worktree = os.path.join(self.topdir, path).replace('\\', '/')
  831. gitdir = os.path.join(self.repodir, 'projects', '%s.git' % path)
  832. # We allow people to mix git worktrees & non-git worktrees for now.
  833. # This allows for in situ migration of repo clients.
  834. if os.path.exists(gitdir) or not self.UseGitWorktrees:
  835. objdir = os.path.join(self.repodir, 'project-objects', '%s.git' % name)
  836. else:
  837. use_git_worktrees = True
  838. gitdir = os.path.join(self.repodir, 'worktrees', '%s.git' % name)
  839. objdir = gitdir
  840. return relpath, worktree, gitdir, objdir, use_git_worktrees
  841. def GetProjectsWithName(self, name):
  842. return self._projects.get(name, [])
  843. def GetSubprojectName(self, parent, submodule_path):
  844. return os.path.join(parent.name, submodule_path)
  845. def _JoinRelpath(self, parent_relpath, relpath):
  846. return os.path.join(parent_relpath, relpath)
  847. def _UnjoinRelpath(self, parent_relpath, relpath):
  848. return os.path.relpath(relpath, parent_relpath)
  849. def GetSubprojectPaths(self, parent, name, path):
  850. relpath = self._JoinRelpath(parent.relpath, path)
  851. gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
  852. objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
  853. if self.IsMirror:
  854. worktree = None
  855. else:
  856. worktree = os.path.join(parent.worktree, path).replace('\\', '/')
  857. return relpath, worktree, gitdir, objdir
  858. @staticmethod
  859. def _CheckLocalPath(path, symlink=False):
  860. """Verify |path| is reasonable for use in <copyfile> & <linkfile>."""
  861. if '~' in path:
  862. return '~ not allowed (due to 8.3 filenames on Windows filesystems)'
  863. # Some filesystems (like Apple's HFS+) try to normalize Unicode codepoints
  864. # which means there are alternative names for ".git". Reject paths with
  865. # these in it as there shouldn't be any reasonable need for them here.
  866. # The set of codepoints here was cribbed from jgit's implementation:
  867. # https://eclipse.googlesource.com/jgit/jgit/+/9110037e3e9461ff4dac22fee84ef3694ed57648/org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectChecker.java#884
  868. BAD_CODEPOINTS = {
  869. u'\u200C', # ZERO WIDTH NON-JOINER
  870. u'\u200D', # ZERO WIDTH JOINER
  871. u'\u200E', # LEFT-TO-RIGHT MARK
  872. u'\u200F', # RIGHT-TO-LEFT MARK
  873. u'\u202A', # LEFT-TO-RIGHT EMBEDDING
  874. u'\u202B', # RIGHT-TO-LEFT EMBEDDING
  875. u'\u202C', # POP DIRECTIONAL FORMATTING
  876. u'\u202D', # LEFT-TO-RIGHT OVERRIDE
  877. u'\u202E', # RIGHT-TO-LEFT OVERRIDE
  878. u'\u206A', # INHIBIT SYMMETRIC SWAPPING
  879. u'\u206B', # ACTIVATE SYMMETRIC SWAPPING
  880. u'\u206C', # INHIBIT ARABIC FORM SHAPING
  881. u'\u206D', # ACTIVATE ARABIC FORM SHAPING
  882. u'\u206E', # NATIONAL DIGIT SHAPES
  883. u'\u206F', # NOMINAL DIGIT SHAPES
  884. u'\uFEFF', # ZERO WIDTH NO-BREAK SPACE
  885. }
  886. if BAD_CODEPOINTS & set(path):
  887. # This message is more expansive than reality, but should be fine.
  888. return 'Unicode combining characters not allowed'
  889. # Assume paths might be used on case-insensitive filesystems.
  890. path = path.lower()
  891. # Split up the path by its components. We can't use os.path.sep exclusively
  892. # as some platforms (like Windows) will convert / to \ and that bypasses all
  893. # our constructed logic here. Especially since manifest authors only use
  894. # / in their paths.
  895. resep = re.compile(r'[/%s]' % re.escape(os.path.sep))
  896. parts = resep.split(path)
  897. # Some people use src="." to create stable links to projects. Lets allow
  898. # that but reject all other uses of "." to keep things simple.
  899. if parts != ['.']:
  900. for part in set(parts):
  901. if part in {'.', '..', '.git'} or part.startswith('.repo'):
  902. return 'bad component: %s' % (part,)
  903. if not symlink and resep.match(path[-1]):
  904. return 'dirs not allowed'
  905. # NB: The two abspath checks here are to handle platforms with multiple
  906. # filesystem path styles (e.g. Windows).
  907. norm = os.path.normpath(path)
  908. if (norm == '..' or
  909. (len(norm) >= 3 and norm.startswith('..') and resep.match(norm[0])) or
  910. os.path.isabs(norm) or
  911. norm.startswith('/')):
  912. return 'path cannot be outside'
  913. @classmethod
  914. def _ValidateFilePaths(cls, element, src, dest):
  915. """Verify |src| & |dest| are reasonable for <copyfile> & <linkfile>.
  916. We verify the path independent of any filesystem state as we won't have a
  917. checkout available to compare to. i.e. This is for parsing validation
  918. purposes only.
  919. We'll do full/live sanity checking before we do the actual filesystem
  920. modifications in _CopyFile/_LinkFile/etc...
  921. """
  922. # |dest| is the file we write to or symlink we create.
  923. # It is relative to the top of the repo client checkout.
  924. msg = cls._CheckLocalPath(dest)
  925. if msg:
  926. raise ManifestInvalidPathError(
  927. '<%s> invalid "dest": %s: %s' % (element, dest, msg))
  928. # |src| is the file we read from or path we point to for symlinks.
  929. # It is relative to the top of the git project checkout.
  930. msg = cls._CheckLocalPath(src, symlink=element == 'linkfile')
  931. if msg:
  932. raise ManifestInvalidPathError(
  933. '<%s> invalid "src": %s: %s' % (element, src, msg))
  934. def _ParseCopyFile(self, project, node):
  935. src = self._reqatt(node, 'src')
  936. dest = self._reqatt(node, 'dest')
  937. if not self.IsMirror:
  938. # src is project relative;
  939. # dest is relative to the top of the tree.
  940. # We only validate paths if we actually plan to process them.
  941. self._ValidateFilePaths('copyfile', src, dest)
  942. project.AddCopyFile(src, dest, self.topdir)
  943. def _ParseLinkFile(self, project, node):
  944. src = self._reqatt(node, 'src')
  945. dest = self._reqatt(node, 'dest')
  946. if not self.IsMirror:
  947. # src is project relative;
  948. # dest is relative to the top of the tree.
  949. # We only validate paths if we actually plan to process them.
  950. self._ValidateFilePaths('linkfile', src, dest)
  951. project.AddLinkFile(src, dest, self.topdir)
  952. def _ParseAnnotation(self, project, node):
  953. name = self._reqatt(node, 'name')
  954. value = self._reqatt(node, 'value')
  955. try:
  956. keep = self._reqatt(node, 'keep').lower()
  957. except ManifestParseError:
  958. keep = "true"
  959. if keep != "true" and keep != "false":
  960. raise ManifestParseError('optional "keep" attribute must be '
  961. '"true" or "false"')
  962. project.AddAnnotation(name, value, keep)
  963. def _get_remote(self, node):
  964. name = node.getAttribute('remote')
  965. if not name:
  966. return None
  967. v = self._remotes.get(name)
  968. if not v:
  969. raise ManifestParseError("remote %s not defined in %s" %
  970. (name, self.manifestFile))
  971. return v
  972. def _reqatt(self, node, attname):
  973. """
  974. reads a required attribute from the node.
  975. """
  976. v = node.getAttribute(attname)
  977. if not v:
  978. raise ManifestParseError("no %s in <%s> within %s" %
  979. (attname, node.nodeName, self.manifestFile))
  980. return v
  981. def projectsDiff(self, manifest):
  982. """return the projects differences between two manifests.
  983. The diff will be from self to given manifest.
  984. """
  985. fromProjects = self.paths
  986. toProjects = manifest.paths
  987. fromKeys = sorted(fromProjects.keys())
  988. toKeys = sorted(toProjects.keys())
  989. diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
  990. for proj in fromKeys:
  991. if proj not in toKeys:
  992. diff['removed'].append(fromProjects[proj])
  993. else:
  994. fromProj = fromProjects[proj]
  995. toProj = toProjects[proj]
  996. try:
  997. fromRevId = fromProj.GetCommitRevisionId()
  998. toRevId = toProj.GetCommitRevisionId()
  999. except ManifestInvalidRevisionError:
  1000. diff['unreachable'].append((fromProj, toProj))
  1001. else:
  1002. if fromRevId != toRevId:
  1003. diff['changed'].append((fromProj, toProj))
  1004. toKeys.remove(proj)
  1005. for proj in toKeys:
  1006. diff['added'].append(toProjects[proj])
  1007. return diff
  1008. class GitcManifest(XmlManifest):
  1009. def __init__(self, repodir, gitc_client_name):
  1010. """Initialize the GitcManifest object."""
  1011. super(GitcManifest, self).__init__(repodir)
  1012. self.isGitcClient = True
  1013. self.gitc_client_name = gitc_client_name
  1014. self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
  1015. gitc_client_name)
  1016. self.manifestFile = os.path.join(self.gitc_client_dir, '.manifest')
  1017. def _ParseProject(self, node, parent=None):
  1018. """Override _ParseProject and add support for GITC specific attributes."""
  1019. return super(GitcManifest, self)._ParseProject(
  1020. node, parent=parent, old_revision=node.getAttribute('old-revision'))
  1021. def _output_manifest_project_extras(self, p, e):
  1022. """Output GITC Specific Project attributes"""
  1023. if p.old_revision:
  1024. e.setAttribute('old-revision', str(p.old_revision))