Change parse_options a bit to automatically add help and detect invalid options

This commit is contained in:
Mitchell Hashimoto 2011-12-17 09:24:38 -08:00
parent 43cadfe830
commit b292008f3b
3 changed files with 35 additions and 6 deletions

View File

@ -23,11 +23,30 @@ module Vagrant
# Parses the options given an OptionParser instance. # Parses the options given an OptionParser instance.
# #
# This is a convenience method that properly handles duping the # This is a convenience method that properly handles duping the
# originally argv array so that it is not destroyed. That is all. # originally argv array so that it is not destroyed.
#
# This method will also automatically detect "-h" and "--help"
# and print help. And if any invalid options are detected, the help
# will be printed, as well.
#
# If this method returns `nil`, then you should assume that help
# was printed and parsing failed.
def parse_options(opts) def parse_options(opts)
# Creating a shallow copy of the arguments so the OptionParser
# doesn't destroy the originals.
argv = @argv.dup argv = @argv.dup
# Add the help option, which must be on every command.
opts.on_tail("-h", "--help", "Print this help") do
puts opts.help
return nil
end
opts.parse!(argv) opts.parse!(argv)
return argv return argv
rescue OptionParser::InvalidOption
puts opts.help
return nil
end end
# Yields a VM for each target VM for the command. # Yields a VM for each target VM for the command.

View File

@ -14,15 +14,11 @@ module Vagrant
opts.on("--[no-]provision", "Enable or disable provisioning") do |p| opts.on("--[no-]provision", "Enable or disable provisioning") do |p|
options[:provision] = p options[:provision] = p
end end
opts.on("-h", "--help", "Print this help") do
puts opts.help
return
end
end end
# Parse the options # Parse the options
argv = parse_options(opts) argv = parse_options(opts)
return if !argv
# Go over each VM and bring it up # Go over each VM and bring it up
@logger.debug("'Up' each target VM...") @logger.debug("'Up' each target VM...")

View File

@ -24,6 +24,20 @@ describe Vagrant::Command::Base do
options[:f].should be options[:f].should be
result.should == ["foo"] result.should == ["foo"]
end end
["-h", "--help"].each do |help_string|
it "returns nil and prints the help if '#{help_string}' is given" do
instance = klass.new([help_string], nil)
instance.should_receive(:puts)
instance.parse_options(OptionParser.new).should be_nil
end
end
it "returns nil if invalid options are given" do
instance = klass.new(["-f"], nil)
instance.should_receive(:puts)
instance.parse_options(OptionParser.new).should be_nil
end
end end
describe "target VMs" do describe "target VMs" do