manifest_xml.py 32 KB

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