Skip to content

Commit 4e346ad

Browse files
fatkodimanobu
authored andcommitted
Fix require_exact to work with options defined as --[no]-something
1 parent b14c2c6 commit 4e346ad

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

lib/optparse.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1048,7 +1048,7 @@ def compsys(to, name = File.basename($0)) # :nodoc:
10481048
# Shows option summary.
10491049
#
10501050
Officious['help'] = proc do |parser|
1051-
Switch::NoArgument.new do |arg|
1051+
Switch::NoArgument.new(nil, nil, ["-h"], ["--help"]) do |arg|
10521052
puts parser.help
10531053
exit
10541054
end
@@ -1473,7 +1473,7 @@ def make_switch(opts, block = nil)
14731473
default_style = default_style.guess(arg = a)
14741474
default_pattern, conv = search(:atype, o) unless default_pattern
14751475
end
1476-
ldesc << "--[no-]#{q}"
1476+
ldesc << "--#{q}" << "--no-#{q}"
14771477
(o = q.downcase).tr!('_', '-')
14781478
long << o
14791479
not_pattern, not_conv = search(:atype, FalseClass) unless not_style
@@ -1649,7 +1649,7 @@ def parse_in_order(argv = default_argv, setter = nil, &nonopt) # :nodoc:
16491649
opt.tr!('_', '-')
16501650
begin
16511651
sw, = complete(:long, opt, true)
1652-
if require_exact && !sw.long.include?(arg)
1652+
if require_exact && !sw.long.include?("--#{opt}")
16531653
throw :terminate, arg unless raise_unknown
16541654
raise InvalidOption, arg
16551655
end

test/optparse/test_optparse.rb

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,9 +88,9 @@ def test_require_exact
8888
end
8989

9090
@opt.require_exact = true
91-
%w(--zrs -F -Ffoo).each do |arg|
91+
[%w(--zrs foo), %w(--zrs=foo), %w(-F foo), %w(-Ffoo)].each do |args|
9292
result = {}
93-
@opt.parse([arg, 'foo'], into: result)
93+
@opt.parse(args, into: result)
9494
assert_equal({zrs: 'foo'}, result)
9595
end
9696

@@ -99,6 +99,14 @@ def test_require_exact
9999
assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(-zrs foo))}
100100
assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(-zr foo))}
101101
assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(-z foo))}
102+
103+
@opt.def_option('-f', '--[no-]foo', 'foo') {|arg| @foo = arg}
104+
@opt.parse(%w[-f])
105+
assert_equal(true, @foo)
106+
@opt.parse(%w[--foo])
107+
assert_equal(true, @foo)
108+
@opt.parse(%w[--no-foo])
109+
assert_equal(false, @foo)
102110
end
103111

104112
def test_raise_unknown

0 commit comments

Comments
 (0)