manifest_xml.py 33 KB

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