From b3f2e0a3f37a4ca23a0267a24a69e0224d1ec9d7 Mon Sep 17 00:00:00 2001 From: Michael Overmeyer Date: Mon, 18 Apr 2022 20:59:45 -0400 Subject: [PATCH] Check if `type: array` values are in `enum` --- lib/thor/parser/arguments.rb | 10 +++++++++- spec/parser/options_spec.rb | 7 +++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/thor/parser/arguments.rb b/lib/thor/parser/arguments.rb index 05c1a659c..582b31c8a 100644 --- a/lib/thor/parser/arguments.rb +++ b/lib/thor/parser/arguments.rb @@ -122,7 +122,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 diff --git a/spec/parser/options_spec.rb b/spec/parser/options_spec.rb index b1e50fbfa..dea46ff5b 100644 --- a/spec/parser/options_spec.rb +++ b/spec/parser/options_spec.rb @@ -443,6 +443,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