shell.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. # ex:ts=4:sw=4:sts=4:et
  2. # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
  3. ##########################################################################
  4. #
  5. # Copyright (C) 2005-2006 Michael 'Mickey' Lauer <mickey@Vanille.de>
  6. # Copyright (C) 2005-2006 Vanille Media
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License version 2 as
  10. # published by the Free Software Foundation.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. #
  21. ##########################################################################
  22. #
  23. # Thanks to:
  24. # * Holger Freyther <zecke@handhelds.org>
  25. # * Justin Patrin <papercrane@reversefold.com>
  26. #
  27. ##########################################################################
  28. """
  29. BitBake Shell
  30. IDEAS:
  31. * list defined tasks per package
  32. * list classes
  33. * toggle force
  34. * command to reparse just one (or more) bbfile(s)
  35. * automatic check if reparsing is necessary (inotify?)
  36. * frontend for bb file manipulation
  37. * more shell-like features:
  38. - output control, i.e. pipe output into grep, sort, etc.
  39. - job control, i.e. bring running commands into background and foreground
  40. * start parsing in background right after startup
  41. * ncurses interface
  42. PROBLEMS:
  43. * force doesn't always work
  44. * readline completion for commands with more than one parameters
  45. """
  46. ##########################################################################
  47. # Import and setup global variables
  48. ##########################################################################
  49. from __future__ import print_function
  50. from functools import reduce
  51. try:
  52. set
  53. except NameError:
  54. from sets import Set as set
  55. import sys, os, readline, socket, httplib, urllib, commands, popen2, shlex, Queue, fnmatch
  56. from bb import data, parse, build, cache, taskdata, runqueue, providers as Providers
  57. __version__ = "0.5.3.1"
  58. __credits__ = """BitBake Shell Version %s (C) 2005 Michael 'Mickey' Lauer <mickey@Vanille.de>
  59. Type 'help' for more information, press CTRL-D to exit.""" % __version__
  60. cmds = {}
  61. leave_mainloop = False
  62. last_exception = None
  63. cooker = None
  64. parsed = False
  65. debug = os.environ.get( "BBSHELL_DEBUG", "" )
  66. ##########################################################################
  67. # Class BitBakeShellCommands
  68. ##########################################################################
  69. class BitBakeShellCommands:
  70. """This class contains the valid commands for the shell"""
  71. def __init__( self, shell ):
  72. """Register all the commands"""
  73. self._shell = shell
  74. for attr in BitBakeShellCommands.__dict__:
  75. if not attr.startswith( "_" ):
  76. if attr.endswith( "_" ):
  77. command = attr[:-1].lower()
  78. else:
  79. command = attr[:].lower()
  80. method = getattr( BitBakeShellCommands, attr )
  81. debugOut( "registering command '%s'" % command )
  82. # scan number of arguments
  83. usage = getattr( method, "usage", "" )
  84. if usage != "<...>":
  85. numArgs = len( usage.split() )
  86. else:
  87. numArgs = -1
  88. shell.registerCommand( command, method, numArgs, "%s %s" % ( command, usage ), method.__doc__ )
  89. def _checkParsed( self ):
  90. if not parsed:
  91. print("SHELL: This command needs to parse bbfiles...")
  92. self.parse( None )
  93. def _findProvider( self, item ):
  94. self._checkParsed()
  95. # Need to use taskData for this information
  96. preferred = data.getVar( "PREFERRED_PROVIDER_%s" % item, cooker.configuration.data, 1 )
  97. if not preferred: preferred = item
  98. try:
  99. lv, lf, pv, pf = Providers.findBestProvider(preferred, cooker.configuration.data, cooker.status)
  100. except KeyError:
  101. if item in cooker.status.providers:
  102. pf = cooker.status.providers[item][0]
  103. else:
  104. pf = None
  105. return pf
  106. def alias( self, params ):
  107. """Register a new name for a command"""
  108. new, old = params
  109. if not old in cmds:
  110. print("ERROR: Command '%s' not known" % old)
  111. else:
  112. cmds[new] = cmds[old]
  113. print("OK")
  114. alias.usage = "<alias> <command>"
  115. def buffer( self, params ):
  116. """Dump specified output buffer"""
  117. index = params[0]
  118. print(self._shell.myout.buffer( int( index ) ))
  119. buffer.usage = "<index>"
  120. def buffers( self, params ):
  121. """Show the available output buffers"""
  122. commands = self._shell.myout.bufferedCommands()
  123. if not commands:
  124. print("SHELL: No buffered commands available yet. Start doing something.")
  125. else:
  126. print("="*35, "Available Output Buffers", "="*27)
  127. for index, cmd in enumerate( commands ):
  128. print("| %s %s" % ( str( index ).ljust( 3 ), cmd ))
  129. print("="*88)
  130. def build( self, params, cmd = "build" ):
  131. """Build a providee"""
  132. global last_exception
  133. globexpr = params[0]
  134. self._checkParsed()
  135. names = globfilter( cooker.status.pkg_pn, globexpr )
  136. if len( names ) == 0: names = [ globexpr ]
  137. print("SHELL: Building %s" % ' '.join( names ))
  138. td = taskdata.TaskData(cooker.configuration.abort)
  139. localdata = data.createCopy(cooker.configuration.data)
  140. data.update_data(localdata)
  141. data.expandKeys(localdata)
  142. try:
  143. tasks = []
  144. for name in names:
  145. td.add_provider(localdata, cooker.status, name)
  146. providers = td.get_provider(name)
  147. if len(providers) == 0:
  148. raise Providers.NoProvider
  149. tasks.append([name, "do_%s" % cmd])
  150. td.add_unresolved(localdata, cooker.status)
  151. rq = runqueue.RunQueue(cooker, localdata, cooker.status, td, tasks)
  152. rq.prepare_runqueue()
  153. rq.execute_runqueue()
  154. except Providers.NoProvider:
  155. print("ERROR: No Provider")
  156. last_exception = Providers.NoProvider
  157. except runqueue.TaskFailure as fnids:
  158. last_exception = runqueue.TaskFailure
  159. except build.FuncFailed as e:
  160. print("ERROR: Couldn't build '%s'" % names)
  161. last_exception = e
  162. build.usage = "<providee>"
  163. def clean( self, params ):
  164. """Clean a providee"""
  165. self.build( params, "clean" )
  166. clean.usage = "<providee>"
  167. def compile( self, params ):
  168. """Execute 'compile' on a providee"""
  169. self.build( params, "compile" )
  170. compile.usage = "<providee>"
  171. def configure( self, params ):
  172. """Execute 'configure' on a providee"""
  173. self.build( params, "configure" )
  174. configure.usage = "<providee>"
  175. def install( self, params ):
  176. """Execute 'install' on a providee"""
  177. self.build( params, "install" )
  178. install.usage = "<providee>"
  179. def edit( self, params ):
  180. """Call $EDITOR on a providee"""
  181. name = params[0]
  182. bbfile = self._findProvider( name )
  183. if bbfile is not None:
  184. os.system( "%s %s" % ( os.environ.get( "EDITOR", "vi" ), bbfile ) )
  185. else:
  186. print("ERROR: Nothing provides '%s'" % name)
  187. edit.usage = "<providee>"
  188. def environment( self, params ):
  189. """Dump out the outer BitBake environment"""
  190. cooker.showEnvironment()
  191. def exit_( self, params ):
  192. """Leave the BitBake Shell"""
  193. debugOut( "setting leave_mainloop to true" )
  194. global leave_mainloop
  195. leave_mainloop = True
  196. def fetch( self, params ):
  197. """Fetch a providee"""
  198. self.build( params, "fetch" )
  199. fetch.usage = "<providee>"
  200. def fileBuild( self, params, cmd = "build" ):
  201. """Parse and build a .bb file"""
  202. global last_exception
  203. name = params[0]
  204. bf = completeFilePath( name )
  205. print("SHELL: Calling '%s' on '%s'" % ( cmd, bf ))
  206. try:
  207. cooker.buildFile(bf, cmd)
  208. except parse.ParseError:
  209. print("ERROR: Unable to open or parse '%s'" % bf)
  210. except build.FuncFailed as e:
  211. print("ERROR: Couldn't build '%s'" % name)
  212. last_exception = e
  213. fileBuild.usage = "<bbfile>"
  214. def fileClean( self, params ):
  215. """Clean a .bb file"""
  216. self.fileBuild( params, "clean" )
  217. fileClean.usage = "<bbfile>"
  218. def fileEdit( self, params ):
  219. """Call $EDITOR on a .bb file"""
  220. name = params[0]
  221. os.system( "%s %s" % ( os.environ.get( "EDITOR", "vi" ), completeFilePath( name ) ) )
  222. fileEdit.usage = "<bbfile>"
  223. def fileRebuild( self, params ):
  224. """Rebuild (clean & build) a .bb file"""
  225. self.fileBuild( params, "rebuild" )
  226. fileRebuild.usage = "<bbfile>"
  227. def fileReparse( self, params ):
  228. """(re)Parse a bb file"""
  229. bbfile = params[0]
  230. print("SHELL: Parsing '%s'" % bbfile)
  231. parse.update_mtime( bbfile )
  232. cooker.parser.reparse(bbfile)
  233. if False: #fromCache:
  234. print("SHELL: File has not been updated, not reparsing")
  235. else:
  236. print("SHELL: Parsed")
  237. fileReparse.usage = "<bbfile>"
  238. def abort( self, params ):
  239. """Toggle abort task execution flag (see bitbake -k)"""
  240. cooker.configuration.abort = not cooker.configuration.abort
  241. print("SHELL: Abort Flag is now '%s'" % repr( cooker.configuration.abort ))
  242. def force( self, params ):
  243. """Toggle force task execution flag (see bitbake -f)"""
  244. cooker.configuration.force = not cooker.configuration.force
  245. print("SHELL: Force Flag is now '%s'" % repr( cooker.configuration.force ))
  246. def help( self, params ):
  247. """Show a comprehensive list of commands and their purpose"""
  248. print("="*30, "Available Commands", "="*30)
  249. for cmd in sorted(cmds):
  250. function, numparams, usage, helptext = cmds[cmd]
  251. print("| %s | %s" % (usage.ljust(30), helptext))
  252. print("="*78)
  253. def lastError( self, params ):
  254. """Show the reason or log that was produced by the last BitBake event exception"""
  255. if last_exception is None:
  256. print("SHELL: No Errors yet (Phew)...")
  257. else:
  258. reason, event = last_exception.args
  259. print("SHELL: Reason for the last error: '%s'" % reason)
  260. if ':' in reason:
  261. msg, filename = reason.split( ':' )
  262. filename = filename.strip()
  263. print("SHELL: Dumping log file for last error:")
  264. try:
  265. print(open( filename ).read())
  266. except IOError:
  267. print("ERROR: Couldn't open '%s'" % filename)
  268. def match( self, params ):
  269. """Dump all files or providers matching a glob expression"""
  270. what, globexpr = params
  271. if what == "files":
  272. self._checkParsed()
  273. for key in globfilter( cooker.status.pkg_fn, globexpr ): print(key)
  274. elif what == "providers":
  275. self._checkParsed()
  276. for key in globfilter( cooker.status.pkg_pn, globexpr ): print(key)
  277. else:
  278. print("Usage: match %s" % self.print_.usage)
  279. match.usage = "<files|providers> <glob>"
  280. def new( self, params ):
  281. """Create a new .bb file and open the editor"""
  282. dirname, filename = params
  283. packages = '/'.join( data.getVar( "BBFILES", cooker.configuration.data, 1 ).split('/')[:-2] )
  284. fulldirname = "%s/%s" % ( packages, dirname )
  285. if not os.path.exists( fulldirname ):
  286. print("SHELL: Creating '%s'" % fulldirname)
  287. os.mkdir( fulldirname )
  288. if os.path.exists( fulldirname ) and os.path.isdir( fulldirname ):
  289. if os.path.exists( "%s/%s" % ( fulldirname, filename ) ):
  290. print("SHELL: ERROR: %s/%s already exists" % ( fulldirname, filename ))
  291. return False
  292. print("SHELL: Creating '%s/%s'" % ( fulldirname, filename ))
  293. newpackage = open( "%s/%s" % ( fulldirname, filename ), "w" )
  294. print("""DESCRIPTION = ""
  295. SECTION = ""
  296. AUTHOR = ""
  297. HOMEPAGE = ""
  298. MAINTAINER = ""
  299. LICENSE = "GPL"
  300. PR = "r0"
  301. SRC_URI = ""
  302. #inherit base
  303. #do_configure() {
  304. #
  305. #}
  306. #do_compile() {
  307. #
  308. #}
  309. #do_stage() {
  310. #
  311. #}
  312. #do_install() {
  313. #
  314. #}
  315. """, file=newpackage)
  316. newpackage.close()
  317. os.system( "%s %s/%s" % ( os.environ.get( "EDITOR" ), fulldirname, filename ) )
  318. new.usage = "<directory> <filename>"
  319. def package( self, params ):
  320. """Execute 'package' on a providee"""
  321. self.build( params, "package" )
  322. package.usage = "<providee>"
  323. def pasteBin( self, params ):
  324. """Send a command + output buffer to the pastebin at http://rafb.net/paste"""
  325. index = params[0]
  326. contents = self._shell.myout.buffer( int( index ) )
  327. sendToPastebin( "output of " + params[0], contents )
  328. pasteBin.usage = "<index>"
  329. def pasteLog( self, params ):
  330. """Send the last event exception error log (if there is one) to http://rafb.net/paste"""
  331. if last_exception is None:
  332. print("SHELL: No Errors yet (Phew)...")
  333. else:
  334. reason, event = last_exception.args
  335. print("SHELL: Reason for the last error: '%s'" % reason)
  336. if ':' in reason:
  337. msg, filename = reason.split( ':' )
  338. filename = filename.strip()
  339. print("SHELL: Pasting log file to pastebin...")
  340. file = open( filename ).read()
  341. sendToPastebin( "contents of " + filename, file )
  342. def patch( self, params ):
  343. """Execute 'patch' command on a providee"""
  344. self.build( params, "patch" )
  345. patch.usage = "<providee>"
  346. def parse( self, params ):
  347. """(Re-)parse .bb files and calculate the dependency graph"""
  348. cooker.status = cache.CacheData(cooker.caches_array)
  349. ignore = data.getVar("ASSUME_PROVIDED", cooker.configuration.data, 1) or ""
  350. cooker.status.ignored_dependencies = set( ignore.split() )
  351. cooker.handleCollections( data.getVar("BBFILE_COLLECTIONS", cooker.configuration.data, 1) )
  352. (filelist, masked) = cooker.collect_bbfiles()
  353. cooker.parse_bbfiles(filelist, masked, cooker.myProgressCallback)
  354. cooker.buildDepgraph()
  355. global parsed
  356. parsed = True
  357. print()
  358. def reparse( self, params ):
  359. """(re)Parse a providee's bb file"""
  360. bbfile = self._findProvider( params[0] )
  361. if bbfile is not None:
  362. print("SHELL: Found bbfile '%s' for '%s'" % ( bbfile, params[0] ))
  363. self.fileReparse( [ bbfile ] )
  364. else:
  365. print("ERROR: Nothing provides '%s'" % params[0])
  366. reparse.usage = "<providee>"
  367. def getvar( self, params ):
  368. """Dump the contents of an outer BitBake environment variable"""
  369. var = params[0]
  370. value = data.getVar( var, cooker.configuration.data, 1 )
  371. print(value)
  372. getvar.usage = "<variable>"
  373. def peek( self, params ):
  374. """Dump contents of variable defined in providee's metadata"""
  375. name, var = params
  376. bbfile = self._findProvider( name )
  377. if bbfile is not None:
  378. the_data = cache.Cache.loadDataFull(bbfile, cooker.configuration.data)
  379. value = the_data.getVar( var, 1 )
  380. print(value)
  381. else:
  382. print("ERROR: Nothing provides '%s'" % name)
  383. peek.usage = "<providee> <variable>"
  384. def poke( self, params ):
  385. """Set contents of variable defined in providee's metadata"""
  386. name, var, value = params
  387. bbfile = self._findProvider( name )
  388. if bbfile is not None:
  389. print("ERROR: Sorry, this functionality is currently broken")
  390. #d = cooker.pkgdata[bbfile]
  391. #data.setVar( var, value, d )
  392. # mark the change semi persistant
  393. #cooker.pkgdata.setDirty(bbfile, d)
  394. #print "OK"
  395. else:
  396. print("ERROR: Nothing provides '%s'" % name)
  397. poke.usage = "<providee> <variable> <value>"
  398. def print_( self, params ):
  399. """Dump all files or providers"""
  400. what = params[0]
  401. if what == "files":
  402. self._checkParsed()
  403. for key in cooker.status.pkg_fn: print(key)
  404. elif what == "providers":
  405. self._checkParsed()
  406. for key in cooker.status.providers: print(key)
  407. else:
  408. print("Usage: print %s" % self.print_.usage)
  409. print_.usage = "<files|providers>"
  410. def python( self, params ):
  411. """Enter the expert mode - an interactive BitBake Python Interpreter"""
  412. sys.ps1 = "EXPERT BB>>> "
  413. sys.ps2 = "EXPERT BB... "
  414. import code
  415. interpreter = code.InteractiveConsole( dict( globals() ) )
  416. interpreter.interact( "SHELL: Expert Mode - BitBake Python %s\nType 'help' for more information, press CTRL-D to switch back to BBSHELL." % sys.version )
  417. def showdata( self, params ):
  418. """Execute 'showdata' on a providee"""
  419. cooker.showEnvironment(None, params)
  420. showdata.usage = "<providee>"
  421. def setVar( self, params ):
  422. """Set an outer BitBake environment variable"""
  423. var, value = params
  424. data.setVar( var, value, cooker.configuration.data )
  425. print("OK")
  426. setVar.usage = "<variable> <value>"
  427. def rebuild( self, params ):
  428. """Clean and rebuild a .bb file or a providee"""
  429. self.build( params, "clean" )
  430. self.build( params, "build" )
  431. rebuild.usage = "<providee>"
  432. def shell( self, params ):
  433. """Execute a shell command and dump the output"""
  434. if params != "":
  435. print(commands.getoutput( " ".join( params ) ))
  436. shell.usage = "<...>"
  437. def stage( self, params ):
  438. """Execute 'stage' on a providee"""
  439. self.build( params, "populate_staging" )
  440. stage.usage = "<providee>"
  441. def status( self, params ):
  442. """<just for testing>"""
  443. print("-" * 78)
  444. print("building list = '%s'" % cooker.building_list)
  445. print("build path = '%s'" % cooker.build_path)
  446. print("consider_msgs_cache = '%s'" % cooker.consider_msgs_cache)
  447. print("build stats = '%s'" % cooker.stats)
  448. if last_exception is not None: print("last_exception = '%s'" % repr( last_exception.args ))
  449. print("memory output contents = '%s'" % self._shell.myout._buffer)
  450. def test( self, params ):
  451. """<just for testing>"""
  452. print("testCommand called with '%s'" % params)
  453. def unpack( self, params ):
  454. """Execute 'unpack' on a providee"""
  455. self.build( params, "unpack" )
  456. unpack.usage = "<providee>"
  457. def which( self, params ):
  458. """Computes the providers for a given providee"""
  459. # Need to use taskData for this information
  460. item = params[0]
  461. self._checkParsed()
  462. preferred = data.getVar( "PREFERRED_PROVIDER_%s" % item, cooker.configuration.data, 1 )
  463. if not preferred: preferred = item
  464. try:
  465. lv, lf, pv, pf = Providers.findBestProvider(preferred, cooker.configuration.data, cooker.status)
  466. except KeyError:
  467. lv, lf, pv, pf = (None,)*4
  468. try:
  469. providers = cooker.status.providers[item]
  470. except KeyError:
  471. print("SHELL: ERROR: Nothing provides", preferred)
  472. else:
  473. for provider in providers:
  474. if provider == pf: provider = " (***) %s" % provider
  475. else: provider = " %s" % provider
  476. print(provider)
  477. which.usage = "<providee>"
  478. ##########################################################################
  479. # Common helper functions
  480. ##########################################################################
  481. def completeFilePath( bbfile ):
  482. """Get the complete bbfile path"""
  483. if not cooker.status: return bbfile
  484. if not cooker.status.pkg_fn: return bbfile
  485. for key in cooker.status.pkg_fn:
  486. if key.endswith( bbfile ):
  487. return key
  488. return bbfile
  489. def sendToPastebin( desc, content ):
  490. """Send content to http://oe.pastebin.com"""
  491. mydata = {}
  492. mydata["lang"] = "Plain Text"
  493. mydata["desc"] = desc
  494. mydata["cvt_tabs"] = "No"
  495. mydata["nick"] = "%s@%s" % ( os.environ.get( "USER", "unknown" ), socket.gethostname() or "unknown" )
  496. mydata["text"] = content
  497. params = urllib.urlencode( mydata )
  498. headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
  499. host = "rafb.net"
  500. conn = httplib.HTTPConnection( "%s:80" % host )
  501. conn.request("POST", "/paste/paste.php", params, headers )
  502. response = conn.getresponse()
  503. conn.close()
  504. if response.status == 302:
  505. location = response.getheader( "location" ) or "unknown"
  506. print("SHELL: Pasted to http://%s%s" % ( host, location ))
  507. else:
  508. print("ERROR: %s %s" % ( response.status, response.reason ))
  509. def completer( text, state ):
  510. """Return a possible readline completion"""
  511. debugOut( "completer called with text='%s', state='%d'" % ( text, state ) )
  512. if state == 0:
  513. line = readline.get_line_buffer()
  514. if " " in line:
  515. line = line.split()
  516. # we are in second (or more) argument
  517. if line[0] in cmds and hasattr( cmds[line[0]][0], "usage" ): # known command and usage
  518. u = getattr( cmds[line[0]][0], "usage" ).split()[0]
  519. if u == "<variable>":
  520. allmatches = cooker.configuration.data.keys()
  521. elif u == "<bbfile>":
  522. if cooker.status.pkg_fn is None: allmatches = [ "(No Matches Available. Parsed yet?)" ]
  523. else: allmatches = [ x.split("/")[-1] for x in cooker.status.pkg_fn ]
  524. elif u == "<providee>":
  525. if cooker.status.pkg_fn is None: allmatches = [ "(No Matches Available. Parsed yet?)" ]
  526. else: allmatches = cooker.status.providers.iterkeys()
  527. else: allmatches = [ "(No tab completion available for this command)" ]
  528. else: allmatches = [ "(No tab completion available for this command)" ]
  529. else:
  530. # we are in first argument
  531. allmatches = cmds.iterkeys()
  532. completer.matches = [ x for x in allmatches if x[:len(text)] == text ]
  533. #print "completer.matches = '%s'" % completer.matches
  534. if len( completer.matches ) > state:
  535. return completer.matches[state]
  536. else:
  537. return None
  538. def debugOut( text ):
  539. if debug:
  540. sys.stderr.write( "( %s )\n" % text )
  541. def columnize( alist, width = 80 ):
  542. """
  543. A word-wrap function that preserves existing line breaks
  544. and most spaces in the text. Expects that existing line
  545. breaks are posix newlines (\n).
  546. """
  547. return reduce(lambda line, word, width=width: '%s%s%s' %
  548. (line,
  549. ' \n'[(len(line[line.rfind('\n')+1:])
  550. + len(word.split('\n', 1)[0]
  551. ) >= width)],
  552. word),
  553. alist
  554. )
  555. def globfilter( names, pattern ):
  556. return fnmatch.filter( names, pattern )
  557. ##########################################################################
  558. # Class MemoryOutput
  559. ##########################################################################
  560. class MemoryOutput:
  561. """File-like output class buffering the output of the last 10 commands"""
  562. def __init__( self, delegate ):
  563. self.delegate = delegate
  564. self._buffer = []
  565. self.text = []
  566. self._command = None
  567. def startCommand( self, command ):
  568. self._command = command
  569. self.text = []
  570. def endCommand( self ):
  571. if self._command is not None:
  572. if len( self._buffer ) == 10: del self._buffer[0]
  573. self._buffer.append( ( self._command, self.text ) )
  574. def removeLast( self ):
  575. if self._buffer:
  576. del self._buffer[ len( self._buffer ) - 1 ]
  577. self.text = []
  578. self._command = None
  579. def lastBuffer( self ):
  580. if self._buffer:
  581. return self._buffer[ len( self._buffer ) -1 ][1]
  582. def bufferedCommands( self ):
  583. return [ cmd for cmd, output in self._buffer ]
  584. def buffer( self, i ):
  585. if i < len( self._buffer ):
  586. return "BB>> %s\n%s" % ( self._buffer[i][0], "".join( self._buffer[i][1] ) )
  587. else: return "ERROR: Invalid buffer number. Buffer needs to be in (0, %d)" % ( len( self._buffer ) - 1 )
  588. def write( self, text ):
  589. if self._command is not None and text != "BB>> ": self.text.append( text )
  590. if self.delegate is not None: self.delegate.write( text )
  591. def flush( self ):
  592. return self.delegate.flush()
  593. def fileno( self ):
  594. return self.delegate.fileno()
  595. def isatty( self ):
  596. return self.delegate.isatty()
  597. ##########################################################################
  598. # Class BitBakeShell
  599. ##########################################################################
  600. class BitBakeShell:
  601. def __init__( self ):
  602. """Register commands and set up readline"""
  603. self.commandQ = Queue.Queue()
  604. self.commands = BitBakeShellCommands( self )
  605. self.myout = MemoryOutput( sys.stdout )
  606. self.historyfilename = os.path.expanduser( "~/.bbsh_history" )
  607. self.startupfilename = os.path.expanduser( "~/.bbsh_startup" )
  608. readline.set_completer( completer )
  609. readline.set_completer_delims( " " )
  610. readline.parse_and_bind("tab: complete")
  611. try:
  612. readline.read_history_file( self.historyfilename )
  613. except IOError:
  614. pass # It doesn't exist yet.
  615. print(__credits__)
  616. def cleanup( self ):
  617. """Write readline history and clean up resources"""
  618. debugOut( "writing command history" )
  619. try:
  620. readline.write_history_file( self.historyfilename )
  621. except:
  622. print("SHELL: Unable to save command history")
  623. def registerCommand( self, command, function, numparams = 0, usage = "", helptext = "" ):
  624. """Register a command"""
  625. if usage == "": usage = command
  626. if helptext == "": helptext = function.__doc__ or "<not yet documented>"
  627. cmds[command] = ( function, numparams, usage, helptext )
  628. def processCommand( self, command, params ):
  629. """Process a command. Check number of params and print a usage string, if appropriate"""
  630. debugOut( "processing command '%s'..." % command )
  631. try:
  632. function, numparams, usage, helptext = cmds[command]
  633. except KeyError:
  634. print("SHELL: ERROR: '%s' command is not a valid command." % command)
  635. self.myout.removeLast()
  636. else:
  637. if (numparams != -1) and (not len( params ) == numparams):
  638. print("Usage: '%s'" % usage)
  639. return
  640. result = function( self.commands, params )
  641. debugOut( "result was '%s'" % result )
  642. def processStartupFile( self ):
  643. """Read and execute all commands found in $HOME/.bbsh_startup"""
  644. if os.path.exists( self.startupfilename ):
  645. startupfile = open( self.startupfilename, "r" )
  646. for cmdline in startupfile:
  647. debugOut( "processing startup line '%s'" % cmdline )
  648. if not cmdline:
  649. continue
  650. if "|" in cmdline:
  651. print("ERROR: '|' in startup file is not allowed. Ignoring line")
  652. continue
  653. self.commandQ.put( cmdline.strip() )
  654. def main( self ):
  655. """The main command loop"""
  656. while not leave_mainloop:
  657. try:
  658. if self.commandQ.empty():
  659. sys.stdout = self.myout.delegate
  660. cmdline = raw_input( "BB>> " )
  661. sys.stdout = self.myout
  662. else:
  663. cmdline = self.commandQ.get()
  664. if cmdline:
  665. allCommands = cmdline.split( ';' )
  666. for command in allCommands:
  667. pipecmd = None
  668. #
  669. # special case for expert mode
  670. if command == 'python':
  671. sys.stdout = self.myout.delegate
  672. self.processCommand( command, "" )
  673. sys.stdout = self.myout
  674. else:
  675. self.myout.startCommand( command )
  676. if '|' in command: # disable output
  677. command, pipecmd = command.split( '|' )
  678. delegate = self.myout.delegate
  679. self.myout.delegate = None
  680. tokens = shlex.split( command, True )
  681. self.processCommand( tokens[0], tokens[1:] or "" )
  682. self.myout.endCommand()
  683. if pipecmd is not None: # restore output
  684. self.myout.delegate = delegate
  685. pipe = popen2.Popen4( pipecmd )
  686. pipe.tochild.write( "\n".join( self.myout.lastBuffer() ) )
  687. pipe.tochild.close()
  688. sys.stdout.write( pipe.fromchild.read() )
  689. #
  690. except EOFError:
  691. print()
  692. return
  693. except KeyboardInterrupt:
  694. print()
  695. ##########################################################################
  696. # Start function - called from the BitBake command line utility
  697. ##########################################################################
  698. def start( aCooker ):
  699. global cooker
  700. cooker = aCooker
  701. bbshell = BitBakeShell()
  702. bbshell.processStartupFile()
  703. bbshell.main()
  704. bbshell.cleanup()
  705. if __name__ == "__main__":
  706. print("SHELL: Sorry, this program should only be called by BitBake.")