Project

General

Profile

Bug #11523 ยป optparse-require-exact.patch

jeremyevans0 (Jeremy Evans), 07/01/2019 10:23 PM

View differences:

lib/optparse.rb
1085 1085
    @summary_width = width
1086 1086
    @summary_indent = indent
1087 1087
    @default_argv = ARGV
1088
    @require_exact = false
1088 1089
    add_officious
1089 1090
    yield self if block_given?
1090 1091
  end
......
1158 1159
  # Strings to be parsed in default.
1159 1160
  attr_accessor :default_argv
1160 1161

  
1162
  # Whether to require that options match exactly (disallows providing
1163
  # abbreviated long option as short option).
1164
  attr_accessor :require_exact
1165

  
1161 1166
  #
1162 1167
  # Heading banner preceding summary.
1163 1168
  #
......
1574 1579
          opt.tr!('_', '-')
1575 1580
          begin
1576 1581
            sw, = complete(:long, opt, true)
1582
            if require_exact && !sw.long.include?(arg)
1583
              raise InvalidOption, arg
1584
            end
1577 1585
          rescue ParseError
1578 1586
            raise $!.set_option(arg, true)
1579 1587
          end
......
1598 1606
                val = arg.delete_prefix('-')
1599 1607
                has_arg = true
1600 1608
              rescue InvalidOption
1609
                raise if require_exact
1601 1610
                # if no short options match, try completion with long
1602 1611
                # options.
1603 1612
                sw, = complete(:long, opt)
test/optparse/test_optparse.rb
75 75
    assert_equal({host: "localhost", port: 8000, verbose: true}, result)
76 76
    assert_equal(true, @verbose)
77 77
  end
78

  
79
  def test_require_exact
80
    @opt.def_option('-F', '--irs=IRS', 'irs')
81
    %w(--irs --ir --i -ifoo -i -F -Ffoo).each do |arg|
82
      result = {}
83
      @opt.parse([arg, 'foo'], into: result)
84
      assert_equal({irs: 'foo'}, result)
85
    end
86

  
87
    @opt.require_exact = true
88
    %w(--irs -F -Ffoo).each do |arg|
89
      result = {}
90
      @opt.parse([arg, 'foo'], into: result)
91
      assert_equal({irs: 'foo'}, result)
92
    end
93

  
94
    assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(--ir foo))}
95
    assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(--i foo))}
96
    assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(-irs foo))}
97
    assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(-ir foo))}
98
    assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(-i foo))}
99
  end
78 100
end
79
-