Created
June 20, 2010 10:47
-
-
Save rkumar/445735 to your computer and use it in GitHub Desktop.
ruby's OptionParser to get subcommands
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby -w | |
## Using ruby's standard OptionParser to get subcommand's in command line arguments | |
## Note you cannot do: opt.rb help command | |
## other options are commander, main, GLI, trollop... | |
# run it as | |
# ruby opt.rb --help | |
# ruby opt.rb foo --help | |
# ruby opt.rb foo -q | |
# etc | |
require 'optparse' | |
options = {} | |
subtext = <<HELP | |
Commonly used command are: | |
foo : does something awesome | |
baz : does something fantastic | |
See 'opt.rb COMMAND --help' for more information on a specific command. | |
HELP | |
global = OptionParser.new do |opts| | |
opts.banner = "Usage: opt.rb [options] [subcommand [options]]" | |
opts.on("-v", "--[no-]verbose", "Run verbosely") do |v| | |
options[:verbose] = v | |
end | |
opts.separator "" | |
opts.separator subtext | |
end | |
#end.parse! | |
subcommands = { | |
'foo' => OptionParser.new do |opts| | |
opts.banner = "Usage: foo [options]" | |
opts.on("-f", "--[no-]force", "force verbosely") do |v| | |
options[:force] = v | |
end | |
end, | |
'baz' => OptionParser.new do |opts| | |
opts.banner = "Usage: baz [options]" | |
opts.on("-q", "--[no-]quiet", "quietly run ") do |v| | |
options[:quiet] = v | |
end | |
end | |
} | |
global.order! | |
command = ARGV.shift | |
subcommands[command].order! | |
puts "Command: #{command} " | |
p options | |
puts "ARGV:" | |
p ARGV |
The first level of help is just the subtext. As specified by "See 'opt.rb COMMAND --help' for more information on a specific command." you have to include the command and then --help, so it acts as an argument for the command. Then the help for that particular command will be printed.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I only see the following when I invoke with tool with
-h
:Any idea why the
subcommands
help is not being printed? I was expecting the help text for-f
and-q
to be included in the output.