manifest_xml.py 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. #
  2. # Copyright (C) 2008 The Android Open Source Project
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from __future__ import print_function
  16. import itertools
  17. import os
  18. import re
  19. import sys
  20. import xml.dom.minidom
  21. from pyversion import is_python3
  22. if is_python3():
  23. import urllib.parse
  24. else:
  25. import imp
  26. import urlparse
  27. urllib = imp.new_module('urllib')
  28. urllib.parse = urlparse
  29. import gitc_utils
  30. from git_config import GitConfig
  31. from git_refs import R_HEADS, HEAD
  32. import platform_utils
  33. from project import RemoteSpec, Project, MetaProject
  34. from error import ManifestParseError, ManifestInvalidRevisionError
  35. MANIFEST_FILE_NAME = 'manifest.xml'
  36. LOCAL_MANIFEST_NAME = 'local_manifest.xml'
  37. LOCAL_MANIFESTS_DIR_NAME = 'local_manifests'
  38. # urljoin gets confused if the scheme is not known.
  39. urllib.parse.uses_relative.extend([
  40. 'ssh',
  41. 'git',
  42. 'persistent-https',
  43. 'sso',
  44. 'rpc'])
  45. urllib.parse.uses_netloc.extend([
  46. 'ssh',
  47. 'git',
  48. 'persistent-https',
  49. 'sso',
  50. 'rpc'])
  51. class _Default(object):
  52. """Project defaults within the manifest."""
  53. revisionExpr = None
  54. destBranchExpr = None
  55. remote = None
  56. sync_j = 1
  57. sync_c = False
  58. sync_s = False
  59. sync_tags = True
  60. def __eq__(self, other):
  61. return self.__dict__ == other.__dict__
  62. def __ne__(self, other):
  63. return self.__dict__ != other.__dict__
  64. class _XmlRemote(object):
  65. def __init__(self,
  66. name,
  67. alias=None,
  68. fetch=None,
  69. pushUrl=None,
  70. manifestUrl=None,
  71. review=None,
  72. revision=None):
  73. self.name = name
  74. self.fetchUrl = fetch
  75. self.pushUrl = pushUrl
  76. self.manifestUrl = manifestUrl
  77. self.remoteAlias = alias
  78. self.reviewUrl = review
  79. self.revision = revision
  80. self.resolvedFetchUrl = self._resolveFetchUrl()
  81. def __eq__(self, other):
  82. return self.__dict__ == other.__dict__
  83. def __ne__(self, other):
  84. return self.__dict__ != other.__dict__
  85. def _resolveFetchUrl(self):
  86. url = self.fetchUrl.rstrip('/')
  87. manifestUrl = self.manifestUrl.rstrip('/')
  88. # urljoin will gets confused over quite a few things. The ones we care
  89. # about here are:
  90. # * no scheme in the base url, like <hostname:port>
  91. # We handle no scheme by replacing it with an obscure protocol, gopher
  92. # and then replacing it with the original when we are done.
  93. if manifestUrl.find(':') != manifestUrl.find('/') - 1:
  94. url = urllib.parse.urljoin('gopher://' + manifestUrl, url)
  95. url = re.sub(r'^gopher://', '', url)
  96. else:
  97. url = urllib.parse.urljoin(manifestUrl, url)
  98. return url
  99. def ToRemoteSpec(self, projectName):
  100. fetchUrl = self.resolvedFetchUrl.rstrip('/')
  101. url = fetchUrl + '/' + projectName
  102. remoteName = self.name
  103. if self.remoteAlias:
  104. remoteName = self.remoteAlias
  105. return RemoteSpec(remoteName,
  106. url=url,
  107. pushUrl=self.pushUrl,
  108. review=self.reviewUrl,
  109. orig_name=self.name,
  110. fetchUrl=self.fetchUrl)
  111. class XmlManifest(object):
  112. """manages the repo configuration file"""
  113. def __init__(self, repodir):
  114. self.repodir = os.path.abspath(repodir)
  115. self.topdir = os.path.dirname(self.repodir)
  116. self.manifestFile = os.path.join(self.repodir, MANIFEST_FILE_NAME)
  117. self.globalConfig = GitConfig.ForUser()
  118. self.localManifestWarning = False
  119. self.isGitcClient = False
  120. self.repoProject = MetaProject(self, 'repo',
  121. gitdir = os.path.join(repodir, 'repo/.git'),
  122. worktree = os.path.join(repodir, 'repo'))
  123. self.manifestProject = MetaProject(self, 'manifests',
  124. gitdir = os.path.join(repodir, 'manifests.git'),
  125. worktree = os.path.join(repodir, 'manifests'))
  126. self._Unload()
  127. def Override(self, name):
  128. """Use a different manifest, just for the current instantiation.
  129. """
  130. path = os.path.join(self.manifestProject.worktree, name)
  131. if not os.path.isfile(path):
  132. raise ManifestParseError('manifest %s not found' % name)
  133. old = self.manifestFile
  134. try:
  135. self.manifestFile = path
  136. self._Unload()
  137. self._Load()
  138. finally:
  139. self.manifestFile = old
  140. def Link(self, name):
  141. """Update the repo metadata to use a different manifest.
  142. """
  143. self.Override(name)
  144. try:
  145. if os.path.lexists(self.manifestFile):
  146. platform_utils.remove(self.manifestFile)
  147. platform_utils.symlink(os.path.join('manifests', name), self.manifestFile)
  148. except OSError as e:
  149. raise ManifestParseError('cannot link manifest %s: %s' % (name, str(e)))
  150. def _RemoteToXml(self, r, doc, root):
  151. e = doc.createElement('remote')
  152. root.appendChild(e)
  153. e.setAttribute('name', r.name)
  154. e.setAttribute('fetch', r.fetchUrl)
  155. if r.pushUrl is not None:
  156. e.setAttribute('pushurl', r.pushUrl)
  157. if r.remoteAlias is not None:
  158. e.setAttribute('alias', r.remoteAlias)
  159. if r.reviewUrl is not None:
  160. e.setAttribute('review', r.reviewUrl)
  161. if r.revision is not None:
  162. e.setAttribute('revision', r.revision)
  163. def _ParseGroups(self, groups):
  164. return [x for x in re.split(r'[,\s]+', groups) if x]
  165. def Save(self, fd, peg_rev=False, peg_rev_upstream=True, groups=None):
  166. """Write the current manifest out to the given file descriptor.
  167. """
  168. mp = self.manifestProject
  169. if groups is None:
  170. groups = mp.config.GetString('manifest.groups')
  171. if groups:
  172. groups = self._ParseGroups(groups)
  173. doc = xml.dom.minidom.Document()
  174. root = doc.createElement('manifest')
  175. doc.appendChild(root)
  176. # Save out the notice. There's a little bit of work here to give it the
  177. # right whitespace, which assumes that the notice is automatically indented
  178. # by 4 by minidom.
  179. if self.notice:
  180. notice_element = root.appendChild(doc.createElement('notice'))
  181. notice_lines = self.notice.splitlines()
  182. indented_notice = ('\n'.join(" "*4 + line for line in notice_lines))[4:]
  183. notice_element.appendChild(doc.createTextNode(indented_notice))
  184. d = self.default
  185. for r in sorted(self.remotes):
  186. self._RemoteToXml(self.remotes[r], doc, root)
  187. if self.remotes:
  188. root.appendChild(doc.createTextNode(''))
  189. have_default = False
  190. e = doc.createElement('default')
  191. if d.remote:
  192. have_default = True
  193. e.setAttribute('remote', d.remote.name)
  194. if d.revisionExpr:
  195. have_default = True
  196. e.setAttribute('revision', d.revisionExpr)
  197. if d.destBranchExpr:
  198. have_default = True
  199. e.setAttribute('dest-branch', d.destBranchExpr)
  200. if d.sync_j > 1:
  201. have_default = True
  202. e.setAttribute('sync-j', '%d' % d.sync_j)
  203. if d.sync_c:
  204. have_default = True
  205. e.setAttribute('sync-c', 'true')
  206. if d.sync_s:
  207. have_default = True
  208. e.setAttribute('sync-s', 'true')
  209. if not d.sync_tags:
  210. have_default = True
  211. e.setAttribute('sync-tags', 'false')
  212. if have_default:
  213. root.appendChild(e)
  214. root.appendChild(doc.createTextNode(''))
  215. if self._manifest_server:
  216. e = doc.createElement('manifest-server')
  217. e.setAttribute('url', self._manifest_server)
  218. root.appendChild(e)
  219. root.appendChild(doc.createTextNode(''))
  220. def output_projects(parent, parent_node, projects):
  221. for project_name in projects:
  222. for project in self._projects[project_name]:
  223. output_project(parent, parent_node, project)
  224. def output_project(parent, parent_node, p):
  225. if not p.MatchesGroups(groups):
  226. return
  227. name = p.name
  228. relpath = p.relpath
  229. if parent:
  230. name = self._UnjoinName(parent.name, name)
  231. relpath = self._UnjoinRelpath(parent.relpath, relpath)
  232. e = doc.createElement('project')
  233. parent_node.appendChild(e)
  234. e.setAttribute('name', name)
  235. if relpath != name:
  236. e.setAttribute('path', relpath)
  237. remoteName = None
  238. if d.remote:
  239. remoteName = d.remote.name
  240. if not d.remote or p.remote.orig_name != remoteName:
  241. remoteName = p.remote.orig_name
  242. e.setAttribute('remote', remoteName)
  243. if peg_rev:
  244. if self.IsMirror:
  245. value = p.bare_git.rev_parse(p.revisionExpr + '^0')
  246. else:
  247. value = p.work_git.rev_parse(HEAD + '^0')
  248. e.setAttribute('revision', value)
  249. if peg_rev_upstream:
  250. if p.upstream:
  251. e.setAttribute('upstream', p.upstream)
  252. elif value != p.revisionExpr:
  253. # Only save the origin if the origin is not a sha1, and the default
  254. # isn't our value
  255. e.setAttribute('upstream', p.revisionExpr)
  256. else:
  257. revision = self.remotes[p.remote.orig_name].revision or d.revisionExpr
  258. if not revision or revision != p.revisionExpr:
  259. e.setAttribute('revision', p.revisionExpr)
  260. if p.upstream and p.upstream != p.revisionExpr:
  261. e.setAttribute('upstream', p.upstream)
  262. if p.dest_branch and p.dest_branch != d.destBranchExpr:
  263. e.setAttribute('dest-branch', p.dest_branch)
  264. for c in p.copyfiles:
  265. ce = doc.createElement('copyfile')
  266. ce.setAttribute('src', c.src)
  267. ce.setAttribute('dest', c.dest)
  268. e.appendChild(ce)
  269. for l in p.linkfiles:
  270. le = doc.createElement('linkfile')
  271. le.setAttribute('src', l.src)
  272. le.setAttribute('dest', l.dest)
  273. e.appendChild(le)
  274. default_groups = ['all', 'name:%s' % p.name, 'path:%s' % p.relpath]
  275. egroups = [g for g in p.groups if g not in default_groups]
  276. if egroups:
  277. e.setAttribute('groups', ','.join(egroups))
  278. for a in p.annotations:
  279. if a.keep == "true":
  280. ae = doc.createElement('annotation')
  281. ae.setAttribute('name', a.name)
  282. ae.setAttribute('value', a.value)
  283. e.appendChild(ae)
  284. if p.sync_c:
  285. e.setAttribute('sync-c', 'true')
  286. if p.sync_s:
  287. e.setAttribute('sync-s', 'true')
  288. if not p.sync_tags:
  289. e.setAttribute('sync-tags', 'false')
  290. if p.clone_depth:
  291. e.setAttribute('clone-depth', str(p.clone_depth))
  292. self._output_manifest_project_extras(p, e)
  293. if p.subprojects:
  294. subprojects = set(subp.name for subp in p.subprojects)
  295. output_projects(p, e, list(sorted(subprojects)))
  296. projects = set(p.name for p in self._paths.values() if not p.parent)
  297. output_projects(None, root, list(sorted(projects)))
  298. if self._repo_hooks_project:
  299. root.appendChild(doc.createTextNode(''))
  300. e = doc.createElement('repo-hooks')
  301. e.setAttribute('in-project', self._repo_hooks_project.name)
  302. e.setAttribute('enabled-list',
  303. ' '.join(self._repo_hooks_project.enabled_repo_hooks))
  304. root.appendChild(e)
  305. doc.writexml(fd, '', ' ', '\n', 'UTF-8')
  306. def _output_manifest_project_extras(self, p, e):
  307. """Manifests can modify e if they support extra project attributes."""
  308. pass
  309. @property
  310. def paths(self):
  311. self._Load()
  312. return self._paths
  313. @property
  314. def projects(self):
  315. self._Load()
  316. return list(self._paths.values())
  317. @property
  318. def remotes(self):
  319. self._Load()
  320. return self._remotes
  321. @property
  322. def default(self):
  323. self._Load()
  324. return self._default
  325. @property
  326. def repo_hooks_project(self):
  327. self._Load()
  328. return self._repo_hooks_project
  329. @property
  330. def notice(self):
  331. self._Load()
  332. return self._notice
  333. @property
  334. def manifest_server(self):
  335. self._Load()
  336. return self._manifest_server
  337. @property
  338. def IsMirror(self):
  339. return self.manifestProject.config.GetBoolean('repo.mirror')
  340. @property
  341. def IsArchive(self):
  342. return self.manifestProject.config.GetBoolean('repo.archive')
  343. @property
  344. def HasSubmodules(self):
  345. return self.manifestProject.config.GetBoolean('repo.submodules')
  346. def _Unload(self):
  347. self._loaded = False
  348. self._projects = {}
  349. self._paths = {}
  350. self._remotes = {}
  351. self._default = None
  352. self._repo_hooks_project = None
  353. self._notice = None
  354. self.branch = None
  355. self._manifest_server = None
  356. def _Load(self):
  357. if not self._loaded:
  358. m = self.manifestProject
  359. b = m.GetBranch(m.CurrentBranch).merge
  360. if b is not None and b.startswith(R_HEADS):
  361. b = b[len(R_HEADS):]
  362. self.branch = b
  363. nodes = []
  364. nodes.append(self._ParseManifestXml(self.manifestFile,
  365. self.manifestProject.worktree))
  366. local = os.path.join(self.repodir, LOCAL_MANIFEST_NAME)
  367. if os.path.exists(local):
  368. if not self.localManifestWarning:
  369. self.localManifestWarning = True
  370. print('warning: %s is deprecated; put local manifests in `%s` instead'
  371. % (LOCAL_MANIFEST_NAME, os.path.join(self.repodir, LOCAL_MANIFESTS_DIR_NAME)),
  372. file=sys.stderr)
  373. nodes.append(self._ParseManifestXml(local, self.repodir))
  374. local_dir = os.path.abspath(os.path.join(self.repodir, LOCAL_MANIFESTS_DIR_NAME))
  375. try:
  376. for local_file in sorted(os.listdir(local_dir)):
  377. if local_file.endswith('.xml'):
  378. local = os.path.join(local_dir, local_file)
  379. nodes.append(self._ParseManifestXml(local, self.repodir))
  380. except OSError:
  381. pass
  382. try:
  383. self._ParseManifest(nodes)
  384. except ManifestParseError as e:
  385. # There was a problem parsing, unload ourselves in case they catch
  386. # this error and try again later, we will show the correct error
  387. self._Unload()
  388. raise e
  389. if self.IsMirror:
  390. self._AddMetaProjectMirror(self.repoProject)
  391. self._AddMetaProjectMirror(self.manifestProject)
  392. self._loaded = True
  393. def _ParseManifestXml(self, path, include_root):
  394. try:
  395. root = xml.dom.minidom.parse(path)
  396. except (OSError, xml.parsers.expat.ExpatError) as e:
  397. raise ManifestParseError("error parsing manifest %s: %s" % (path, e))
  398. if not root or not root.childNodes:
  399. raise ManifestParseError("no root node in %s" % (path,))
  400. for manifest in root.childNodes:
  401. if manifest.nodeName == 'manifest':
  402. break
  403. else:
  404. raise ManifestParseError("no <manifest> in %s" % (path,))
  405. nodes = []
  406. for node in manifest.childNodes: # pylint:disable=W0631
  407. # We only get here if manifest is initialised
  408. if node.nodeName == 'include':
  409. name = self._reqatt(node, 'name')
  410. fp = os.path.join(include_root, name)
  411. if not os.path.isfile(fp):
  412. raise ManifestParseError("include %s doesn't exist or isn't a file"
  413. % (name,))
  414. try:
  415. nodes.extend(self._ParseManifestXml(fp, include_root))
  416. # should isolate this to the exact exception, but that's
  417. # tricky. actual parsing implementation may vary.
  418. except (KeyboardInterrupt, RuntimeError, SystemExit):
  419. raise
  420. except Exception as e:
  421. raise ManifestParseError(
  422. "failed parsing included manifest %s: %s", (name, e))
  423. else:
  424. nodes.append(node)
  425. return nodes
  426. def _ParseManifest(self, node_list):
  427. for node in itertools.chain(*node_list):
  428. if node.nodeName == 'remote':
  429. remote = self._ParseRemote(node)
  430. if remote:
  431. if remote.name in self._remotes:
  432. if remote != self._remotes[remote.name]:
  433. raise ManifestParseError(
  434. 'remote %s already exists with different attributes' %
  435. (remote.name))
  436. else:
  437. self._remotes[remote.name] = remote
  438. for node in itertools.chain(*node_list):
  439. if node.nodeName == 'default':
  440. new_default = self._ParseDefault(node)
  441. if self._default is None:
  442. self._default = new_default
  443. elif new_default != self._default:
  444. raise ManifestParseError('duplicate default in %s' %
  445. (self.manifestFile))
  446. if self._default is None:
  447. self._default = _Default()
  448. for node in itertools.chain(*node_list):
  449. if node.nodeName == 'notice':
  450. if self._notice is not None:
  451. raise ManifestParseError(
  452. 'duplicate notice in %s' %
  453. (self.manifestFile))
  454. self._notice = self._ParseNotice(node)
  455. for node in itertools.chain(*node_list):
  456. if node.nodeName == 'manifest-server':
  457. url = self._reqatt(node, 'url')
  458. if self._manifest_server is not None:
  459. raise ManifestParseError(
  460. 'duplicate manifest-server in %s' %
  461. (self.manifestFile))
  462. self._manifest_server = url
  463. def recursively_add_projects(project):
  464. projects = self._projects.setdefault(project.name, [])
  465. if project.relpath is None:
  466. raise ManifestParseError(
  467. 'missing path for %s in %s' %
  468. (project.name, self.manifestFile))
  469. if project.relpath in self._paths:
  470. raise ManifestParseError(
  471. 'duplicate path %s in %s' %
  472. (project.relpath, self.manifestFile))
  473. self._paths[project.relpath] = project
  474. projects.append(project)
  475. for subproject in project.subprojects:
  476. recursively_add_projects(subproject)
  477. for node in itertools.chain(*node_list):
  478. if node.nodeName == 'project':
  479. project = self._ParseProject(node)
  480. recursively_add_projects(project)
  481. if node.nodeName == 'extend-project':
  482. name = self._reqatt(node, 'name')
  483. if name not in self._projects:
  484. raise ManifestParseError('extend-project element specifies non-existent '
  485. 'project: %s' % name)
  486. path = node.getAttribute('path')
  487. groups = node.getAttribute('groups')
  488. if groups:
  489. groups = self._ParseGroups(groups)
  490. for p in self._projects[name]:
  491. if path and p.relpath != path:
  492. continue
  493. if groups:
  494. p.groups.extend(groups)
  495. if node.nodeName == 'repo-hooks':
  496. # Get the name of the project and the (space-separated) list of enabled.
  497. repo_hooks_project = self._reqatt(node, 'in-project')
  498. enabled_repo_hooks = self._reqatt(node, 'enabled-list').split()
  499. # Only one project can be the hooks project
  500. if self._repo_hooks_project is not None:
  501. raise ManifestParseError(
  502. 'duplicate repo-hooks in %s' %
  503. (self.manifestFile))
  504. # Store a reference to the Project.
  505. try:
  506. repo_hooks_projects = self._projects[repo_hooks_project]
  507. except KeyError:
  508. raise ManifestParseError(
  509. 'project %s not found for repo-hooks' %
  510. (repo_hooks_project))
  511. if len(repo_hooks_projects) != 1:
  512. raise ManifestParseError(
  513. 'internal error parsing repo-hooks in %s' %
  514. (self.manifestFile))
  515. self._repo_hooks_project = repo_hooks_projects[0]
  516. # Store the enabled hooks in the Project object.
  517. self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
  518. if node.nodeName == 'remove-project':
  519. name = self._reqatt(node, 'name')
  520. if name not in self._projects:
  521. raise ManifestParseError('remove-project element specifies non-existent '
  522. 'project: %s' % name)
  523. for p in self._projects[name]:
  524. del self._paths[p.relpath]
  525. del self._projects[name]
  526. # If the manifest removes the hooks project, treat it as if it deleted
  527. # the repo-hooks element too.
  528. if self._repo_hooks_project and (self._repo_hooks_project.name == name):
  529. self._repo_hooks_project = None
  530. def _AddMetaProjectMirror(self, m):
  531. name = None
  532. m_url = m.GetRemote(m.remote.name).url
  533. if m_url.endswith('/.git'):
  534. raise ManifestParseError('refusing to mirror %s' % m_url)
  535. if self._default and self._default.remote:
  536. url = self._default.remote.resolvedFetchUrl
  537. if not url.endswith('/'):
  538. url += '/'
  539. if m_url.startswith(url):
  540. remote = self._default.remote
  541. name = m_url[len(url):]
  542. if name is None:
  543. s = m_url.rindex('/') + 1
  544. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  545. remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
  546. name = m_url[s:]
  547. if name.endswith('.git'):
  548. name = name[:-4]
  549. if name not in self._projects:
  550. m.PreSync()
  551. gitdir = os.path.join(self.topdir, '%s.git' % name)
  552. project = Project(manifest = self,
  553. name = name,
  554. remote = remote.ToRemoteSpec(name),
  555. gitdir = gitdir,
  556. objdir = gitdir,
  557. worktree = None,
  558. relpath = name or None,
  559. revisionExpr = m.revisionExpr,
  560. revisionId = None)
  561. self._projects[project.name] = [project]
  562. self._paths[project.relpath] = project
  563. def _ParseRemote(self, node):
  564. """
  565. reads a <remote> element from the manifest file
  566. """
  567. name = self._reqatt(node, 'name')
  568. alias = node.getAttribute('alias')
  569. if alias == '':
  570. alias = None
  571. fetch = self._reqatt(node, 'fetch')
  572. pushUrl = node.getAttribute('pushurl')
  573. if pushUrl == '':
  574. pushUrl = None
  575. review = node.getAttribute('review')
  576. if review == '':
  577. review = None
  578. revision = node.getAttribute('revision')
  579. if revision == '':
  580. revision = None
  581. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  582. return _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
  583. def _ParseDefault(self, node):
  584. """
  585. reads a <default> element from the manifest file
  586. """
  587. d = _Default()
  588. d.remote = self._get_remote(node)
  589. d.revisionExpr = node.getAttribute('revision')
  590. if d.revisionExpr == '':
  591. d.revisionExpr = None
  592. d.destBranchExpr = node.getAttribute('dest-branch') or None
  593. sync_j = node.getAttribute('sync-j')
  594. if sync_j == '' or sync_j is None:
  595. d.sync_j = 1
  596. else:
  597. d.sync_j = int(sync_j)
  598. sync_c = node.getAttribute('sync-c')
  599. if not sync_c:
  600. d.sync_c = False
  601. else:
  602. d.sync_c = sync_c.lower() in ("yes", "true", "1")
  603. sync_s = node.getAttribute('sync-s')
  604. if not sync_s:
  605. d.sync_s = False
  606. else:
  607. d.sync_s = sync_s.lower() in ("yes", "true", "1")
  608. sync_tags = node.getAttribute('sync-tags')
  609. if not sync_tags:
  610. d.sync_tags = True
  611. else:
  612. d.sync_tags = sync_tags.lower() in ("yes", "true", "1")
  613. return d
  614. def _ParseNotice(self, node):
  615. """
  616. reads a <notice> element from the manifest file
  617. The <notice> element is distinct from other tags in the XML in that the
  618. data is conveyed between the start and end tag (it's not an empty-element
  619. tag).
  620. The white space (carriage returns, indentation) for the notice element is
  621. relevant and is parsed in a way that is based on how python docstrings work.
  622. In fact, the code is remarkably similar to here:
  623. http://www.python.org/dev/peps/pep-0257/
  624. """
  625. # Get the data out of the node...
  626. notice = node.childNodes[0].data
  627. # Figure out minimum indentation, skipping the first line (the same line
  628. # as the <notice> tag)...
  629. minIndent = sys.maxsize
  630. lines = notice.splitlines()
  631. for line in lines[1:]:
  632. lstrippedLine = line.lstrip()
  633. if lstrippedLine:
  634. indent = len(line) - len(lstrippedLine)
  635. minIndent = min(indent, minIndent)
  636. # Strip leading / trailing blank lines and also indentation.
  637. cleanLines = [lines[0].strip()]
  638. for line in lines[1:]:
  639. cleanLines.append(line[minIndent:].rstrip())
  640. # Clear completely blank lines from front and back...
  641. while cleanLines and not cleanLines[0]:
  642. del cleanLines[0]
  643. while cleanLines and not cleanLines[-1]:
  644. del cleanLines[-1]
  645. return '\n'.join(cleanLines)
  646. def _JoinName(self, parent_name, name):
  647. return os.path.join(parent_name, name)
  648. def _UnjoinName(self, parent_name, name):
  649. return os.path.relpath(name, parent_name)
  650. def _ParseProject(self, node, parent = None, **extra_proj_attrs):
  651. """
  652. reads a <project> element from the manifest file
  653. """
  654. name = self._reqatt(node, 'name')
  655. if parent:
  656. name = self._JoinName(parent.name, name)
  657. remote = self._get_remote(node)
  658. if remote is None:
  659. remote = self._default.remote
  660. if remote is None:
  661. raise ManifestParseError("no remote for project %s within %s" %
  662. (name, self.manifestFile))
  663. revisionExpr = node.getAttribute('revision') or remote.revision
  664. if not revisionExpr:
  665. revisionExpr = self._default.revisionExpr
  666. if not revisionExpr:
  667. raise ManifestParseError("no revision for project %s within %s" %
  668. (name, self.manifestFile))
  669. path = node.getAttribute('path')
  670. if not path:
  671. path = name
  672. if path.startswith('/'):
  673. raise ManifestParseError("project %s path cannot be absolute in %s" %
  674. (name, self.manifestFile))
  675. rebase = node.getAttribute('rebase')
  676. if not rebase:
  677. rebase = True
  678. else:
  679. rebase = rebase.lower() in ("yes", "true", "1")
  680. sync_c = node.getAttribute('sync-c')
  681. if not sync_c:
  682. sync_c = False
  683. else:
  684. sync_c = sync_c.lower() in ("yes", "true", "1")
  685. sync_s = node.getAttribute('sync-s')
  686. if not sync_s:
  687. sync_s = self._default.sync_s
  688. else:
  689. sync_s = sync_s.lower() in ("yes", "true", "1")
  690. sync_tags = node.getAttribute('sync-tags')
  691. if not sync_tags:
  692. sync_tags = self._default.sync_tags
  693. else:
  694. sync_tags = sync_tags.lower() in ("yes", "true", "1")
  695. clone_depth = node.getAttribute('clone-depth')
  696. if clone_depth:
  697. try:
  698. clone_depth = int(clone_depth)
  699. if clone_depth <= 0:
  700. raise ValueError()
  701. except ValueError:
  702. raise ManifestParseError('invalid clone-depth %s in %s' %
  703. (clone_depth, self.manifestFile))
  704. dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
  705. upstream = node.getAttribute('upstream')
  706. groups = ''
  707. if node.hasAttribute('groups'):
  708. groups = node.getAttribute('groups')
  709. groups = self._ParseGroups(groups)
  710. if parent is None:
  711. relpath, worktree, gitdir, objdir = self.GetProjectPaths(name, path)
  712. else:
  713. relpath, worktree, gitdir, objdir = \
  714. self.GetSubprojectPaths(parent, name, path)
  715. default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
  716. groups.extend(set(default_groups).difference(groups))
  717. if self.IsMirror and node.hasAttribute('force-path'):
  718. if node.getAttribute('force-path').lower() in ("yes", "true", "1"):
  719. gitdir = os.path.join(self.topdir, '%s.git' % path)
  720. project = Project(manifest = self,
  721. name = name,
  722. remote = remote.ToRemoteSpec(name),
  723. gitdir = gitdir,
  724. objdir = objdir,
  725. worktree = worktree,
  726. relpath = relpath,
  727. revisionExpr = revisionExpr,
  728. revisionId = None,
  729. rebase = rebase,
  730. groups = groups,
  731. sync_c = sync_c,
  732. sync_s = sync_s,
  733. sync_tags = sync_tags,
  734. clone_depth = clone_depth,
  735. upstream = upstream,
  736. parent = parent,
  737. dest_branch = dest_branch,
  738. **extra_proj_attrs)
  739. for n in node.childNodes:
  740. if n.nodeName == 'copyfile':
  741. self._ParseCopyFile(project, n)
  742. if n.nodeName == 'linkfile':
  743. self._ParseLinkFile(project, n)
  744. if n.nodeName == 'annotation':
  745. self._ParseAnnotation(project, n)
  746. if n.nodeName == 'project':
  747. project.subprojects.append(self._ParseProject(n, parent = project))
  748. return project
  749. def GetProjectPaths(self, name, path):
  750. relpath = path
  751. if self.IsMirror:
  752. worktree = None
  753. gitdir = os.path.join(self.topdir, '%s.git' % name)
  754. objdir = gitdir
  755. else:
  756. worktree = os.path.join(self.topdir, path).replace('\\', '/')
  757. gitdir = os.path.join(self.repodir, 'projects', '%s.git' % path)
  758. objdir = os.path.join(self.repodir, 'project-objects', '%s.git' % name)
  759. return relpath, worktree, gitdir, objdir
  760. def GetProjectsWithName(self, name):
  761. return self._projects.get(name, [])
  762. def GetSubprojectName(self, parent, submodule_path):
  763. return os.path.join(parent.name, submodule_path)
  764. def _JoinRelpath(self, parent_relpath, relpath):
  765. return os.path.join(parent_relpath, relpath)
  766. def _UnjoinRelpath(self, parent_relpath, relpath):
  767. return os.path.relpath(relpath, parent_relpath)
  768. def GetSubprojectPaths(self, parent, name, path):
  769. relpath = self._JoinRelpath(parent.relpath, path)
  770. gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
  771. objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
  772. if self.IsMirror:
  773. worktree = None
  774. else:
  775. worktree = os.path.join(parent.worktree, path).replace('\\', '/')
  776. return relpath, worktree, gitdir, objdir
  777. def _ParseCopyFile(self, project, node):
  778. src = self._reqatt(node, 'src')
  779. dest = self._reqatt(node, 'dest')
  780. if not self.IsMirror:
  781. # src is project relative;
  782. # dest is relative to the top of the tree
  783. project.AddCopyFile(src, dest, os.path.join(self.topdir, dest))
  784. def _ParseLinkFile(self, project, node):
  785. src = self._reqatt(node, 'src')
  786. dest = self._reqatt(node, 'dest')
  787. if not self.IsMirror:
  788. # src is project relative;
  789. # dest is relative to the top of the tree
  790. project.AddLinkFile(src, dest, os.path.join(self.topdir, dest))
  791. def _ParseAnnotation(self, project, node):
  792. name = self._reqatt(node, 'name')
  793. value = self._reqatt(node, 'value')
  794. try:
  795. keep = self._reqatt(node, 'keep').lower()
  796. except ManifestParseError:
  797. keep = "true"
  798. if keep != "true" and keep != "false":
  799. raise ManifestParseError('optional "keep" attribute must be '
  800. '"true" or "false"')
  801. project.AddAnnotation(name, value, keep)
  802. def _get_remote(self, node):
  803. name = node.getAttribute('remote')
  804. if not name:
  805. return None
  806. v = self._remotes.get(name)
  807. if not v:
  808. raise ManifestParseError("remote %s not defined in %s" %
  809. (name, self.manifestFile))
  810. return v
  811. def _reqatt(self, node, attname):
  812. """
  813. reads a required attribute from the node.
  814. """
  815. v = node.getAttribute(attname)
  816. if not v:
  817. raise ManifestParseError("no %s in <%s> within %s" %
  818. (attname, node.nodeName, self.manifestFile))
  819. return v
  820. def projectsDiff(self, manifest):
  821. """return the projects differences between two manifests.
  822. The diff will be from self to given manifest.
  823. """
  824. fromProjects = self.paths
  825. toProjects = manifest.paths
  826. fromKeys = sorted(fromProjects.keys())
  827. toKeys = sorted(toProjects.keys())
  828. diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
  829. for proj in fromKeys:
  830. if not proj in toKeys:
  831. diff['removed'].append(fromProjects[proj])
  832. else:
  833. fromProj = fromProjects[proj]
  834. toProj = toProjects[proj]
  835. try:
  836. fromRevId = fromProj.GetCommitRevisionId()
  837. toRevId = toProj.GetCommitRevisionId()
  838. except ManifestInvalidRevisionError:
  839. diff['unreachable'].append((fromProj, toProj))
  840. else:
  841. if fromRevId != toRevId:
  842. diff['changed'].append((fromProj, toProj))
  843. toKeys.remove(proj)
  844. for proj in toKeys:
  845. diff['added'].append(toProjects[proj])
  846. return diff
  847. class GitcManifest(XmlManifest):
  848. def __init__(self, repodir, gitc_client_name):
  849. """Initialize the GitcManifest object."""
  850. super(GitcManifest, self).__init__(repodir)
  851. self.isGitcClient = True
  852. self.gitc_client_name = gitc_client_name
  853. self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
  854. gitc_client_name)
  855. self.manifestFile = os.path.join(self.gitc_client_dir, '.manifest')
  856. def _ParseProject(self, node, parent = None):
  857. """Override _ParseProject and add support for GITC specific attributes."""
  858. return super(GitcManifest, self)._ParseProject(
  859. node, parent=parent, old_revision=node.getAttribute('old-revision'))
  860. def _output_manifest_project_extras(self, p, e):
  861. """Output GITC Specific Project attributes"""
  862. if p.old_revision:
  863. e.setAttribute('old-revision', str(p.old_revision))