Skip to content

Commit dfefb2d

Browse files
jeremyevansnobu
authored andcommitted
Add OptionParser#require_exact accessor
This allows you to disable allowing abbreviations of long options and using short options for long options. Implements Ruby Feature #11523
1 parent 1a77caf commit dfefb2d

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

lib/optparse.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1091,6 +1091,7 @@ def initialize(banner = nil, width = 32, indent = ' ' * 4)
10911091
@summary_width = width
10921092
@summary_indent = indent
10931093
@default_argv = ARGV
1094+
@require_exact = false
10941095
add_officious
10951096
yield self if block_given?
10961097
end
@@ -1164,6 +1165,10 @@ def self.reject(*args, &blk) top.reject(*args, &blk) end
11641165
# Strings to be parsed in default.
11651166
attr_accessor :default_argv
11661167

1168+
# Whether to require that options match exactly (disallows providing
1169+
# abbreviated long option as short option).
1170+
attr_accessor :require_exact
1171+
11671172
#
11681173
# Heading banner preceding summary.
11691174
#
@@ -1583,6 +1588,9 @@ def parse_in_order(argv = default_argv, setter = nil, &nonopt) # :nodoc:
15831588
opt.tr!('_', '-')
15841589
begin
15851590
sw, = complete(:long, opt, true)
1591+
if require_exact && !sw.long.include?(arg)
1592+
raise InvalidOption, arg
1593+
end
15861594
rescue ParseError
15871595
raise $!.set_option(arg, true)
15881596
end
@@ -1607,6 +1615,7 @@ def parse_in_order(argv = default_argv, setter = nil, &nonopt) # :nodoc:
16071615
val = arg.delete_prefix('-')
16081616
has_arg = true
16091617
rescue InvalidOption
1618+
raise if require_exact
16101619
# if no short options match, try completion with long
16111620
# options.
16121621
sw, = complete(:long, opt)

test/optparse/test_optparse.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,4 +75,26 @@ def test_into
7575
assert_equal({host: "localhost", port: 8000, verbose: true}, result)
7676
assert_equal(true, @verbose)
7777
end
78+
79+
def test_require_exact
80+
@opt.def_option('-F', '--zrs=IRS', 'zrs')
81+
%w(--zrs --zr --z -zfoo -z -F -Ffoo).each do |arg|
82+
result = {}
83+
@opt.parse([arg, 'foo'], into: result)
84+
assert_equal({zrs: 'foo'}, result)
85+
end
86+
87+
@opt.require_exact = true
88+
%w(--zrs -F -Ffoo).each do |arg|
89+
result = {}
90+
@opt.parse([arg, 'foo'], into: result)
91+
assert_equal({zrs: 'foo'}, result)
92+
end
93+
94+
assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(--zr foo))}
95+
assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(--z foo))}
96+
assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(-zrs foo))}
97+
assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(-zr foo))}
98+
assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(-z foo))}
99+
end
78100
end

0 commit comments

Comments
 (0)