manifest_xml.py 32 KB

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