summaryrefslogtreecommitdiff
path: root/lib/optparse.rb
diff options
context:
space:
mode:
authorNobuyoshi Nakada <nobu@ruby-lang.org>2024-02-09 19:03:20 +0900
committerNobuyoshi Nakada <nobu@ruby-lang.org>2024-02-09 19:58:31 +0900
commitdb73226bf6aa8c67ad6976ff6b3c628cf6b8a952 (patch)
tree4ad00621b4b7f970df8c814b90687310248f5e93 /lib/optparse.rb
parent2c6767b71ef5154f49e4aef7a236849a934e68fb (diff)
[ruby/optparse] Adjust arguments for lambda-callbacks
Rake uses [lambda] as callbacks. Calling it without omitted argument raises an `ArgumentError`. lambda: https://github.com/ruby/rake/blob/master/lib/rake/application.rb#L543 https://github.com/ruby/optparse/commit/213cb03b59
Diffstat (limited to 'lib/optparse.rb')
-rw-r--r--lib/optparse.rb21
1 files changed, 16 insertions, 5 deletions
diff --git a/lib/optparse.rb b/lib/optparse.rb
index d363b910ef..fbcd7f9746 100644
--- a/lib/optparse.rb
+++ b/lib/optparse.rb
@@ -1639,7 +1639,7 @@ XXX
# Non-option arguments remain in +argv+.
#
def order!(argv = default_argv, into: nil, &nonopt)
- setter = ->(name, val = nil) {into[name.to_sym] = val} if into
+ setter = ->(name, val) {into[name.to_sym] = val} if into
parse_in_order(argv, setter, &nonopt)
end
@@ -1665,8 +1665,8 @@ XXX
end
begin
opt, cb, *val = sw.parse(rest, argv) {|*exc| raise(*exc)}
- val = cb.call(*val) if cb
- setter.call(sw.switch_name, *val) if setter
+ val = callback!(cb, 1, *val) if cb
+ callback!(setter, 2, sw.switch_name, *val) if setter
rescue ParseError
raise $!.set_option(arg, rest)
end
@@ -1704,8 +1704,8 @@ XXX
end
begin
argv.unshift(opt) if opt and (!rest or (opt = opt.sub(/\A-*/, '-')) != '-')
- val = cb.call(*val) if cb
- setter.call(sw.switch_name, *val) if setter
+ val = callback!(cb, 1, *val) if cb
+ callback!(setter, 2, sw.switch_name, *val) if setter
rescue ParseError
raise $!.set_option(arg, arg.length > 2)
end
@@ -1731,6 +1731,17 @@ XXX
end
private :parse_in_order
+ # Calls callback with _val_.
+ def callback!(cb, max_arity, *args) # :nodoc:
+ if (size = args.size) < max_arity and cb.to_proc.lambda?
+ (arity = cb.arity) < 0 and arity = (1-arity)
+ arity = max_arity if arity > max_arity
+ args[arity - 1] = nil if arity > size
+ end
+ cb.call(*args)
+ end
+ private :callback!
+
#
# Parses command line arguments +argv+ in permutation mode and returns
# list of non-option arguments. When optional +into+ keyword