Skip to content

Commit b3f2e0a

Browse files
committed
Check if type: array values are in enum
1 parent ab3b5be commit b3f2e0a

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

lib/thor/parser/arguments.rb

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,15 @@ def parse_hash(name)
122122
def parse_array(name)
123123
return shift if peek.is_a?(Array)
124124
array = []
125-
array << shift while current_is_value?
125+
while current_is_value?
126+
value = shift
127+
if !value.empty? && @switches.is_a?(Hash) && switch = @switches[name]
128+
if switch.enum && !switch.enum.include?(value)
129+
raise MalformattedArgumentError, "Expected all values of '#{name}' to be one of #{switch.enum.join(', ')}; got #{value}"
130+
end
131+
end
132+
array << value
133+
end
126134
array
127135
end
128136

spec/parser/options_spec.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,13 @@ def remaining
443443
create :attributes => Thor::Option.new("attributes", :type => :array, :repeatable => true)
444444
expect(parse("--attributes", "1", "2", "--attributes", "3", "4")["attributes"]).to eq([["1", "2"], ["3", "4"]])
445445
end
446+
447+
it "raises error when value isn't in enum" do
448+
enum = %w(apple banana)
449+
create :fruit => Thor::Option.new("fruits", :type => :array, :enum => enum)
450+
expect { parse("--fruits=", "apple", "banana", "strawberry") }.to raise_error(Thor::MalformattedArgumentError,
451+
"Expected all values of '--fruits' to be one of #{enum.join(', ')}; got strawberry")
452+
end
446453
end
447454

448455
describe "with :numeric type" do

0 commit comments

Comments
 (0)