manifest_xml.py 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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. revision = node.getAttribute('revision')
  491. for p in self._projects[name]:
  492. if path and p.relpath != path:
  493. continue
  494. if groups:
  495. p.groups.extend(groups)
  496. if revision:
  497. p.revisionExpr = revision
  498. if node.nodeName == 'repo-hooks':
  499. # Get the name of the project and the (space-separated) list of enabled.
  500. repo_hooks_project = self._reqatt(node, 'in-project')
  501. enabled_repo_hooks = self._reqatt(node, 'enabled-list').split()
  502. # Only one project can be the hooks project
  503. if self._repo_hooks_project is not None:
  504. raise ManifestParseError(
  505. 'duplicate repo-hooks in %s' %
  506. (self.manifestFile))
  507. # Store a reference to the Project.
  508. try:
  509. repo_hooks_projects = self._projects[repo_hooks_project]
  510. except KeyError:
  511. raise ManifestParseError(
  512. 'project %s not found for repo-hooks' %
  513. (repo_hooks_project))
  514. if len(repo_hooks_projects) != 1:
  515. raise ManifestParseError(
  516. 'internal error parsing repo-hooks in %s' %
  517. (self.manifestFile))
  518. self._repo_hooks_project = repo_hooks_projects[0]
  519. # Store the enabled hooks in the Project object.
  520. self._repo_hooks_project.enabled_repo_hooks = enabled_repo_hooks
  521. if node.nodeName == 'remove-project':
  522. name = self._reqatt(node, 'name')
  523. if name not in self._projects:
  524. raise ManifestParseError('remove-project element specifies non-existent '
  525. 'project: %s' % name)
  526. for p in self._projects[name]:
  527. del self._paths[p.relpath]
  528. del self._projects[name]
  529. # If the manifest removes the hooks project, treat it as if it deleted
  530. # the repo-hooks element too.
  531. if self._repo_hooks_project and (self._repo_hooks_project.name == name):
  532. self._repo_hooks_project = None
  533. def _AddMetaProjectMirror(self, m):
  534. name = None
  535. m_url = m.GetRemote(m.remote.name).url
  536. if m_url.endswith('/.git'):
  537. raise ManifestParseError('refusing to mirror %s' % m_url)
  538. if self._default and self._default.remote:
  539. url = self._default.remote.resolvedFetchUrl
  540. if not url.endswith('/'):
  541. url += '/'
  542. if m_url.startswith(url):
  543. remote = self._default.remote
  544. name = m_url[len(url):]
  545. if name is None:
  546. s = m_url.rindex('/') + 1
  547. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  548. remote = _XmlRemote('origin', fetch=m_url[:s], manifestUrl=manifestUrl)
  549. name = m_url[s:]
  550. if name.endswith('.git'):
  551. name = name[:-4]
  552. if name not in self._projects:
  553. m.PreSync()
  554. gitdir = os.path.join(self.topdir, '%s.git' % name)
  555. project = Project(manifest = self,
  556. name = name,
  557. remote = remote.ToRemoteSpec(name),
  558. gitdir = gitdir,
  559. objdir = gitdir,
  560. worktree = None,
  561. relpath = name or None,
  562. revisionExpr = m.revisionExpr,
  563. revisionId = None)
  564. self._projects[project.name] = [project]
  565. self._paths[project.relpath] = project
  566. def _ParseRemote(self, node):
  567. """
  568. reads a <remote> element from the manifest file
  569. """
  570. name = self._reqatt(node, 'name')
  571. alias = node.getAttribute('alias')
  572. if alias == '':
  573. alias = None
  574. fetch = self._reqatt(node, 'fetch')
  575. pushUrl = node.getAttribute('pushurl')
  576. if pushUrl == '':
  577. pushUrl = None
  578. review = node.getAttribute('review')
  579. if review == '':
  580. review = None
  581. revision = node.getAttribute('revision')
  582. if revision == '':
  583. revision = None
  584. manifestUrl = self.manifestProject.config.GetString('remote.origin.url')
  585. return _XmlRemote(name, alias, fetch, pushUrl, manifestUrl, review, revision)
  586. def _ParseDefault(self, node):
  587. """
  588. reads a <default> element from the manifest file
  589. """
  590. d = _Default()
  591. d.remote = self._get_remote(node)
  592. d.revisionExpr = node.getAttribute('revision')
  593. if d.revisionExpr == '':
  594. d.revisionExpr = None
  595. d.destBranchExpr = node.getAttribute('dest-branch') or None
  596. sync_j = node.getAttribute('sync-j')
  597. if sync_j == '' or sync_j is None:
  598. d.sync_j = 1
  599. else:
  600. d.sync_j = int(sync_j)
  601. sync_c = node.getAttribute('sync-c')
  602. if not sync_c:
  603. d.sync_c = False
  604. else:
  605. d.sync_c = sync_c.lower() in ("yes", "true", "1")
  606. sync_s = node.getAttribute('sync-s')
  607. if not sync_s:
  608. d.sync_s = False
  609. else:
  610. d.sync_s = sync_s.lower() in ("yes", "true", "1")
  611. sync_tags = node.getAttribute('sync-tags')
  612. if not sync_tags:
  613. d.sync_tags = True
  614. else:
  615. d.sync_tags = sync_tags.lower() in ("yes", "true", "1")
  616. return d
  617. def _ParseNotice(self, node):
  618. """
  619. reads a <notice> element from the manifest file
  620. The <notice> element is distinct from other tags in the XML in that the
  621. data is conveyed between the start and end tag (it's not an empty-element
  622. tag).
  623. The white space (carriage returns, indentation) for the notice element is
  624. relevant and is parsed in a way that is based on how python docstrings work.
  625. In fact, the code is remarkably similar to here:
  626. http://www.python.org/dev/peps/pep-0257/
  627. """
  628. # Get the data out of the node...
  629. notice = node.childNodes[0].data
  630. # Figure out minimum indentation, skipping the first line (the same line
  631. # as the <notice> tag)...
  632. minIndent = sys.maxsize
  633. lines = notice.splitlines()
  634. for line in lines[1:]:
  635. lstrippedLine = line.lstrip()
  636. if lstrippedLine:
  637. indent = len(line) - len(lstrippedLine)
  638. minIndent = min(indent, minIndent)
  639. # Strip leading / trailing blank lines and also indentation.
  640. cleanLines = [lines[0].strip()]
  641. for line in lines[1:]:
  642. cleanLines.append(line[minIndent:].rstrip())
  643. # Clear completely blank lines from front and back...
  644. while cleanLines and not cleanLines[0]:
  645. del cleanLines[0]
  646. while cleanLines and not cleanLines[-1]:
  647. del cleanLines[-1]
  648. return '\n'.join(cleanLines)
  649. def _JoinName(self, parent_name, name):
  650. return os.path.join(parent_name, name)
  651. def _UnjoinName(self, parent_name, name):
  652. return os.path.relpath(name, parent_name)
  653. def _ParseProject(self, node, parent = None, **extra_proj_attrs):
  654. """
  655. reads a <project> element from the manifest file
  656. """
  657. name = self._reqatt(node, 'name')
  658. if parent:
  659. name = self._JoinName(parent.name, name)
  660. remote = self._get_remote(node)
  661. if remote is None:
  662. remote = self._default.remote
  663. if remote is None:
  664. raise ManifestParseError("no remote for project %s within %s" %
  665. (name, self.manifestFile))
  666. revisionExpr = node.getAttribute('revision') or remote.revision
  667. if not revisionExpr:
  668. revisionExpr = self._default.revisionExpr
  669. if not revisionExpr:
  670. raise ManifestParseError("no revision for project %s within %s" %
  671. (name, self.manifestFile))
  672. path = node.getAttribute('path')
  673. if not path:
  674. path = name
  675. if path.startswith('/'):
  676. raise ManifestParseError("project %s path cannot be absolute in %s" %
  677. (name, self.manifestFile))
  678. rebase = node.getAttribute('rebase')
  679. if not rebase:
  680. rebase = True
  681. else:
  682. rebase = rebase.lower() in ("yes", "true", "1")
  683. sync_c = node.getAttribute('sync-c')
  684. if not sync_c:
  685. sync_c = False
  686. else:
  687. sync_c = sync_c.lower() in ("yes", "true", "1")
  688. sync_s = node.getAttribute('sync-s')
  689. if not sync_s:
  690. sync_s = self._default.sync_s
  691. else:
  692. sync_s = sync_s.lower() in ("yes", "true", "1")
  693. sync_tags = node.getAttribute('sync-tags')
  694. if not sync_tags:
  695. sync_tags = self._default.sync_tags
  696. else:
  697. sync_tags = sync_tags.lower() in ("yes", "true", "1")
  698. clone_depth = node.getAttribute('clone-depth')
  699. if clone_depth:
  700. try:
  701. clone_depth = int(clone_depth)
  702. if clone_depth <= 0:
  703. raise ValueError()
  704. except ValueError:
  705. raise ManifestParseError('invalid clone-depth %s in %s' %
  706. (clone_depth, self.manifestFile))
  707. dest_branch = node.getAttribute('dest-branch') or self._default.destBranchExpr
  708. upstream = node.getAttribute('upstream')
  709. groups = ''
  710. if node.hasAttribute('groups'):
  711. groups = node.getAttribute('groups')
  712. groups = self._ParseGroups(groups)
  713. if parent is None:
  714. relpath, worktree, gitdir, objdir = self.GetProjectPaths(name, path)
  715. else:
  716. relpath, worktree, gitdir, objdir = \
  717. self.GetSubprojectPaths(parent, name, path)
  718. default_groups = ['all', 'name:%s' % name, 'path:%s' % relpath]
  719. groups.extend(set(default_groups).difference(groups))
  720. if self.IsMirror and node.hasAttribute('force-path'):
  721. if node.getAttribute('force-path').lower() in ("yes", "true", "1"):
  722. gitdir = os.path.join(self.topdir, '%s.git' % path)
  723. project = Project(manifest = self,
  724. name = name,
  725. remote = remote.ToRemoteSpec(name),
  726. gitdir = gitdir,
  727. objdir = objdir,
  728. worktree = worktree,
  729. relpath = relpath,
  730. revisionExpr = revisionExpr,
  731. revisionId = None,
  732. rebase = rebase,
  733. groups = groups,
  734. sync_c = sync_c,
  735. sync_s = sync_s,
  736. sync_tags = sync_tags,
  737. clone_depth = clone_depth,
  738. upstream = upstream,
  739. parent = parent,
  740. dest_branch = dest_branch,
  741. **extra_proj_attrs)
  742. for n in node.childNodes:
  743. if n.nodeName == 'copyfile':
  744. self._ParseCopyFile(project, n)
  745. if n.nodeName == 'linkfile':
  746. self._ParseLinkFile(project, n)
  747. if n.nodeName == 'annotation':
  748. self._ParseAnnotation(project, n)
  749. if n.nodeName == 'project':
  750. project.subprojects.append(self._ParseProject(n, parent = project))
  751. return project
  752. def GetProjectPaths(self, name, path):
  753. relpath = path
  754. if self.IsMirror:
  755. worktree = None
  756. gitdir = os.path.join(self.topdir, '%s.git' % name)
  757. objdir = gitdir
  758. else:
  759. worktree = os.path.join(self.topdir, path).replace('\\', '/')
  760. gitdir = os.path.join(self.repodir, 'projects', '%s.git' % path)
  761. objdir = os.path.join(self.repodir, 'project-objects', '%s.git' % name)
  762. return relpath, worktree, gitdir, objdir
  763. def GetProjectsWithName(self, name):
  764. return self._projects.get(name, [])
  765. def GetSubprojectName(self, parent, submodule_path):
  766. return os.path.join(parent.name, submodule_path)
  767. def _JoinRelpath(self, parent_relpath, relpath):
  768. return os.path.join(parent_relpath, relpath)
  769. def _UnjoinRelpath(self, parent_relpath, relpath):
  770. return os.path.relpath(relpath, parent_relpath)
  771. def GetSubprojectPaths(self, parent, name, path):
  772. relpath = self._JoinRelpath(parent.relpath, path)
  773. gitdir = os.path.join(parent.gitdir, 'subprojects', '%s.git' % path)
  774. objdir = os.path.join(parent.gitdir, 'subproject-objects', '%s.git' % name)
  775. if self.IsMirror:
  776. worktree = None
  777. else:
  778. worktree = os.path.join(parent.worktree, path).replace('\\', '/')
  779. return relpath, worktree, gitdir, objdir
  780. def _ParseCopyFile(self, project, node):
  781. src = self._reqatt(node, 'src')
  782. dest = self._reqatt(node, 'dest')
  783. if not self.IsMirror:
  784. # src is project relative;
  785. # dest is relative to the top of the tree
  786. project.AddCopyFile(src, dest, os.path.join(self.topdir, dest))
  787. def _ParseLinkFile(self, project, node):
  788. src = self._reqatt(node, 'src')
  789. dest = self._reqatt(node, 'dest')
  790. if not self.IsMirror:
  791. # src is project relative;
  792. # dest is relative to the top of the tree
  793. project.AddLinkFile(src, dest, os.path.join(self.topdir, dest))
  794. def _ParseAnnotation(self, project, node):
  795. name = self._reqatt(node, 'name')
  796. value = self._reqatt(node, 'value')
  797. try:
  798. keep = self._reqatt(node, 'keep').lower()
  799. except ManifestParseError:
  800. keep = "true"
  801. if keep != "true" and keep != "false":
  802. raise ManifestParseError('optional "keep" attribute must be '
  803. '"true" or "false"')
  804. project.AddAnnotation(name, value, keep)
  805. def _get_remote(self, node):
  806. name = node.getAttribute('remote')
  807. if not name:
  808. return None
  809. v = self._remotes.get(name)
  810. if not v:
  811. raise ManifestParseError("remote %s not defined in %s" %
  812. (name, self.manifestFile))
  813. return v
  814. def _reqatt(self, node, attname):
  815. """
  816. reads a required attribute from the node.
  817. """
  818. v = node.getAttribute(attname)
  819. if not v:
  820. raise ManifestParseError("no %s in <%s> within %s" %
  821. (attname, node.nodeName, self.manifestFile))
  822. return v
  823. def projectsDiff(self, manifest):
  824. """return the projects differences between two manifests.
  825. The diff will be from self to given manifest.
  826. """
  827. fromProjects = self.paths
  828. toProjects = manifest.paths
  829. fromKeys = sorted(fromProjects.keys())
  830. toKeys = sorted(toProjects.keys())
  831. diff = {'added': [], 'removed': [], 'changed': [], 'unreachable': []}
  832. for proj in fromKeys:
  833. if not proj in toKeys:
  834. diff['removed'].append(fromProjects[proj])
  835. else:
  836. fromProj = fromProjects[proj]
  837. toProj = toProjects[proj]
  838. try:
  839. fromRevId = fromProj.GetCommitRevisionId()
  840. toRevId = toProj.GetCommitRevisionId()
  841. except ManifestInvalidRevisionError:
  842. diff['unreachable'].append((fromProj, toProj))
  843. else:
  844. if fromRevId != toRevId:
  845. diff['changed'].append((fromProj, toProj))
  846. toKeys.remove(proj)
  847. for proj in toKeys:
  848. diff['added'].append(toProjects[proj])
  849. return diff
  850. class GitcManifest(XmlManifest):
  851. def __init__(self, repodir, gitc_client_name):
  852. """Initialize the GitcManifest object."""
  853. super(GitcManifest, self).__init__(repodir)
  854. self.isGitcClient = True
  855. self.gitc_client_name = gitc_client_name
  856. self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),
  857. gitc_client_name)
  858. self.manifestFile = os.path.join(self.gitc_client_dir, '.manifest')
  859. def _ParseProject(self, node, parent = None):
  860. """Override _ParseProject and add support for GITC specific attributes."""
  861. return super(GitcManifest, self)._ParseProject(
  862. node, parent=parent, old_revision=node.getAttribute('old-revision'))
  863. def _output_manifest_project_extras(self, p, e):
  864. """Output GITC Specific Project attributes"""
  865. if p.old_revision:
  866. e.setAttribute('old-revision', str(p.old_revision))