Skip to content

Commit

Permalink
Add validation to options parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrmurach committed Apr 4, 2020
1 parent 478e7cd commit e996fd9
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 7 deletions.
14 changes: 7 additions & 7 deletions lib/tty/option/parser/options.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# frozen_string_literal: true

require_relative "../param_conversion"
require_relative "../param_validation"
require_relative "../pipeline"

module TTY
module Option
Expand Down Expand Up @@ -251,18 +250,19 @@ def record_error(type, message, opt = nil)

# @api private
def assign_option(opt, val)
value = Pipeline.process(opt, val)

if opt.multiple?
converted = ParamConversion[opt, val]
case converted
case value
when Hash
(@parsed[opt.name] ||= {}).merge!(converted)
(@parsed[opt.name] ||= {}).merge!(value)
else
Array(converted).each do |v|
Array(value).each do |v|
(@parsed[opt.name] ||= []) << v
end
end
else
@parsed[opt.name] = ParamConversion[opt, val]
@parsed[opt.name] = value
end
end
end # Options
Expand Down
46 changes: 46 additions & 0 deletions spec/unit/parse_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -382,5 +382,51 @@ def new_command(&block)
expect(cmd.params[:bar]).to eq({c: 1, d: 2})
end
end

context "validate" do
it "validates an option with a custom proc" do
cmd = new_command do
option :foo do
long "--foo VAL"
convert Integer
validate -> (val) { val == 12 }
end
end

expect {
cmd.parse(%w[--foo 13])
}.to raise_error(TTY::Option::InvalidArgument,
"value of `13` fails validation rule for :foo parameter")
end

it "validates an option with a string as regex" do
cmd = new_command do
option :foo do
long "--foo VAL"
validate "\d+"
end
end

expect {
cmd.parse(%w[--foo bar])
}.to raise_error(TTY::Option::InvalidArgument,
"value of `bar` fails validation rule for :foo parameter")
end

it "validates an option with a multiple argument" do
cmd = new_command do
option :foo do
long "--foo VAL"
convert :int_list
validate -> (val) { val < 12 }
end
end

expect {
cmd.parse(%w[--foo 10,11,12])
}.to raise_error(TTY::Option::InvalidArgument,
"value of `12` fails validation rule for :foo parameter")
end
end
end
end

0 comments on commit e996fd9

Please sign in to comment.