manifest_xml.py 30 KB

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