manifest_xml.py 30 KB

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