diff --git a/lib/optparse.rb b/lib/optparse.rb index 97178e2..bae97fd 100644 --- a/lib/optparse.rb +++ b/lib/optparse.rb @@ -563,6 +563,10 @@ def initialize(pattern = nil, conv = nil, # private def parse_arg(arg) # :nodoc: pattern or return nil, [arg] + # As in #parse_in_order: an argument that is not valid in its encoding + # would make Regexp#match raise, and String#rindex below fail to find a + # substring it does contain. + arg = arg.b unless arg.valid_encoding? unless m = pattern.match(arg) yield(InvalidArgument, arg) return arg, [] @@ -1733,6 +1737,14 @@ def order!(argv = default_argv, into: nil, **keywords, &nonopt) nonopt ||= proc {|a| throw :terminate, a} argv.unshift(arg) if arg = catch(:terminate) { while arg = argv.shift + # Ruby passes arguments through ARGV as the bytes it was given, so one + # can hold bytes that are not valid in its encoding, such as a file + # name from another system. Matching such a string raises + # ArgumentError from Regexp#===, before optparse can decide whether it + # is an option at all, so treat it as the bytes it is. Only arguments + # that raise today are affected. + arg = arg.b unless arg.valid_encoding? + case arg # long option when /\A--([^=]*)(?:=(.*))?/m diff --git a/test/optparse/test_invalid_encoding.rb b/test/optparse/test_invalid_encoding.rb new file mode 100644 index 0000000..3a280e4 --- /dev/null +++ b/test/optparse/test_invalid_encoding.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: false +require_relative 'test_optparse' + +class TestOptionParserInvalidEncoding < TestOptionParser + # Ruby passes arguments through ARGV as the bytes it was given, so an + # argument can hold bytes that are not valid in its encoding, such as a + # file name from a system using another one. + INVALID = "caf\xE9.txt".force_encoding(Encoding::UTF_8) + + def setup + super + @opt.def_option("-n", "--name=NAME") {|x| @flag = x} + @opt.def_option("-v", "--verbose") {|x| @flag = x} + assert_not_predicate(INVALID, :valid_encoding?) + end + + def test_non_option_argument_is_left_alone + rest = no_error {@opt.parse!([INVALID.dup])} + assert_equal([INVALID.bytes], rest.map(&:bytes)) + assert_equal(self.class, @flag) + end + + def test_option_argument_joined_by_equals + assert_empty(no_error {@opt.parse!(["--name=#{INVALID}"])}) + assert_equal(INVALID.bytes, @flag.bytes) + end + + def test_option_argument_in_the_next_element + assert_empty(no_error {@opt.parse!(["--name", INVALID.dup])}) + assert_equal(INVALID.bytes, @flag.bytes) + end + + def test_short_option_argument + assert_empty(no_error {@opt.parse!(["-n#{INVALID}"])}) + assert_equal(INVALID.bytes, @flag.bytes) + end + + def test_option_before_a_non_option_argument + rest = no_error {@opt.parse!(["--verbose", INVALID.dup])} + assert_equal([INVALID.bytes], rest.map(&:bytes)) + assert_equal(true, @flag) + end + + def test_an_unknown_option_still_raises_parse_error + assert_raise(OptionParser::InvalidOption) {@opt.parse!(["--bogus", INVALID.dup])} + end +end