From 5426d18d6bdbff3c4ca8fac9c8d9f5341221f378 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Mon, 1 Jul 2019 15:19:16 -0700 Subject: [PATCH] Add OptionParser#require_exact accessor This allows you to disable allowing abbreviations of long options and using short options for long options. --- lib/optparse.rb | 9 +++++++++ test/optparse/test_optparse.rb | 22 ++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/lib/optparse.rb b/lib/optparse.rb index 9937e2500d..0331adbf94 100644 --- a/lib/optparse.rb +++ b/lib/optparse.rb @@ -1085,6 +1085,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 @@ -1158,6 +1159,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. # @@ -1574,6 +1579,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 @@ -1598,6 +1606,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) diff --git a/test/optparse/test_optparse.rb b/test/optparse/test_optparse.rb index e4aeb07aac..5e7c68ab75 100644 --- a/test/optparse/test_optparse.rb +++ b/test/optparse/test_optparse.rb @@ -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', '--irs=IRS', 'irs') + %w(--irs --ir --i -ifoo -i -F -Ffoo).each do |arg| + result = {} + @opt.parse([arg, 'foo'], into: result) + assert_equal({irs: 'foo'}, result) + end + + @opt.require_exact = true + %w(--irs -F -Ffoo).each do |arg| + result = {} + @opt.parse([arg, 'foo'], into: result) + assert_equal({irs: 'foo'}, result) + end + + assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(--ir foo))} + assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(--i foo))} + assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(-irs foo))} + assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(-ir foo))} + assert_raise(OptionParser::InvalidOption) {@opt.parse(%w(-i foo))} + end end -- 2.21.0