Skip to content

Commit

Permalink
Merge pull request #784 from movermeyer/movermeyer/add_enum_validatio…
Browse files Browse the repository at this point in the history
…n_to_array_values

Check if `type: array` values are in `enum`
  • Loading branch information
rafaelfranca authored May 12, 2023
2 parents cb53d45 + b3f2e0a commit 98ebfd2
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/thor/parser/arguments.rb
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,15 @@ def parse_hash(name)
def parse_array(name)
return shift if peek.is_a?(Array)
array = []
array << shift while current_is_value?
while current_is_value?
value = shift
if !value.empty? && @switches.is_a?(Hash) && switch = @switches[name]
if switch.enum && !switch.enum.include?(value)
raise MalformattedArgumentError, "Expected all values of '#{name}' to be one of #{switch.enum.join(', ')}; got #{value}"
end
end
array << value
end
array
end

Expand Down
7 changes: 7 additions & 0 deletions spec/parser/options_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,13 @@ def remaining
create attributes: Thor::Option.new("attributes", type: :array, repeatable: true)
expect(parse("--attributes", "1", "2", "--attributes", "3", "4")["attributes"]).to eq([["1", "2"], ["3", "4"]])
end

it "raises error when value isn't in enum" do
enum = %w(apple banana)
create :fruit => Thor::Option.new("fruits", :type => :array, :enum => enum)
expect { parse("--fruits=", "apple", "banana", "strawberry") }.to raise_error(Thor::MalformattedArgumentError,
"Expected all values of '--fruits' to be one of #{enum.join(', ')}; got strawberry")
end
end

describe "with :numeric type" do
Expand Down

0 comments on commit 98ebfd2

Please sign in to comment.