From 7f6aef195716989d8fb7e66b1ca52e348551b67a Mon Sep 17 00:00:00 2001 From: Andrew Clemons Date: Mon, 4 Apr 2016 15:10:25 +1200 Subject: Support arguments to options with leading - This allows negative values as arguments to numeric options and strings starting with - for any other type. Fixes #170 Fixes #179 --- lib/slop/parser.rb | 10 +++++++++- lib/slop/types.rb | 4 ++-- test/parser_test.rb | 21 +++++++++++++++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/lib/slop/parser.rb b/lib/slop/parser.rb index ea1869e..0b33d55 100644 --- a/lib/slop/parser.rb +++ b/lib/slop/parser.rb @@ -43,7 +43,8 @@ module Slop @arguments = strings.dup - pairs.each do |flag, arg| + pairs.each_with_index do |pair, idx| + flag, arg = pair break if !flag # ignore everything after '--', flag or not @@ -54,6 +55,7 @@ module Slop # support `foo=bar` orig_flag = flag.dup + orig_arg = arg if flag.include?("=") flag, arg = flag.split("=") end @@ -63,6 +65,12 @@ module Slop # arguments (plus the arg if necessary) # delete argument first while we can find its index. if opt.expects_argument? + + # if we consumed the argument, remove the next pair + if orig_arg == opt.value.to_s + pairs.delete_at(idx + 1) + end + arguments.each_with_index do |argument, i| if argument == orig_flag && !orig_flag.include?("=") arguments.delete_at(i + 1) diff --git a/lib/slop/types.rb b/lib/slop/types.rb index 7e80544..b7e41c8 100644 --- a/lib/slop/types.rb +++ b/lib/slop/types.rb @@ -44,7 +44,7 @@ module Slop # Cast the option argument to an Integer. class IntegerOption < Option def call(value) - value =~ /\A\d+\z/ && value.to_i + value =~ /\A-?\d+\z/ && value.to_i end end IntOption = IntegerOption @@ -53,7 +53,7 @@ module Slop class FloatOption < Option def call(value) # TODO: scientific notation, etc. - value =~ /\A\d*\.*\d+\z/ && value.to_f + value =~ /\A-?\d*\.*\d+\z/ && value.to_f end end diff --git a/test/parser_test.rb b/test/parser_test.rb index 1099871..339a522 100644 --- a/test/parser_test.rb +++ b/test/parser_test.rb @@ -22,6 +22,27 @@ describe Slop::Parser do assert_equal 123, @result[:port] end + it "parses arg with leading -" do + @options.string "-t", "--text" + @result.parser.parse %w(--name=bob --text --sometext) + assert_equal "bob", @result[:name] + assert_equal "--sometext", @result[:text] + end + + it "parses negative integer" do + @options.integer "-p", "--port" + @result.parser.parse %w(--name=bob --port -123) + assert_equal "bob", @result[:name] + assert_equal(-123, @result[:port]) + end + + it "parses negative float" do + @options.float "-m", "--multiple" + @result.parser.parse %w(--name=bob -m -123.987) + assert_equal "bob", @result[:name] + assert_equal(-123.987, @result[:multiple]) + end + describe "parsing grouped short flags" do before do @options.bool "-q", "--quiet" -- cgit v1.2.1