manifest_xml.py 31 KB

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