From a23fa41a5674485600365985bea2a905e5e087df Mon Sep 17 00:00:00 2001 From: Victor Gama Date: Fri, 10 Feb 2023 16:25:08 -0300 Subject: Add optional type validation --- lib/slop/error.rb | 12 ++++++++++++ lib/slop/option.rb | 20 +++++++++++++++++++- lib/slop/options.rb | 4 ++++ lib/slop/types.rb | 21 +++++++++++++++++++-- test/error_test.rb | 15 +++++++++++++++ 5 files changed, 69 insertions(+), 3 deletions(-) diff --git a/lib/slop/error.rb b/lib/slop/error.rb index ddfa1a7..b83cab3 100644 --- a/lib/slop/error.rb +++ b/lib/slop/error.rb @@ -38,4 +38,16 @@ module Slop # Suppress with the `suppress_errors` config option. class MissingRequiredOption < Error end + + # Raised when a given option is provided by the user and does not + # match the expected format for that type. This is only raised if + # validate_types is set to true. + class InvalidOptionValue < Error + attr_reader :flag + + def initialize(msg, flag) + super(msg) + @flag = flag + end + end end diff --git a/lib/slop/option.rb b/lib/slop/option.rb index 093b37f..3afc93a 100644 --- a/lib/slop/option.rb +++ b/lib/slop/option.rb @@ -56,7 +56,11 @@ module Slop raise Slop::MissingArgument.new("missing argument for #{flag}", flags) end else - @value = call(value) + if validate_type? && !valid?(value) && !suppress_errors? + raise Slop::InvalidOptionValue.new("invalid value for #{flag}", flags) + end + + @value = valid?(value) && call(value) end block.call(@value) if block.respond_to?(:call) @@ -107,6 +111,13 @@ module Slop config[:required] end + # Returns true if an exception should be raised when this option value can't + # be parsed into the desired type or does not conform to the expected type's + # format + def validate_type? + config[:validate_types] + end + # Returns all flags joined by a comma. Used by the help string. def flag flags.join(", ") @@ -119,6 +130,13 @@ module Slop key.to_sym end + # Override this if you want to provide a custom validator for a type. This + # method must return whether the provided value is valid for the current + # argument's type + def valid?(value) + true + end + # Returns true if this option should be displayed with dashes transformed into underscores. def underscore_flags? config[:underscore_flags] diff --git a/lib/slop/options.rb b/lib/slop/options.rb index 17e9501..5e71eac 100755 --- a/lib/slop/options.rb +++ b/lib/slop/options.rb @@ -7,6 +7,7 @@ module Slop type: "null", banner: true, underscore_flags: true, + validate_types: false, } # The Array of Option instances we've created. @@ -24,6 +25,9 @@ module Slop # The String banner prefixed to the help string. attr_accessor :banner + # Whether we should validate types of values provided by the user + attr_accessor :validate_types + def initialize(**config, &block) @options = [] @separators = [] diff --git a/lib/slop/types.rb b/lib/slop/types.rb index 83e4a0b..a08537d 100644 --- a/lib/slop/types.rb +++ b/lib/slop/types.rb @@ -22,6 +22,13 @@ module Slop attr_accessor :explicit_value FALSE_VALUES = [false, 'false', 'no', 'off', '0'].freeze + TRUE_VALUES = [true, 'true', 'yes', 'on', '1'].freeze + VALID_VALUES = (FALSE_VALUES + TRUE_VALUES).freeze + + def valid?(value) + return true if value.is_a?(String) && value.start_with?("--") + value.nil? || VALID_VALUES.include?(value) + end def call(value) self.explicit_value = value @@ -52,8 +59,14 @@ module Slop # Cast the option argument to an Integer. class IntegerOption < Option + INT_STRING_REGEXP = /\A[+-]?\d+\z/.freeze + + def valid?(value) + value =~ INT_STRING_REGEXP + end + def call(value) - value =~ /\A[+-]?\d+\z/ && value.to_i + value.to_i end end IntOption = IntegerOption @@ -62,8 +75,12 @@ module Slop class FloatOption < Option FLOAT_STRING_REGEXP = /\A[+-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?\z/.freeze + def valid?(value) + value =~ FLOAT_STRING_REGEXP + end + def call(value) - value =~ FLOAT_STRING_REGEXP && value.to_f + value.to_f end end diff --git a/test/error_test.rb b/test/error_test.rb index d9c71ab..341fa75 100644 --- a/test/error_test.rb +++ b/test/error_test.rb @@ -63,3 +63,18 @@ describe Slop::MissingRequiredOption do opts.parse [] end end + +describe Slop::InvalidOptionValue do + it "raises when an option has an invalid value" do + opts = Slop::Options.new(validate_types: true) + opts.integer "-n", "--number", default: 10 + assert_raises(Slop::InvalidOptionValue) { opts.parse %w(-n foo) } + end + + it "does not raise when errors are suppressed" do + opts = Slop::Options.new(validate_types: true, suppress_errors: true) + opts.integer "-n", "--number", default: 10 + r = opts.parse %w(-n foo) + assert_equal(10, r[:n]) + end +end -- cgit v1.2.1 From 25cae16e2c3ca2fbe8c1c75923dae9b14cc38b72 Mon Sep 17 00:00:00 2001 From: Victor Gama Date: Fri, 10 Feb 2023 16:26:00 -0300 Subject: Update README --- README.md | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3876428..f15fbc3 100644 --- a/README.md +++ b/README.md @@ -204,6 +204,8 @@ Slop will raise errors for the following: * An option used without an argument when it expects one: `Slop::MissingArgument` * An option used that Slop doesn't know about: `Slop::UnknownOption` * An option marked as `required` when not provided: `Slop::MissingRequiredOption` +* An option marked as `validate_types`, with an argument that does not match its +type (i.e. `bla` for `integer`): `Slop::InvalidOptionValue` These errors inherit from `Slop::Error`, so you can rescue them all. Alternatively you can suppress these errors with the `suppress_errors` config @@ -222,6 +224,33 @@ opts = Slop.parse do end ``` +Validating Types +---------------- + +By default, Slop does not validate whether an argument is a valid value for a +given option; instead, if the option has a default value, it will be used over +the invalid argument provided. +In order to have types (such as `integer` and `float`) validate and indicate +that the provided value is invalid, an extra option can be either provided to +the argument itself, or its option set: + +```ruby +opts = Slop::Options.new +opts.int "-p", "--port", "a port", default: 80, validate_types: true + +parser = Slop::Parser.new(opts) +result = parser.parse(["--port", "bla"]) +# invalid value for -p, --port (Slop::InvalidOptionValue) + +# Or to the option set... +opts = Slop::Options.new(validate_types: true) +opts.int "-p", "--port", "a port", default: 80 + +parser = Slop::Parser.new(opts) +result = parser.parse(["--port", "bla"]) +# invalid value for -p, --port (Slop::InvalidOptionValue) +``` + Printing help ------------- @@ -279,4 +308,4 @@ end Commands -------- -Slop not longer has built in support for git-style subcommands. +Slop no longer has built in support for git-style subcommands. -- cgit v1.2.1 From 556f88322951b4a64c7bdf6f68f3e0a970940fb7 Mon Sep 17 00:00:00 2001 From: Victor Gama Date: Wed, 15 Feb 2023 11:41:22 -0300 Subject: Allow singular form 'validate_type' to be provided to Option --- lib/slop/option.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/slop/option.rb b/lib/slop/option.rb index 3afc93a..655b283 100644 --- a/lib/slop/option.rb +++ b/lib/slop/option.rb @@ -115,7 +115,7 @@ module Slop # be parsed into the desired type or does not conform to the expected type's # format def validate_type? - config[:validate_types] + config[:validate_type] || config[:validate_types] end # Returns all flags joined by a comma. Used by the help string. -- cgit v1.2.1 From becc0305239c2885affb1f57419afac3e5418a88 Mon Sep 17 00:00:00 2001 From: Victor Gama Date: Wed, 15 Feb 2023 11:42:36 -0300 Subject: Augment tests for validated types --- test/error_test.rb | 4 ++-- test/types_test.rb | 26 ++++++++++++++++++++++---- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/test/error_test.rb b/test/error_test.rb index 341fa75..8ea9069 100644 --- a/test/error_test.rb +++ b/test/error_test.rb @@ -72,8 +72,8 @@ describe Slop::InvalidOptionValue do end it "does not raise when errors are suppressed" do - opts = Slop::Options.new(validate_types: true, suppress_errors: true) - opts.integer "-n", "--number", default: 10 + opts = Slop::Options.new(suppress_errors: true) + opts.integer "-n", "--number", default: 10, validate_type: true r = opts.parse %w(-n foo) assert_equal(10, r[:n]) end diff --git a/test/types_test.rb b/test/types_test.rb index ea2ba8d..c6f0864 100644 --- a/test/types_test.rb +++ b/test/types_test.rb @@ -31,10 +31,10 @@ end describe Slop::BoolOption do before do @options = Slop::Options.new - @verbose = @options.bool "--verbose" + @verbose = @options.bool "--verbose", validate_type: true @quiet = @options.bool "--quiet" @inversed = @options.bool "--inversed", default: true - @explicit = @options.bool "--explicit" + @explicit = @options.bool "--explicit", validate_type: true @bloc = @options.bool("--bloc"){|val| (@bloc_val ||= []) << val} @result = @options.parse %w(--verbose --no-inversed --bloc --no-bloc @@ -60,13 +60,19 @@ describe Slop::BoolOption do it "returns false when explicitly false" do assert_equal false, @result[:explicit] end + + it "raises with invalid types" do + assert_raises(Slop::InvalidOptionValue) do + @result.parser.parse %w(--verbose foo) + end + end end describe Slop::IntegerOption do before do @options = Slop::Options.new @age = @options.integer "--age" - @minus = @options.integer "--minus" + @minus = @options.integer "--minus", validate_type: true @plus = @options.integer "--plus" @result = @options.parse %w(--age 20 --minus -10 --plus +30) end @@ -81,6 +87,12 @@ describe Slop::IntegerOption do @result.parser.parse %w(--age hello) assert_nil @result[:age] end + + it "raises with invalid types" do + assert_raises(Slop::InvalidOptionValue) do + @result.parser.parse %w(--minus foo) + end + end end describe Slop::FloatOption do @@ -88,7 +100,7 @@ describe Slop::FloatOption do @options = Slop::Options.new @apr = @options.float "--apr" @apr_value = 2.9 - @minus = @options.float "--minus" + @minus = @options.float "--minus", validate_type: true @plus = @options.float "--plus" @scientific_notation = @options.float "--scientific-notation" @scientific_notation_value = 4e21 @@ -125,6 +137,12 @@ describe Slop::FloatOption do @result.parser.parse %w(--apr hello) assert_nil @result[:apr] end + + it "raises with invalid types" do + assert_raises(Slop::InvalidOptionValue) do + @result.parser.parse %w(--minus foo) + end + end end describe Slop::ArrayOption do -- cgit v1.2.1