return argument value when nargs = 1
This commit is contained in:
parent
056257b8f5
commit
4a693ba1ea
35
lib/yawpa.rb
35
lib/yawpa.rb
@ -9,6 +9,7 @@ require "yawpa/version"
|
||||
# }
|
||||
module Yawpa
|
||||
class UnknownOptionException < Exception; end
|
||||
class InvalidArgumentsException < Exception; end
|
||||
|
||||
module_function
|
||||
def parse(params, options)
|
||||
@ -17,24 +18,42 @@ module Yawpa
|
||||
i = 0
|
||||
while i < params.length
|
||||
param = params[i]
|
||||
if param =~ /^(-+)(.+)$/
|
||||
case $1.length
|
||||
if param =~ /^(-+)([^=]+)(=.+)?$/
|
||||
leader, param_name, val = $1, $2, $3
|
||||
case leader.length
|
||||
when 2
|
||||
param_key = if options[$2]
|
||||
$2
|
||||
elsif options[$2.to_sym]
|
||||
$2.to_sym
|
||||
param_key = if options[param_name]
|
||||
param_name
|
||||
elsif options[param_name.to_sym]
|
||||
param_name.to_sym
|
||||
else
|
||||
nil
|
||||
end
|
||||
if param_key.nil?
|
||||
raise UnknownOptionException.new("Unknown option '#{param}'")
|
||||
raise UnknownOptionException.new("Unknown option '#{param_name}'")
|
||||
end
|
||||
opt_config = options[param_key]
|
||||
nargs = opt_config[:nargs] || 0
|
||||
if nargs == 0
|
||||
opts[param_key] = true
|
||||
elsif nargs.class == FixNum
|
||||
elsif nargs.class == Fixnum
|
||||
n_gathered = 0
|
||||
opts[param_key] = []
|
||||
if val
|
||||
opts[param_key] << val[1, val.length]
|
||||
n_gathered += 1
|
||||
end
|
||||
while n_gathered < nargs
|
||||
if i + 1 >= params.length
|
||||
raise InvalidArgumentsException.new("Not enough arguments supplied for option '#{param_name}'")
|
||||
end
|
||||
i += 1
|
||||
opts[param_key] << params[i]
|
||||
n_gathered += 1
|
||||
end
|
||||
if n_gathered == 1
|
||||
opts[param_key] = opts[param_key][0]
|
||||
end
|
||||
elsif nargs.class == Range
|
||||
end
|
||||
end
|
||||
|
@ -29,5 +29,15 @@ describe Yawpa do
|
||||
opts.include?(:three).should be_false
|
||||
args.should eq(['arg', 'arg2'])
|
||||
end
|
||||
|
||||
it "returns an option's value when nargs = 1" do
|
||||
options = {
|
||||
opt: {nargs: 1},
|
||||
}
|
||||
params = ['--opt', 'val', 'arg']
|
||||
opts, args = Yawpa.parse(params, options)
|
||||
opts[:opt].should eq('val')
|
||||
args.should eq(['arg'])
|
||||
end
|
||||
end
|
||||
end
|
||||
|
Loading…
x
Reference in New Issue
Block a user