Skip to content

Commit

Permalink
Change missing argument to accept failed param
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrmurach committed Apr 15, 2020
1 parent b498210 commit 5433cf3
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 10 deletions.
4 changes: 3 additions & 1 deletion lib/tty/option/error_aggregator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ def call(error, message, param = nil)
.gsub(/([a-z]+)([A-Z])/, "\\1_\\2")
.downcase.to_sym

if param
if error.respond_to?(:param) && error.param
(@errors[error.param.name] ||= {}).merge!(type_key => message)
elsif param
(@errors[param.name] ||= {}).merge!(type_key => message)
else
(@errors[:messages] ||= []) << { type_key => message }
Expand Down
16 changes: 14 additions & 2 deletions lib/tty/option/errors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,25 @@ def pluralize(noun, count = 1)
InvalidValidation = Class.new(Error)

# Raised when option requires an argument
MissingArgument = Class.new(Error)
class MissingArgument < Error
attr_reader :param

def initialize(param, switch_name = nil)
@param = param
name = switch_name.nil? ? param.name : switch_name
message = "#{param.to_sym} #{name} requires an argument"

super(message)
end
end

# Raised when a parameter is required but not present
class MissingParameter < Error
attr_reader :param

def initialize(param_or_message)
if param_or_message.is_a?(Parameter)
param = param_or_message
@param = param_or_message

name = if param.respond_to?(:long_name)
param.long? ? param.long_name : param.short_name
Expand Down
11 changes: 4 additions & 7 deletions lib/tty/option/parser/options.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ class Options
# @api public
def initialize(options, **config)
@options = options
@raise_if_missing = config.fetch(:raise_if_missing) { true }
@check_invalid_options = config.fetch(:check_invalid_options) { true }
@error_aggregator = ErrorAggregator.new(**config)
@parsed = {}
Expand Down Expand Up @@ -133,9 +132,8 @@ def process_double_option(long, sep, rest)
elsif !@argv.empty?
value = opt.multi_argument? ? consume_arguments : @argv.shift
else
@error_aggregator.(MissingArgument,
"option #{long} requires an argument",
opt)
error = MissingArgument.new(opt, long)
@error_aggregator.(error, error.message)
end
elsif opt.argument_optional?
if !rest.empty?
Expand Down Expand Up @@ -194,9 +192,8 @@ def process_single_option(short, other_singles)
elsif !@argv.empty?
value = opt.multi_argument? ? consume_arguments : @argv.shift
else
@error_aggregator.(MissingArgument,
"option #{short} requires an argument",
opt)
error = MissingArgument.new(opt, short)
@error_aggregator.(error, error.message)
end
elsif opt.argument_optional?
if !other_singles.empty?
Expand Down

0 comments on commit 5433cf3

Please sign in to comment.