Skip to content

OptionParser#on with non-option Regexp causes invalid options to be duplicated #3

@postmodern

Description

@postmodern

I discovered this unexpected behavior which may be a bug in OptionParser. When an OptionParser is defined with an .on(/^[^-].*$/) { |arg| ... } to catch all non-option arguments, it causes invalid option arguments to be duplicated or doubled. When the on(...) callback is removed, the invalid options are not doubled or duplicated.

Example (with .on(/.../))

#!/usr/bin/env ruby

require 'optparse'

optparser = OptionParser.new do |opts|
  opts.on(/^[^-].*$/) do |arg|
    puts "Never gets called"
  end
end

begin
  optparser.parse(ARGV)
rescue OptionParser::ParseError => error
  $stderr.puts "error: #{error.message}"
  $stderr.puts "args: #{error.args.inspect}"
end

Output

$ ./test.rb -t
error: invalid option: -t -t
args: ["-t", "-t"]

Example (without .on(/.../))

#!/usr/bin/env ruby

require 'optparse'

optparser = OptionParser.new do |opts|
end

begin
  optparser.parse(ARGV)
rescue OptionParser::ParseError => error
  $stderr.puts "error: #{error.message}"
  $stderr.puts "args: #{error.args.inspect}"
end

Output

$ ./test.rb -t
error: invalid option -t
args: ["-t"]

Tested With

  • optparse (default: 0.1.0)
  • ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [x86_64-linux]
  • ruby 2.7.2p137 (2020-10-01 revision 5445e04352) [x86_64-linux]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions