Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions lib/optparse.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1091,6 +1091,7 @@ def initialize(banner = nil, width = 32, indent = ' ' * 4)
@summary_width = width
@summary_indent = indent
@default_argv = ARGV
@require_exact = false
add_officious
yield self if block_given?
end
Expand Down Expand Up @@ -1164,6 +1165,10 @@ def self.reject(*args, &blk) top.reject(*args, &blk) end
# Strings to be parsed in default.
attr_accessor :default_argv

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

#
# Heading banner preceding summary.
#
Expand Down Expand Up @@ -1583,6 +1588,9 @@ def parse_in_order(argv = default_argv, setter = nil, &nonopt) # :nodoc:
opt.tr!('_', '-')
begin
sw, = complete(:long, opt, true)
if require_exact && !sw.long.include?(arg)
raise InvalidOption, arg
end
rescue ParseError
raise $!.set_option(arg, true)
end
Expand All @@ -1607,6 +1615,7 @@ def parse_in_order(argv = default_argv, setter = nil, &nonopt) # :nodoc:
val = arg.delete_prefix('-')
has_arg = true
rescue InvalidOption
raise if require_exact
# if no short options match, try completion with long
# options.
sw, = complete(:long, opt)
Expand Down
22 changes: 22 additions & 0 deletions test/optparse/test_optparse.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,26 @@ def test_into
assert_equal({host: "localhost", port: 8000, verbose: true}, result)
assert_equal(true, @verbose)
end

def test_require_exact
@opt.def_option('-F', '--zrs=IRS', 'zrs')
%w(--zrs --zr --z -zfoo -z -F -Ffoo).each do |arg|
result = {}
@opt.parse([arg, 'foo'], into: result)
assert_equal({zrs: 'foo'}, result)
end

@opt.require_exact = true
%w(--zrs -F -Ffoo).each do |arg|
result = {}
@opt.parse([arg, 'foo'], into: result)
assert_equal({zrs: 'foo'}, result)
end

assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(--zr foo))}
assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(--z foo))}
assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(-zrs foo))}
assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(-zr foo))}
assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(-z foo))}
end
end