manifest_xml.py 30 KB

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