From b292008f3ba433d3c7a39690b64a0df3a60e4cf6 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Sat, 17 Dec 2011 09:24:38 -0800 Subject: [PATCH] Change parse_options a bit to automatically add help and detect invalid options --- lib/vagrant/command/base.rb | 21 ++++++++++++++++++++- lib/vagrant/command/up.rb | 6 +----- test/unit/vagrant/command/base_test.rb | 14 ++++++++++++++ 3 files changed, 35 insertions(+), 6 deletions(-) diff --git a/lib/vagrant/command/base.rb b/lib/vagrant/command/base.rb index 09a2a01f3..8a4498fd8 100644 --- a/lib/vagrant/command/base.rb +++ b/lib/vagrant/command/base.rb @@ -23,11 +23,30 @@ module Vagrant # Parses the options given an OptionParser instance. # # 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) + # Creating a shallow copy of the arguments so the OptionParser + # doesn't destroy the originals. 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) return argv + rescue OptionParser::InvalidOption + puts opts.help + return nil end # Yields a VM for each target VM for the command. diff --git a/lib/vagrant/command/up.rb b/lib/vagrant/command/up.rb index d647a2844..4b33933e6 100644 --- a/lib/vagrant/command/up.rb +++ b/lib/vagrant/command/up.rb @@ -14,15 +14,11 @@ module Vagrant opts.on("--[no-]provision", "Enable or disable provisioning") do |p| options[:provision] = p end - - opts.on("-h", "--help", "Print this help") do - puts opts.help - return - end end # Parse the options argv = parse_options(opts) + return if !argv # Go over each VM and bring it up @logger.debug("'Up' each target VM...") diff --git a/test/unit/vagrant/command/base_test.rb b/test/unit/vagrant/command/base_test.rb index bab3fd35e..b3ea69b97 100644 --- a/test/unit/vagrant/command/base_test.rb +++ b/test/unit/vagrant/command/base_test.rb @@ -24,6 +24,20 @@ describe Vagrant::Command::Base do options[:f].should be result.should == ["foo"] 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 describe "target VMs" do