manifest_xml.py 30 KB

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