Skip to content

Commit

Permalink
Change to only collect options matching arity
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrmurach committed Apr 6, 2020
1 parent 87b3c43 commit 2085269
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
20 changes: 14 additions & 6 deletions lib/tty/option/parser/options.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ def initialize(options, **config)
@remaining = []
@shorts = {}
@longs = {}
@arities = {}
@required = []

setup_opts
Expand Down Expand Up @@ -67,6 +68,7 @@ def parse(argv)
opt, value = next_option
break if opt.nil?
@required.delete(opt)
@arities[opt.name] = @arities[opt.name].to_i + 1

if block_given?
yield(opt, value)
Expand Down Expand Up @@ -278,13 +280,19 @@ def assign_option(opt, val)
value = Pipeline.process(opt, val)

if opt.multiple?
case value
when Hash
(@parsed[opt.name] ||= {}).merge!(value)
else
Array(value).each do |v|
(@parsed[opt.name] ||= []) << v
allowed = opt.arity < 0 || (@arities[opt.name] || 0) <= opt.arity
if allowed
case value
when Hash
(@parsed[opt.name] ||= {}).merge!(value)
else
Array(value).each do |v|
(@parsed[opt.name] ||= []) << v
end
end
else
@remaining << opt.short_name
@remaining << value
end
else
@parsed[opt.name] = value
Expand Down
21 changes: 21 additions & 0 deletions spec/unit/parser/options_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -348,12 +348,33 @@ def parse(argv, options, **config)
expect(rest).to eq([])
end

it "parses short flag with required argument many times and keeps only two" do
params, rest = parse(%w[-f 1 -f 2 -f 3], option(:foo, short: "-f int", arity: 2))

expect(params[:foo]).to eq(%w[1 2])
expect(rest).to eq(%w[-f 3])
end

it "parses short flag with required argument many times and keeps all" do
params, rest = parse(%w[-f 1 -f 2 -f 3], option(:foo, short: "-f int", arity: :any))

expect(params[:foo]).to eq(%w[1 2 3])
expect(rest).to eq([])
end

it "parses long flag with required argument and keeps the last argument" do
params, rest = parse(%w[--f 1 --f 2 --f 3], option(:foo, long: "--f int"))

expect(params[:foo]).to eq("3")
expect(rest).to eq([])
end

it "parses long flags with required argument and keeps all" do
params, rest = parse(%w[--f 1 --f 2 --f 3], option(:foo, long: "--f int", arity: -2))

expect(params[:foo]).to eq(%w[1 2 3])
expect(rest).to eq([])
end
end

context "when list argument" do
Expand Down

0 comments on commit 2085269

Please sign in to comment.