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
|
module Yawpa
|
||||||
class UnknownOptionException < Exception; end
|
class UnknownOptionException < Exception; end
|
||||||
|
class InvalidArgumentsException < Exception; end
|
||||||
|
|
||||||
module_function
|
module_function
|
||||||
def parse(params, options)
|
def parse(params, options)
|
||||||
@ -17,24 +18,42 @@ module Yawpa
|
|||||||
i = 0
|
i = 0
|
||||||
while i < params.length
|
while i < params.length
|
||||||
param = params[i]
|
param = params[i]
|
||||||
if param =~ /^(-+)(.+)$/
|
if param =~ /^(-+)([^=]+)(=.+)?$/
|
||||||
case $1.length
|
leader, param_name, val = $1, $2, $3
|
||||||
|
case leader.length
|
||||||
when 2
|
when 2
|
||||||
param_key = if options[$2]
|
param_key = if options[param_name]
|
||||||
$2
|
param_name
|
||||||
elsif options[$2.to_sym]
|
elsif options[param_name.to_sym]
|
||||||
$2.to_sym
|
param_name.to_sym
|
||||||
else
|
else
|
||||||
nil
|
nil
|
||||||
end
|
end
|
||||||
if param_key.nil?
|
if param_key.nil?
|
||||||
raise UnknownOptionException.new("Unknown option '#{param}'")
|
raise UnknownOptionException.new("Unknown option '#{param_name}'")
|
||||||
end
|
end
|
||||||
opt_config = options[param_key]
|
opt_config = options[param_key]
|
||||||
nargs = opt_config[:nargs] || 0
|
nargs = opt_config[:nargs] || 0
|
||||||
if nargs == 0
|
if nargs == 0
|
||||||
opts[param_key] = true
|
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
|
elsif nargs.class == Range
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
@ -29,5 +29,15 @@ describe Yawpa do
|
|||||||
opts.include?(:three).should be_false
|
opts.include?(:three).should be_false
|
||||||
args.should eq(['arg', 'arg2'])
|
args.should eq(['arg', 'arg2'])
|
||||||
end
|
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
|
||||||
end
|
end
|
||||||
|
Loading…
x
Reference in New Issue
Block a user