tinfoil.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. # tinfoil: a simple wrapper around cooker for bitbake-based command-line utilities
  2. #
  3. # Copyright (C) 2012-2017 Intel Corporation
  4. # Copyright (C) 2011 Mentor Graphics Corporation
  5. # Copyright (C) 2006-2012 Richard Purdie
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License version 2 as
  9. # published by the Free Software Foundation.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License along
  17. # with this program; if not, write to the Free Software Foundation, Inc.,
  18. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. import logging
  20. import os
  21. import sys
  22. import atexit
  23. import re
  24. from collections import OrderedDict, defaultdict
  25. import bb.cache
  26. import bb.cooker
  27. import bb.providers
  28. import bb.taskdata
  29. import bb.utils
  30. import bb.command
  31. import bb.remotedata
  32. from bb.cookerdata import CookerConfiguration, ConfigParameters
  33. from bb.main import setup_bitbake, BitBakeConfigParameters, BBMainException
  34. import bb.fetch2
  35. # We need this in order to shut down the connection to the bitbake server,
  36. # otherwise the process will never properly exit
  37. _server_connections = []
  38. def _terminate_connections():
  39. for connection in _server_connections:
  40. connection.terminate()
  41. atexit.register(_terminate_connections)
  42. class TinfoilUIException(Exception):
  43. """Exception raised when the UI returns non-zero from its main function"""
  44. def __init__(self, returncode):
  45. self.returncode = returncode
  46. def __repr__(self):
  47. return 'UI module main returned %d' % self.returncode
  48. class TinfoilCommandFailed(Exception):
  49. """Exception raised when run_command fails"""
  50. class TinfoilDataStoreConnector:
  51. def __init__(self, tinfoil, dsindex):
  52. self.tinfoil = tinfoil
  53. self.dsindex = dsindex
  54. def getVar(self, name):
  55. value = self.tinfoil.run_command('dataStoreConnectorFindVar', self.dsindex, name)
  56. overrides = None
  57. if isinstance(value, dict):
  58. if '_connector_origtype' in value:
  59. value['_content'] = self.tinfoil._reconvert_type(value['_content'], value['_connector_origtype'])
  60. del value['_connector_origtype']
  61. if '_connector_overrides' in value:
  62. overrides = value['_connector_overrides']
  63. del value['_connector_overrides']
  64. return value, overrides
  65. def getKeys(self):
  66. return set(self.tinfoil.run_command('dataStoreConnectorGetKeys', self.dsindex))
  67. def getVarHistory(self, name):
  68. return self.tinfoil.run_command('dataStoreConnectorGetVarHistory', self.dsindex, name)
  69. def expandPythonRef(self, varname, expr, d):
  70. ds = bb.remotedata.RemoteDatastores.transmit_datastore(d)
  71. ret = self.tinfoil.run_command('dataStoreConnectorExpandPythonRef', ds, varname, expr)
  72. return ret
  73. def setVar(self, varname, value):
  74. if self.dsindex is None:
  75. self.tinfoil.run_command('setVariable', varname, value)
  76. else:
  77. # Not currently implemented - indicate that setting should
  78. # be redirected to local side
  79. return True
  80. def setVarFlag(self, varname, flagname, value):
  81. if self.dsindex is None:
  82. self.tinfoil.run_command('dataStoreConnectorSetVarFlag', self.dsindex, varname, flagname, value)
  83. else:
  84. # Not currently implemented - indicate that setting should
  85. # be redirected to local side
  86. return True
  87. def delVar(self, varname):
  88. if self.dsindex is None:
  89. self.tinfoil.run_command('dataStoreConnectorDelVar', self.dsindex, varname)
  90. else:
  91. # Not currently implemented - indicate that setting should
  92. # be redirected to local side
  93. return True
  94. def delVarFlag(self, varname, flagname):
  95. if self.dsindex is None:
  96. self.tinfoil.run_command('dataStoreConnectorDelVar', self.dsindex, varname, flagname)
  97. else:
  98. # Not currently implemented - indicate that setting should
  99. # be redirected to local side
  100. return True
  101. def renameVar(self, name, newname):
  102. if self.dsindex is None:
  103. self.tinfoil.run_command('dataStoreConnectorRenameVar', self.dsindex, name, newname)
  104. else:
  105. # Not currently implemented - indicate that setting should
  106. # be redirected to local side
  107. return True
  108. class TinfoilCookerAdapter:
  109. """
  110. Provide an adapter for existing code that expects to access a cooker object via Tinfoil,
  111. since now Tinfoil is on the client side it no longer has direct access.
  112. """
  113. class TinfoilCookerCollectionAdapter:
  114. """ cooker.collection adapter """
  115. def __init__(self, tinfoil):
  116. self.tinfoil = tinfoil
  117. def get_file_appends(self, fn):
  118. return self.tinfoil.get_file_appends(fn)
  119. def __getattr__(self, name):
  120. if name == 'overlayed':
  121. return self.tinfoil.get_overlayed_recipes()
  122. elif name == 'bbappends':
  123. return self.tinfoil.run_command('getAllAppends')
  124. else:
  125. raise AttributeError("%s instance has no attribute '%s'" % (self.__class__.__name__, name))
  126. class TinfoilRecipeCacheAdapter:
  127. """ cooker.recipecache adapter """
  128. def __init__(self, tinfoil):
  129. self.tinfoil = tinfoil
  130. self._cache = {}
  131. def get_pkg_pn_fn(self):
  132. pkg_pn = defaultdict(list, self.tinfoil.run_command('getRecipes') or [])
  133. pkg_fn = {}
  134. for pn, fnlist in pkg_pn.items():
  135. for fn in fnlist:
  136. pkg_fn[fn] = pn
  137. self._cache['pkg_pn'] = pkg_pn
  138. self._cache['pkg_fn'] = pkg_fn
  139. def __getattr__(self, name):
  140. # Grab these only when they are requested since they aren't always used
  141. if name in self._cache:
  142. return self._cache[name]
  143. elif name == 'pkg_pn':
  144. self.get_pkg_pn_fn()
  145. return self._cache[name]
  146. elif name == 'pkg_fn':
  147. self.get_pkg_pn_fn()
  148. return self._cache[name]
  149. elif name == 'deps':
  150. attrvalue = defaultdict(list, self.tinfoil.run_command('getRecipeDepends') or [])
  151. elif name == 'rundeps':
  152. attrvalue = defaultdict(lambda: defaultdict(list), self.tinfoil.run_command('getRuntimeDepends') or [])
  153. elif name == 'runrecs':
  154. attrvalue = defaultdict(lambda: defaultdict(list), self.tinfoil.run_command('getRuntimeRecommends') or [])
  155. elif name == 'pkg_pepvpr':
  156. attrvalue = self.tinfoil.run_command('getRecipeVersions') or {}
  157. elif name == 'inherits':
  158. attrvalue = self.tinfoil.run_command('getRecipeInherits') or {}
  159. elif name == 'bbfile_priority':
  160. attrvalue = self.tinfoil.run_command('getBbFilePriority') or {}
  161. elif name == 'pkg_dp':
  162. attrvalue = self.tinfoil.run_command('getDefaultPreference') or {}
  163. else:
  164. raise AttributeError("%s instance has no attribute '%s'" % (self.__class__.__name__, name))
  165. self._cache[name] = attrvalue
  166. return attrvalue
  167. def __init__(self, tinfoil):
  168. self.tinfoil = tinfoil
  169. self.collection = self.TinfoilCookerCollectionAdapter(tinfoil)
  170. self.recipecaches = {}
  171. # FIXME all machines
  172. self.recipecaches[''] = self.TinfoilRecipeCacheAdapter(tinfoil)
  173. self._cache = {}
  174. def __getattr__(self, name):
  175. # Grab these only when they are requested since they aren't always used
  176. if name in self._cache:
  177. return self._cache[name]
  178. elif name == 'skiplist':
  179. attrvalue = self.tinfoil.get_skipped_recipes()
  180. elif name == 'bbfile_config_priorities':
  181. ret = self.tinfoil.run_command('getLayerPriorities')
  182. bbfile_config_priorities = []
  183. for collection, pattern, regex, pri in ret:
  184. bbfile_config_priorities.append((collection, pattern, re.compile(regex), pri))
  185. attrvalue = bbfile_config_priorities
  186. else:
  187. raise AttributeError("%s instance has no attribute '%s'" % (self.__class__.__name__, name))
  188. self._cache[name] = attrvalue
  189. return attrvalue
  190. def findBestProvider(self, pn):
  191. return self.tinfoil.find_best_provider(pn)
  192. class Tinfoil:
  193. def __init__(self, output=sys.stdout, tracking=False, setup_logging=True):
  194. self.logger = logging.getLogger('BitBake')
  195. self.config_data = None
  196. self.cooker = None
  197. self.tracking = tracking
  198. self.ui_module = None
  199. self.server_connection = None
  200. self.recipes_parsed = False
  201. self.quiet = 0
  202. if setup_logging:
  203. # This is the *client-side* logger, nothing to do with
  204. # logging messages from the server
  205. bb.msg.logger_create('BitBake', output)
  206. def __enter__(self):
  207. return self
  208. def __exit__(self, type, value, traceback):
  209. self.shutdown()
  210. def prepare(self, config_only=False, config_params=None, quiet=0, extra_features=None):
  211. self.quiet = quiet
  212. if self.tracking:
  213. extrafeatures = [bb.cooker.CookerFeatures.BASEDATASTORE_TRACKING]
  214. else:
  215. extrafeatures = []
  216. if extra_features:
  217. extrafeatures += extra_features
  218. if not config_params:
  219. config_params = TinfoilConfigParameters(config_only=config_only, quiet=quiet)
  220. cookerconfig = CookerConfiguration()
  221. cookerconfig.setConfigParameters(config_params)
  222. self.server_connection, ui_module = setup_bitbake(config_params,
  223. cookerconfig,
  224. extrafeatures,
  225. setup_logging=False)
  226. self.ui_module = ui_module
  227. # Ensure the path to bitbake's bin directory is in PATH so that things like
  228. # bitbake-worker can be run (usually this is the case, but it doesn't have to be)
  229. path = os.getenv('PATH').split(':')
  230. bitbakebinpath = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'bin'))
  231. for entry in path:
  232. if entry.endswith(os.sep):
  233. entry = entry[:-1]
  234. if os.path.abspath(entry) == bitbakebinpath:
  235. break
  236. else:
  237. path.insert(0, bitbakebinpath)
  238. os.environ['PATH'] = ':'.join(path)
  239. if self.server_connection:
  240. _server_connections.append(self.server_connection)
  241. if config_only:
  242. config_params.updateToServer(self.server_connection.connection, os.environ.copy())
  243. self.run_command('parseConfiguration')
  244. else:
  245. self.run_actions(config_params)
  246. self.recipes_parsed = True
  247. self.config_data = bb.data.init()
  248. connector = TinfoilDataStoreConnector(self, None)
  249. self.config_data.setVar('_remote_data', connector)
  250. self.cooker = TinfoilCookerAdapter(self)
  251. self.cooker_data = self.cooker.recipecaches['']
  252. else:
  253. raise Exception('Failed to start bitbake server')
  254. def run_actions(self, config_params):
  255. """
  256. Run the actions specified in config_params through the UI.
  257. """
  258. ret = self.ui_module.main(self.server_connection.connection, self.server_connection.events, config_params)
  259. if ret:
  260. raise TinfoilUIException(ret)
  261. def parseRecipes(self):
  262. """
  263. Legacy function - use parse_recipes() instead.
  264. """
  265. self.parse_recipes()
  266. def parse_recipes(self):
  267. """
  268. Load information on all recipes. Normally you should specify
  269. config_only=False when calling prepare() instead of using this
  270. function; this function is designed for situations where you need
  271. to initialise Tinfoil and use it with config_only=True first and
  272. then conditionally call this function to parse recipes later.
  273. """
  274. config_params = TinfoilConfigParameters(config_only=False)
  275. self.run_actions(config_params)
  276. self.recipes_parsed = True
  277. def run_command(self, command, *params):
  278. """
  279. Run a command on the server (as implemented in bb.command).
  280. Note that there are two types of command - synchronous and
  281. asynchronous; in order to receive the results of asynchronous
  282. commands you will need to set an appropriate event mask
  283. using set_event_mask() and listen for the result using
  284. wait_event() - with the correct event mask you'll at least get
  285. bb.command.CommandCompleted and possibly other events before
  286. that depending on the command.
  287. """
  288. if not self.server_connection:
  289. raise Exception('Not connected to server (did you call .prepare()?)')
  290. commandline = [command]
  291. if params:
  292. commandline.extend(params)
  293. result = self.server_connection.connection.runCommand(commandline)
  294. if result[1]:
  295. raise TinfoilCommandFailed(result[1])
  296. return result[0]
  297. def set_event_mask(self, eventlist):
  298. """Set the event mask which will be applied within wait_event()"""
  299. if not self.server_connection:
  300. raise Exception('Not connected to server (did you call .prepare()?)')
  301. llevel, debug_domains = bb.msg.constructLogOptions()
  302. ret = self.run_command('setEventMask', self.server_connection.connection.getEventHandle(), llevel, debug_domains, eventlist)
  303. if not ret:
  304. raise Exception('setEventMask failed')
  305. def wait_event(self, timeout=0):
  306. """
  307. Wait for an event from the server for the specified time.
  308. A timeout of 0 means don't wait if there are no events in the queue.
  309. Returns the next event in the queue or None if the timeout was
  310. reached. Note that in order to recieve any events you will
  311. first need to set the internal event mask using set_event_mask()
  312. (otherwise whatever event mask the UI set up will be in effect).
  313. """
  314. if not self.server_connection:
  315. raise Exception('Not connected to server (did you call .prepare()?)')
  316. return self.server_connection.events.waitEvent(timeout)
  317. def get_overlayed_recipes(self):
  318. return defaultdict(list, self.run_command('getOverlayedRecipes'))
  319. def get_skipped_recipes(self):
  320. return OrderedDict(self.run_command('getSkippedRecipes'))
  321. def get_all_providers(self):
  322. return defaultdict(list, self.run_command('allProviders'))
  323. def find_providers(self):
  324. return self.run_command('findProviders')
  325. def find_best_provider(self, pn):
  326. return self.run_command('findBestProvider', pn)
  327. def get_runtime_providers(self, rdep):
  328. return self.run_command('getRuntimeProviders', rdep)
  329. def get_recipe_file(self, pn):
  330. """
  331. Get the file name for the specified recipe/target. Raises
  332. bb.providers.NoProvider if there is no match or the recipe was
  333. skipped.
  334. """
  335. best = self.find_best_provider(pn)
  336. if not best or (len(best) > 3 and not best[3]):
  337. skiplist = self.get_skipped_recipes()
  338. taskdata = bb.taskdata.TaskData(None, skiplist=skiplist)
  339. skipreasons = taskdata.get_reasons(pn)
  340. if skipreasons:
  341. raise bb.providers.NoProvider('%s is unavailable:\n %s' % (pn, ' \n'.join(skipreasons)))
  342. else:
  343. raise bb.providers.NoProvider('Unable to find any recipe file matching "%s"' % pn)
  344. return best[3]
  345. def get_file_appends(self, fn):
  346. return self.run_command('getFileAppends', fn)
  347. def parse_recipe(self, pn):
  348. """
  349. Parse the specified recipe and return a datastore object
  350. representing the environment for the recipe.
  351. """
  352. fn = self.get_recipe_file(pn)
  353. return self.parse_recipe_file(fn)
  354. def parse_recipe_file(self, fn, appends=True, appendlist=None, config_data=None):
  355. """
  356. Parse the specified recipe file (with or without bbappends)
  357. and return a datastore object representing the environment
  358. for the recipe.
  359. Parameters:
  360. fn: recipe file to parse - can be a file path or virtual
  361. specification
  362. appends: True to apply bbappends, False otherwise
  363. appendlist: optional list of bbappend files to apply, if you
  364. want to filter them
  365. config_data: custom config datastore to use. NOTE: if you
  366. specify config_data then you cannot use a virtual
  367. specification for fn.
  368. """
  369. if appends and appendlist == []:
  370. appends = False
  371. if config_data:
  372. dctr = bb.remotedata.RemoteDatastores.transmit_datastore(config_data)
  373. dscon = self.run_command('parseRecipeFile', fn, appends, appendlist, dctr)
  374. else:
  375. dscon = self.run_command('parseRecipeFile', fn, appends, appendlist)
  376. if dscon:
  377. return self._reconvert_type(dscon, 'DataStoreConnectionHandle')
  378. else:
  379. return None
  380. def build_file(self, buildfile, task, internal=True):
  381. """
  382. Runs the specified task for just a single recipe (i.e. no dependencies).
  383. This is equivalent to bitbake -b, except with the default internal=True
  384. no warning about dependencies will be produced, normal info messages
  385. from the runqueue will be silenced and BuildInit, BuildStarted and
  386. BuildCompleted events will not be fired.
  387. """
  388. return self.run_command('buildFile', buildfile, task, internal)
  389. def build_targets(self, targets, task=None, handle_events=True, extra_events=None, event_callback=None):
  390. """
  391. Builds the specified targets. This is equivalent to a normal invocation
  392. of bitbake. Has built-in event handling which is enabled by default and
  393. can be extended if needed.
  394. Parameters:
  395. targets:
  396. One or more targets to build. Can be a list or a
  397. space-separated string.
  398. task:
  399. The task to run; if None then the value of BB_DEFAULT_TASK
  400. will be used. Default None.
  401. handle_events:
  402. True to handle events in a similar way to normal bitbake
  403. invocation with knotty; False to return immediately (on the
  404. assumption that the caller will handle the events instead).
  405. Default True.
  406. extra_events:
  407. An optional list of events to add to the event mask (if
  408. handle_events=True). If you add events here you also need
  409. to specify a callback function in event_callback that will
  410. handle the additional events. Default None.
  411. event_callback:
  412. An optional function taking a single parameter which
  413. will be called first upon receiving any event (if
  414. handle_events=True) so that the caller can override or
  415. extend the event handling. Default None.
  416. """
  417. if isinstance(targets, str):
  418. targets = targets.split()
  419. if not task:
  420. task = self.config_data.getVar('BB_DEFAULT_TASK')
  421. if handle_events:
  422. # A reasonable set of default events matching up with those we handle below
  423. eventmask = [
  424. 'bb.event.BuildStarted',
  425. 'bb.event.BuildCompleted',
  426. 'logging.LogRecord',
  427. 'bb.event.NoProvider',
  428. 'bb.command.CommandCompleted',
  429. 'bb.command.CommandFailed',
  430. 'bb.build.TaskStarted',
  431. 'bb.build.TaskFailed',
  432. 'bb.build.TaskSucceeded',
  433. 'bb.build.TaskFailedSilent',
  434. 'bb.build.TaskProgress',
  435. 'bb.runqueue.runQueueTaskStarted',
  436. 'bb.runqueue.sceneQueueTaskStarted',
  437. 'bb.event.ProcessStarted',
  438. 'bb.event.ProcessProgress',
  439. 'bb.event.ProcessFinished',
  440. ]
  441. if extra_events:
  442. eventmask.extend(extra_events)
  443. ret = self.set_event_mask(eventmask)
  444. ret = self.run_command('buildTargets', targets, task)
  445. if handle_events:
  446. result = False
  447. # Borrowed from knotty, instead somewhat hackily we use the helper
  448. # as the object to store "shutdown" on
  449. helper = bb.ui.uihelper.BBUIHelper()
  450. # We set up logging optionally in the constructor so now we need to
  451. # grab the handlers to pass to TerminalFilter
  452. console = None
  453. errconsole = None
  454. for handler in self.logger.handlers:
  455. if isinstance(handler, logging.StreamHandler):
  456. if handler.stream == sys.stdout:
  457. console = handler
  458. elif handler.stream == sys.stderr:
  459. errconsole = handler
  460. format_str = "%(levelname)s: %(message)s"
  461. format = bb.msg.BBLogFormatter(format_str)
  462. helper.shutdown = 0
  463. parseprogress = None
  464. termfilter = bb.ui.knotty.TerminalFilter(helper, helper, console, errconsole, format, quiet=self.quiet)
  465. try:
  466. while True:
  467. try:
  468. event = self.wait_event(0.25)
  469. if event:
  470. if event_callback and event_callback(event):
  471. continue
  472. if helper.eventHandler(event):
  473. continue
  474. if isinstance(event, bb.event.ProcessStarted):
  475. if self.quiet > 1:
  476. continue
  477. parseprogress = bb.ui.knotty.new_progress(event.processname, event.total)
  478. parseprogress.start(False)
  479. continue
  480. if isinstance(event, bb.event.ProcessProgress):
  481. if self.quiet > 1:
  482. continue
  483. if parseprogress:
  484. parseprogress.update(event.progress)
  485. else:
  486. bb.warn("Got ProcessProgress event for someting that never started?")
  487. continue
  488. if isinstance(event, bb.event.ProcessFinished):
  489. if self.quiet > 1:
  490. continue
  491. if parseprogress:
  492. parseprogress.finish()
  493. parseprogress = None
  494. continue
  495. if isinstance(event, bb.command.CommandCompleted):
  496. result = True
  497. break
  498. if isinstance(event, bb.command.CommandFailed):
  499. self.logger.error(str(event))
  500. result = False
  501. break
  502. if isinstance(event, logging.LogRecord):
  503. if event.taskpid == 0 or event.levelno > logging.INFO:
  504. self.logger.handle(event)
  505. continue
  506. if isinstance(event, bb.event.NoProvider):
  507. self.logger.error(str(event))
  508. result = False
  509. break
  510. elif helper.shutdown > 1:
  511. break
  512. termfilter.updateFooter()
  513. except KeyboardInterrupt:
  514. termfilter.clearFooter()
  515. if helper.shutdown == 1:
  516. print("\nSecond Keyboard Interrupt, stopping...\n")
  517. ret = self.run_command("stateForceShutdown")
  518. if ret and ret[2]:
  519. self.logger.error("Unable to cleanly stop: %s" % ret[2])
  520. elif helper.shutdown == 0:
  521. print("\nKeyboard Interrupt, closing down...\n")
  522. interrupted = True
  523. ret = self.run_command("stateShutdown")
  524. if ret and ret[2]:
  525. self.logger.error("Unable to cleanly shutdown: %s" % ret[2])
  526. helper.shutdown = helper.shutdown + 1
  527. termfilter.clearFooter()
  528. finally:
  529. termfilter.finish()
  530. if helper.failed_tasks:
  531. result = False
  532. return result
  533. else:
  534. return ret
  535. def shutdown(self):
  536. if self.server_connection:
  537. self.run_command('clientComplete')
  538. _server_connections.remove(self.server_connection)
  539. bb.event.ui_queue = []
  540. self.server_connection.terminate()
  541. self.server_connection = None
  542. def _reconvert_type(self, obj, origtypename):
  543. """
  544. Convert an object back to the right type, in the case
  545. that marshalling has changed it (especially with xmlrpc)
  546. """
  547. supported_types = {
  548. 'set': set,
  549. 'DataStoreConnectionHandle': bb.command.DataStoreConnectionHandle,
  550. }
  551. origtype = supported_types.get(origtypename, None)
  552. if origtype is None:
  553. raise Exception('Unsupported type "%s"' % origtypename)
  554. if type(obj) == origtype:
  555. newobj = obj
  556. elif isinstance(obj, dict):
  557. # New style class
  558. newobj = origtype()
  559. for k,v in obj.items():
  560. setattr(newobj, k, v)
  561. else:
  562. # Assume we can coerce the type
  563. newobj = origtype(obj)
  564. if isinstance(newobj, bb.command.DataStoreConnectionHandle):
  565. connector = TinfoilDataStoreConnector(self, newobj.dsindex)
  566. newobj = bb.data.init()
  567. newobj.setVar('_remote_data', connector)
  568. return newobj
  569. class TinfoilConfigParameters(BitBakeConfigParameters):
  570. def __init__(self, config_only, **options):
  571. self.initial_options = options
  572. # Apply some sane defaults
  573. if not 'parse_only' in options:
  574. self.initial_options['parse_only'] = not config_only
  575. #if not 'status_only' in options:
  576. # self.initial_options['status_only'] = config_only
  577. if not 'ui' in options:
  578. self.initial_options['ui'] = 'knotty'
  579. if not 'argv' in options:
  580. self.initial_options['argv'] = []
  581. super(TinfoilConfigParameters, self).__init__()
  582. def parseCommandLine(self, argv=None):
  583. # We don't want any parameters parsed from the command line
  584. opts = super(TinfoilConfigParameters, self).parseCommandLine([])
  585. for key, val in self.initial_options.items():
  586. setattr(opts[0], key, val)
  587. return opts