shell.py 31 KB

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