piotrmurach/tty-option

Additional "keywords" not captured in `remaining`

Closed this issue ยท 2 comments

bbugh commented

Hi again! ๐Ÿ‘‹๐Ÿป

Describe the problem

Using unknown KEYWORDS is not captured. This is for a script to set environment variables on multiple systems. I can add an option for it which I will do, but this was unexpected behavior and I'd rather it capture it as expected!

Steps to reproduce the problem

# test-command.rb
require 'tty-option'

class Command
  include TTY::Option

  def run
    puts "params #{params.to_h.inspect}"
    puts "remaining #{params.remaining.inspect}"
  end
end

cmd = Command.new
# Neither cmd.parse nor cmd.parse(check_invalid_params: true) produce expected outcome
cmd.parse
cmd.run

Actual behaviour

ruby test-command.rb KEYWORD=test -b 5
# => params {}
# => remaining ["5"]

The keyword is not being output in either the params or the remaining.

Expected behaviour

The keyword is captured.

Describe your environment

  • OS version: macOS 12.2 arm64
  • Ruby version: ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [arm64-darwin21]
  • TTY::Option version: 0.2.0

Hi Brian ๐Ÿ‘‹

Thanks for this issue report. Would you have time to investigate?

This behaviour is by design as expressed in the features section:

Parsing doesn't raise errors by default and collects issues to allow for a better user experience.

By default, all the unrecognised parameters are collected as errors. You can print errors with params.errors.summary:

# test-command.rb
require 'tty-option'

class Command
  include TTY::Option

  def run
    puts "params #{params.to_h.inspect}"
    puts "remaining #{params.remaining.inspect}"
    puts params.errors.summary
  end
end

cmd = Command.new
# Neither cmd.parse nor cmd.parse(check_invalid_params: true) produce expected outcome
cmd.parse
cmd.run

This will output:

params {}
remaining ["5"]
Errors:
  1) Invalid option '-b'
  2) Invalid environment keyword=test

If you don't want to check the validity of parameters and collect all of them as remaining use check_invalid_params set to false.

cmd.parse(check_invalid_params: false)

This will output:

params {}
remaining ["KEYWORD=test", "-b", "5"]

You're in full control of how the parameters are parsed. The :raise_on_parse_error configuration may also be handy.