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.
This commit is contained in:
Mitchell Hashimoto 2012-06-01 15:57:55 +02:00
parent 100e1f7eb0
commit 83917a6bb0
1 changed files with 46 additions and 0 deletions

View File

@ -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.