diff --git a/lib/optimist.rb b/lib/optimist.rb index 9aa8962..2172ccc 100644 --- a/lib/optimist.rb +++ b/lib/optimist.rb @@ -245,7 +245,8 @@ def parse(cmdline = ARGV) @specs.each do |sym, opts| required[sym] = true if opts.required? vals[sym] = opts.default - vals[sym] = [] if opts.multi && !opts.default # multi arguments default to [], not nil + vals[sym] = [] if opts.multi && !opts.default && !opts.flag? # multi arguments default to [], not nil + vals[sym] = 0 if opts.multi && !opts.default && opts.flag? # multi argument flags default to 0 because they return a count end resolve_default_short_options! @@ -283,6 +284,11 @@ def parse(cmdline = ARGV) # The block returns the number of parameters taken. num_params_taken = 0 + if @specs[sym].multi? && @specs[sym].flag? + given_args[sym][:params][0] ||= 0 + given_args[sym][:params][0] += 1 + end + unless params.empty? if @specs[sym].single_arg? given_args[sym][:params] << params[0, 1] # take the first parameter @@ -765,6 +771,7 @@ def initialize end def flag? ; true ; end def parse(_paramlist, neg_given) + return _paramlist[0] if @multi_given return(self.name.to_s =~ /^no_/ ? neg_given : !neg_given) end end diff --git a/test/optimist/parser_test.rb b/test/optimist/parser_test.rb index fbb3b4a..6a0a5fc 100644 --- a/test/optimist/parser_test.rb +++ b/test/optimist/parser_test.rb @@ -565,19 +565,19 @@ def test_short_options_with_multiple_options assert_equal [], @p.leftovers end - def test_short_options_with_multiple_options_does_not_affect_flags_type + def test_short_options_with_multiple_options_flag_types_get_counted @p.opt :xarg, "desc", :short => "-x", :type => :flag, :multi => true opts = @p.parse %w(-x a) - assert_equal true, opts[:xarg] + assert_equal 1, opts[:xarg] assert_equal %w(a), @p.leftovers opts = @p.parse %w(-x a -x b) - assert_equal true, opts[:xarg] + assert_equal 2, opts[:xarg] assert_equal %w(a b), @p.leftovers opts = @p.parse %w(-xx a -x b) - assert_equal true, opts[:xarg] + assert_equal 3, opts[:xarg] assert_equal %w(a b), @p.leftovers end @@ -1116,12 +1116,18 @@ def test_accepts_arguments_with_spaces assert_equal 0, @p.leftovers.size end - def test_multi_args_default_to_empty_array - @p.opt :arg1, "arg", :multi => true + def test_multi_args_with_specified_type_defaults_to_empty_array + @p.opt :arg1, "arg", :type => :string, :multi => true opts = @p.parse [] assert_equal [], opts[:arg1] end + def test_multi_args_with_type_flag_defaults_to_zero + @p.opt :arg1, "arg", :multi => true + opts = @p.parse [] + assert_equal 0, opts[:arg1] + end + def test_simple_interface_handles_help assert_stdout(/Options:/) do assert_raises(SystemExit) do