manifest_xml.py 32 KB

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