manifest_xml.py 33 KB

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