From 83917a6bb007a5abd5e37208b676138b8d6a4479 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Fri, 1 Jun 2012 15:57:55 +0200 Subject: [PATCH] Added `arg` and `arg_extra` API to easy commands Easy commands can now easily get arguments from the command line. Using `arg`, you can get named arguments on the command line, such as "--foo" or "-f" With `arg_extra`, you can get any remaining arguments after a "--" on the command line, which is a common pattern used to grab longer parameters. --- lib/vagrant/easy/command_api.rb | 46 +++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/lib/vagrant/easy/command_api.rb b/lib/vagrant/easy/command_api.rb index 38b2cd571..5369da49d 100644 --- a/lib/vagrant/easy/command_api.rb +++ b/lib/vagrant/easy/command_api.rb @@ -1,4 +1,5 @@ require "delegate" +require "optparse" require "vagrant/easy/operations" @@ -16,6 +17,51 @@ module Vagrant @vm = vm end + # Gets the value of an argument from the command line. Many arguments + # can be given as a parameter and the first matching one will be returned. + # + # @return [String] + def arg(*names) + # Mangle the names a bit to add "=VALUE" to every flag. + names = names.map do |name| + "#{name}=VALUE" + end + + # Create a basic option parser + parser = OptionParser.new + + # Add on a matcher for this thing + result = nil + parser.on(*names) do |value| + result = value + end + + begin + parser.parse!(@argv.dup) + rescue OptionParser::MissingArgument + # Missing argument means the argument existed but had no data, + # so we mark it as an empty string + result = "" + rescue OptionParser::InvalidOption + # Ignore! + end + + # Return the results + result + end + + # Returns any extra arguments that are past a "--" on the command line. + # + # @return [String] + def arg_extra + # Split the arguments and remove the "--" + remaining = @argv.drop_while { |v| v != "--" } + remaining.shift + + # Return the remaining arguments + remaining.join(" ") + end + # Outputs an error message to the UI. # # @param [String] message Message to send.