-
-
Save melioratus/90252660aa710ef0f5219a1828ce9a33 to your computer and use it in GitHub Desktop.
ruby's OptionParser to get subcommands
This file contains hidden or 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 | |
unless command | |
STDERR.puts "ERROR: no subcommand" | |
STDERR.puts global # prints usage | |
exit(-1) | |
end | |
subcommands[command].order! | |
puts "Command: #{command} " | |
p options | |
puts "ARGV:" | |
p ARGV |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Added fix