manifest_xml.py 29 KB

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