manifest_xml.py 38 KB

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