Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ruby's OptionParser to parse sub-commands

I'd like to be able to use ruby's OptionParser to parse sub-commands of the form

COMMAND [GLOBAL FLAGS] [SUB-COMMAND [SUB-COMMAND FLAGS]]

like:

git branch -a
gem list foo

I know I could switch to a different option parser library (like Trollop), but I'm interested in learning how to do this from within OptionParser, since I'd like to learn the library better.

Any tips?

like image 298
rampion Avatar asked Apr 28 '10 20:04

rampion


2 Answers

Figured it out. I need to use OptionParser#order!. It will parse all the options from the start of ARGV until it finds a non-option (that isn't an option argument), removing everything it processes from ARGV, and then it will quit.

So I just need to do something like:

global = OptionParser.new do |opts|   # ... end subcommands = {    'foo' => OptionParser.new do |opts|      # ...    end,    # ...    'baz' => OptionParser.new do |opts|      # ...    end  }   global.order!  subcommands[ARGV.shift].order! 
like image 71
rampion Avatar answered Oct 19 '22 21:10

rampion


It looks like the OptionParser syntax has changed some. I had to use the following so that the arguments array had all of the options not parsed by the opts object.

begin   opts.order!(arguments) rescue OptionParser::InvalidOption => io   # Prepend the invalid option onto the arguments array   arguments = io.recover(arguments) rescue => e   raise "Argument parsing failed: #{e.to_s()}" end 
like image 25
jmace Avatar answered Oct 19 '22 21:10

jmace