Thanks to visit codestin.com
Credit goes to github.com

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
Add raise_unknown flag (#38)
  • Loading branch information
nobu committed Oct 29, 2022
commit e48aca47bbb4b0a39e479a2c68cdea182a4fc55e
7 changes: 7 additions & 0 deletions lib/optparse.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1148,6 +1148,7 @@ def initialize(banner = nil, width = 32, indent = ' ' * 4)
@summary_indent = indent
@default_argv = ARGV
@require_exact = false
@raise_unknown = true
add_officious
yield self if block_given?
end
Expand Down Expand Up @@ -1225,6 +1226,9 @@ def self.reject(*args, &blk) top.reject(*args, &blk) end
# abbreviated long option as short option).
attr_accessor :require_exact

# Whether to raise at unknown option.
attr_accessor :raise_unknown

#
# Heading banner preceding summary.
#
Expand Down Expand Up @@ -1639,9 +1643,11 @@ def parse_in_order(argv = default_argv, setter = nil, &nonopt) # :nodoc:
begin
sw, = complete(:long, opt, true)
if require_exact && !sw.long.include?(arg)
throw :terminate, arg unless raise_unknown
raise InvalidOption, arg
end
rescue ParseError
throw :terminate, arg unless raise_unknown
raise $!.set_option(arg, true)
end
begin
Expand Down Expand Up @@ -1673,6 +1679,7 @@ def parse_in_order(argv = default_argv, setter = nil, &nonopt) # :nodoc:
end
end
rescue ParseError
throw :terminate, arg unless raise_unknown
raise $!.set_option(arg, true)
end
begin
Expand Down
12 changes: 12 additions & 0 deletions test/optparse/test_optparse.rb
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,18 @@ def test_require_exact
assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(-z foo))}
end

def test_raise_unknown
@opt.def_option('--foo [ARG]') {|arg| @foo = arg}
assert @opt.raise_unknown

@opt.raise_unknown = false
assert_equal(%w[--bar], @opt.parse(%w[--foo --bar]))
assert_nil(@foo)

assert_equal(%w[--bar], @opt.parse(%w[--foo x --bar]))
assert_equal("x", @foo)
end

def test_nonopt_pattern
@opt.def_option(/^[^-]/) do |arg|
assert(false, "Never gets called")
Expand Down