manifest_xml.py 31 KB

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