manifest_xml.py 30 KB

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