8000 Add `raise_unknown` flag (#38) · ruby/optparse@1252965 · GitHub
[go: up one dir, main page]

Skip to content

Commit 1252965

Browse files
committed
Add raise_unknown flag (#38)
1 parent ab5073e commit 1252965

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

lib/optparse.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1148,6 +1148,7 @@ def initialize(banner = nil, width = 32, indent = ' ' * 4)
11481148
@summary_indent = indent
11491149
@default_argv = ARGV
11501150
@require_exact = false
1151+
@raise_unknown = true
11511152
add_officious
11521153
yield self if block_given?
11531154
end
@@ -1225,6 +1226,9 @@ def self.reject(*args, &blk) top.reject(*args, &blk) end
12251226
# abbreviated long option as short option).
12261227
attr_accessor :require_exact
12271228

1229+
# Whether to raise at unknown option.
1230+
attr_accessor :raise_unknown
1231+
12281232
#
12291233
# Heading banner preceding summary.
12301234
#
@@ -1639,9 +1643,11 @@ def parse_in_order(argv = default_argv, setter = nil, &nonopt) # :nodoc:
16391643
begin
16401644
sw, = complete(:long, opt, true)
16411645
if require_exact && !sw.long.include?(arg)
1646+
throw :terminate, arg unless raise_unknown
16421647
raise InvalidOption, arg
16431648
end
16441649
rescue ParseError
1650+
throw :terminate, arg unless raise_unknown
16451651
raise $!.set_option(arg, true)
16461652
end
16471653
begin
@@ -1673,6 +1679,7 @@ def parse_in_order(argv = default_argv, setter = nil, &nonopt) # :nodoc:
16731679
end
16741680
end
16751681
rescue ParseError
1682+
throw :terminate, arg unless raise_unknown
16761683
raise $!.set_option(arg, true)
16771684
end
16781685
begin

test/optparse/test_optparse.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,18 @@ def test_require_exact
9898
assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(-z foo))}
9999
end
100100

101+
def test_raise_unknown
102+
@opt.def_option('--foo [ARG]') {|arg| @foo = arg}
103+
assert @opt.raise_unknown
104+
105+
@opt.raise_unknown = false
106+
assert_equal(%w[--bar], @opt.parse(%w[--foo --bar]))
107+
assert_nil(@foo)
108+
109+
assert_equal(%w[--bar], @opt.parse(%w[--foo x --bar]))
110+
assert_equal("x", @foo)
111+
end
112+
101113
def test_nonopt_pattern
102114
@opt.def_option(/^[^-]/) do |arg|
103115
assert(false, "Never gets called")

0 commit comments

Comments
 (0)
0