dry-cli 1.4.1 → 2.0.0.rc1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,22 +2,88 @@
2
2
 
3
3
  require "forwardable"
4
4
  require "dry/cli/option"
5
+ require "dry/cli/stream"
6
+ require "dry/cli/style_mixin"
5
7
 
6
8
  module Dry
7
9
  class CLI
8
10
  # Base class for commands
9
11
  #
12
+ # ## Streams
13
+ #
14
+ # A command should write to the streams it is given, available as {#stdout}, {#stderr} and
15
+ # {#stdin}. These are set before `#initialize` runs, so you can access them in your
16
+ # `#initialize` as required.
17
+ #
18
+ # A command registered as an instance (instead of a class) is built before the CLI knows where
19
+ # its output should go, so at that point {#stdout} and {#stderr} fall back to Ruby's standard
20
+ # `$stdout` and `$stderr`. The CLI's real streams arrive later, when the command is called, so
21
+ # you should build on top of streams only when you use them:
22
+ #
23
+ # ```
24
+ # # Wrong: built at initialization; captures the fallback stream
25
+ # def initialize
26
+ # @logger = Logger.new(stdout)
27
+ # end
28
+ #
29
+ # # Right: built on first use; captures the stream the CLI is using
30
+ # def logger
31
+ # @logger ||= Logger.new(stdout)
32
+ # end
33
+ # ```
34
+ #
35
+ # ## Exiting
36
+ #
37
+ # To stop the CLI with an exit code, throw `:exit` with the code:
38
+ #
39
+ # ```
40
+ # def call(**)
41
+ # unless File.exist?("config.yml")
42
+ # stderr.puts "config.yml not found"
43
+ # throw :exit, 1
44
+ # end
45
+ # end
46
+ # ```
47
+ #
48
+ # The CLI catches this and exits with the code. Throw `:exit` instead of calling `Kernel#exit`,
49
+ # so that tests can give the CLI their own `exit:` and check the code (see {Dry::CLI#call}).
50
+ #
51
+ # To stop with a message for the user, raise {Dry::CLI::ExitError} (or your own subclass of it).
52
+ # The CLI prints the message to stderr, with no backtrace, and exits with the error's exit code
53
+ # (1 by default). This works from anywhere the command calls in the same thread, such as a
54
+ # helper object:
55
+ #
56
+ # ```
57
+ # raise Dry::CLI::ExitError, "config.yml not found"
58
+ # raise Dry::CLI::ExitError.new("deploy failed", exit_code: 2)
59
+ # ```
60
+ #
61
+ # When you call a command directly (with no CLI around it), nothing catches these for you. Wrap
62
+ # the call in `catch(:exit)` to get a thrown code. A {Dry::CLI::ExitError} is raised as normal,
63
+ # so rescue it (or, in a test, expect it to be raised):
64
+ #
65
+ # ```
66
+ # code = catch(:exit) { command.call }
67
+ #
68
+ # expect { command.call }.to raise_error(Dry::CLI::ExitError, "config.yml not found")
69
+ # ```
70
+ #
71
+ # @api public
10
72
  # @since 0.1.0
11
73
  class Command
74
+ include StyleMixin
75
+ extend StyleMixin
76
+
12
77
  # @since 0.1.0
13
78
  # @api private
14
79
  def self.inherited(base)
15
80
  super
16
81
  base.class_eval do
17
- @_mutex = Mutex.new
18
- @description = nil
19
- @examples = []
20
- @subcommands = []
82
+ @_mutex = Mutex.new
83
+ @description = nil
84
+ @long_description = nil
85
+ @examples = []
86
+ @subcommands = []
21
87
  @arguments = base.superclass_arguments || []
22
88
  @options = base.superclass_options || []
23
89
  end
@@ -31,6 +97,9 @@ module Dry
31
97
  # @api private
32
98
  attr_reader :description
33
99
 
100
+ # @api private
101
+ attr_reader :long_description
102
+
34
103
  # @since 0.1.0
35
104
  # @api private
36
105
  attr_reader :examples
@@ -52,8 +121,6 @@ module Dry
52
121
  #
53
122
  # @param description [String] the description
54
123
  #
55
- # @since 0.1.0
56
- #
57
124
  # @example
58
125
  # require "dry/cli"
59
126
  #
@@ -64,10 +131,43 @@ module Dry
64
131
  # # ...
65
132
  # end
66
133
  # end
134
+ #
135
+ # @api public
136
+ # @since 0.1.0
67
137
  def self.desc(description)
68
138
  @description = description
69
139
  end
70
140
 
141
+ # Set the long description of the command
142
+ #
143
+ # It is printed in the "Description" section of the full command help (`--help`). Short help
144
+ # (`-h`) and command listings keep using the short description set via `.desc`. When no long
145
+ # description is set, `--help` falls back to the short description.
146
+ #
147
+ # @param long_description [String] the long description
148
+ #
149
+ # @example
150
+ # require "dry/cli"
151
+ #
152
+ # class Echo < Dry::CLI::Command
153
+ # desc "Prints given input"
154
+ # long_desc <<~DESC
155
+ # Prints the given input back to standard output.
156
+ #
157
+ # When no input is given, it prints an empty line.
158
+ # DESC
159
+ #
160
+ # def call(*)
161
+ # # ...
162
+ # end
163
+ # end
164
+ #
165
+ # @api public
166
+ # @since unreleased
167
+ def self.long_desc(long_description)
168
+ @long_description = long_description
169
+ end
170
+
71
171
  # Describe the usage of the command
72
172
  #
73
173
  # @param examples [Array<String>] one or more examples
@@ -78,13 +178,11 @@ module Dry
78
178
  # require "dry/cli"
79
179
  #
80
180
  # class Server < Dry::CLI::Command
81
- # example [
82
- # " # Basic usage (it uses the bundled server engine)",
83
- # "--server=webrick # Force `webrick` server engine",
84
- # "--host=0.0.0.0 # Bind to a host",
85
- # "--port=2306 # Bind to a port",
86
- # "--no-code-reloading # Disable code reloading"
87
- # ]
181
+ # example "", "Basic usage (it uses the bundled server engine)",
182
+ # example "--server=webrick, "Force `webrick` server engine",
183
+ # example "--host=0.0.0.0, "Bind to a host",
184
+ # example "--port=2306", "Bind to a port",
185
+ # example "--no-code-reloading", "Disable code reloading"
88
186
  #
89
187
  # def call(*)
90
188
  # # ...
@@ -100,15 +198,22 @@ module Dry
100
198
  # # foo server --host=0.0.0.0 # Bind to a host
101
199
  # # foo server --port=2306 # Bind to a port
102
200
  # # foo server --no-code-reloading # Disable code reloading
103
- def self.example(*examples)
104
- @examples += examples.flatten(1)
201
+ def self.example(example, description = "")
202
+ @examples.push([example, description])
105
203
  end
106
204
 
107
205
  # Specify an argument
108
206
  #
207
+ # Arguments are matched by position, so required arguments must be declared before optional
208
+ # ones. An array argument takes all the remaining values, so it must be declared last.
209
+ #
109
210
  # @param name [Symbol] the argument name
110
211
  # @param options [Hash] a set of options
111
212
  #
213
+ # @raise [Dry::CLI::CommandDefinitionError] if a required argument is declared after an
214
+ # optional one, if any argument is declared after an array argument, or if the argument is
215
+ # both required and has a default
216
+ #
112
217
  # @since 0.1.0
113
218
  #
114
219
  # @example Optional argument
@@ -197,12 +302,49 @@ module Dry
197
302
  def self.argument(name, options = {})
198
303
  new_arg = Argument.new(name, options)
199
304
 
200
- duplicate_index = @arguments.find_index { _1.name == new_arg.name }
201
- @arguments.delete_at(duplicate_index) unless duplicate_index.nil?
305
+ arguments = @arguments.dup
306
+
307
+ # Replace a redeclared argument where it is, since arguments are matched by position
308
+ index = arguments.find_index { _1.name == new_arg.name } || arguments.length
309
+ arguments[index] = new_arg
202
310
 
203
- @arguments << new_arg
311
+ if (error = argument_position_error(arguments, index))
312
+ raise CommandDefinitionError, error
313
+ end
314
+
315
+ @arguments.replace(arguments)
204
316
  end
205
317
 
318
+ # Returns an error message if the argument at `index` can never be given a value in its
319
+ # position, or nil if its position is valid.
320
+ #
321
+ # Every other argument was checked when it was declared, so only the argument at `index` is
322
+ # checked here.
323
+ #
324
+ # @api private
325
+ # rubocop:disable Metrics/AbcSize, Metrics/PerceivedComplexity
326
+ def self.argument_position_error(arguments, index)
327
+ argument = arguments[index]
328
+ before = arguments.take(index)
329
+ after = arguments.drop(index + 1)
330
+
331
+ # An array argument takes all the remaining values, so no argument can come after it
332
+ if (array_arg = before.find(&:array?))
333
+ "argument `#{argument.name}' can't be declared after array argument `#{array_arg.name}'"
334
+ elsif argument.array? && after.any?
335
+ "array argument `#{argument.name}' can't be declared before argument `#{after.first.name}'"
336
+ # A required argument after an optional one could never be given without also giving the
337
+ # optional one
338
+ elsif argument.required? && (optional_arg = before.find { !_1.required? })
339
+ "required argument `#{argument.name}' can't be declared after optional argument " \
340
+ "`#{optional_arg.name}'"
341
+ elsif !argument.required? && (required_arg = after.find(&:required?))
342
+ "optional argument `#{argument.name}' can't be declared before required argument " \
343
+ "`#{required_arg.name}'"
344
+ end
345
+ end
346
+ # rubocop:enable Metrics/AbcSize, Metrics/PerceivedComplexity
347
+
206
348
  # Command line option (aka optional argument)
207
349
  #
208
350
  # @param name [Symbol] the param name
@@ -262,7 +404,7 @@ module Dry
262
404
  # # # ...
263
405
  # #
264
406
  # # Options:
265
- # # --engine=VALUE # Force a console engine: (irb/pry/ripl)
407
+ # # --engine=VALUE # Force a console engine: (irb, pry, ripl)
266
408
  # # --help, -h # Print this help
267
409
  #
268
410
  # @example Boolean
@@ -313,6 +455,34 @@ module Dry
313
455
  # #
314
456
  # # Options:
315
457
  # # --port=VALUE, -p VALUE
458
+ #
459
+ # @example Required
460
+ # require "dry/cli"
461
+ #
462
+ # class Deploy < Dry::CLI::Command
463
+ # option :env, required: true, desc: "The target environment"
464
+ #
465
+ # def call(env:, **)
466
+ # puts "deploying to #{env}"
467
+ # end
468
+ # end
469
+ #
470
+ # # $ foo deploy --env=production
471
+ # # deploying to production
472
+ #
473
+ # # $ foo deploy
474
+ # # ERROR: "foo deploy" is missing required option --env
475
+ # # Usage: "foo deploy --env=VALUE"
476
+ #
477
+ # # $ foo deploy --help
478
+ # # # ...
479
+ # #
480
+ # # Options:
481
+ # # --env=VALUE # REQUIRED The target environment
482
+ # # --help, -h # Print this help
483
+ #
484
+ # # A required option with a default always has a value, so it is not
485
+ # # enforced and not shown as REQUIRED.
316
486
  def self.option(name, options = {})
317
487
  new_op = Option.new(name, options)
318
488
 
@@ -350,6 +520,36 @@ module Dry
350
520
  arguments.reject(&:required?)
351
521
  end
352
522
 
523
+ # @since 1.3.0
524
+ # @api private
525
+ # rubocop:disable Metrics/PerceivedComplexity
526
+ def self.arguments_sorted_by_usage_order
527
+ args = required_arguments + optional_arguments
528
+
529
+ args.sort! do |a1, a2|
530
+ a1_priority = a2_priority = 0
531
+
532
+ a1_priority += 2 unless a1.array?
533
+ a2_priority += 2 unless a2.array?
534
+ a1_priority += 1 if a1.required?
535
+ a2_priority += 1 if a2.required?
536
+
537
+ if a1_priority > a2_priority
538
+ -1
539
+ elsif a2_priority > a1_priority
540
+ 1
541
+ else
542
+ 0
543
+ end
544
+ end
545
+ end
546
+ # rubocop:enable Metrics/PerceivedComplexity
547
+
548
+ # @api private
549
+ def self.required_options
550
+ options.select(&:required?)
551
+ end
552
+
353
553
  # @since 0.7.0
354
554
  # @api private
355
555
  def self.subcommands
@@ -376,52 +576,262 @@ module Dry
376
576
  superclass_variable_dup(:@options)
377
577
  end
378
578
 
579
+ # Returns the keywords that `.new` gives to `#auto_initialize`, rather than passing on to
580
+ # `#initialize` itself.
581
+ #
582
+ # Auto-initialized keywords allow for the command classes in your CLI app to keep their
583
+ # `#initialize` methods focused on their distinct dependencies only, while "standard"
584
+ # dependencies (those required for every command) are still assigned as expected.
585
+ #
586
+ # This means that command class authors do not need to supply `**kwargs` as an `#initialize`
587
+ # parameter and then call `super(**kwargs)`. This reduces boilerplate, as well as the chance
588
+ # of bugs from these lines being forgotten.
589
+ #
590
+ # These are collected from every `#auto_initialize` in the command's ancestry, so a class
591
+ # adding its own needs only to declare and assign them. Define it alongside your
592
+ # `#initialize`, since the two share the job of setting the command up:
593
+ #
594
+ # ```
595
+ # private def auto_initialize(inflector: Dry::Inflector.new, **kwargs)
596
+ # super(**kwargs)
597
+ # @inflector = inflector
598
+ # end
599
+ # ```
600
+ #
601
+ # Auto-initialized keywords are best used sparingly. Consider these for your CLI app's base
602
+ # command class only.
603
+ #
604
+ # A command cannot use auto-initialized keywords as its own `#initialize` parameters, since it
605
+ # will never receive them.
606
+ #
607
+ # @return [Array<Symbol>]
608
+ #
609
+ # @api private
610
+ def self.auto_initialize_keywords
611
+ keywords = []
612
+ method = instance_method(:auto_initialize)
613
+
614
+ # Each `#auto_initialize` declares the keywords it wants, then should take the rest as
615
+ # `**kwargs` to hand to `super`, so follow that same path to collect them all.
616
+ while method
617
+ own_keywords = method.parameters.filter_map { |type, keyword|
618
+ keyword if type == :key || type == :keyreq
619
+ }
620
+ keywords = own_keywords | keywords
621
+
622
+ # A method taking no `**kwargs` presumably never calls super; end the chain here.
623
+ break unless method.parameters.any? { |type, _| type == :keyrest }
624
+
625
+ method = method.super_method
626
+ end
627
+
628
+ keywords
629
+ end
630
+
631
+ # Returns a new command.
632
+ #
633
+ # The {.auto_initialize_keywords} are taken here and given to {#auto_initialize} before
634
+ # `#initialize` runs. This allows a subclass to declare its own `#initialize` concerned with
635
+ # only its own arguments, and still use {#stdout}, {#stderr} and {#stdin} inside `#initialize`
636
+ # as needed. All other arguments are passed along untouched.
637
+ #
638
+ # @param args [Array] arguments for the command's own `#initialize`
639
+ # @param kwargs [Hash] the auto-initialized keywords, plus any for the command's own
640
+ # `#initialize`
641
+ #
642
+ # @return [Dry::CLI::Command]
643
+ #
644
+ # @since x.y.z
645
+ # @api public
646
+ def self.new(*args, **kwargs, &block)
647
+ auto_initialize_keywords = self.auto_initialize_keywords
648
+
649
+ allocate.tap { |command|
650
+ command.send(:auto_initialize, **kwargs.slice(*auto_initialize_keywords))
651
+ command.send(:initialize, *args, **kwargs.except(*auto_initialize_keywords), &block)
652
+ }
653
+ end
654
+
655
+ # Assigns framework-level attributes before `#initialize` runs.
656
+ #
657
+ # @see .auto_initialize_keywords
658
+ #
659
+ # @api private
660
+ private def auto_initialize(stderr: nil, stdin: nil, stdout: nil)
661
+ set_streams(stderr:, stdin:, stdout:)
662
+ end
663
+
379
664
  extend Forwardable
380
665
 
381
666
  delegate %i[
667
+ arguments
668
+ arguments_sorted_by_usage_order
669
+ default_params
382
670
  description
671
+ long_description
383
672
  examples
384
- arguments
673
+ optional_arguments
385
674
  options
386
675
  params
387
- default_params
388
676
  required_arguments
389
- optional_arguments
677
+ required_options
390
678
  subcommands
391
679
  ] => "self.class"
392
680
 
393
- protected
394
-
395
681
  # The error output used to print error messaging
396
682
  #
683
+ # @return [Dry::CLI::Stream] for the stream given to this command, or `$stderr`
684
+ #
397
685
  # @example
398
686
  # class MyCommand
399
687
  # def call
400
- # out.puts "Hello World!"
401
- # exit(0)
402
- # rescue StandardError => e
403
- # err.puts "Uh oh: #{e.message}"
404
- # exit(1)
688
+ # stdout.puts File.read("config.yml")
689
+ # rescue Errno::ENOENT
690
+ # stderr.puts "config.yml not found"
691
+ # throw :exit, 1
405
692
  # end
406
693
  # end
407
694
  #
408
- # @since unreleased
409
- # @return [IO]
410
- attr_reader :err
695
+ # @since x.y.z
696
+ def stderr
697
+ # When we haven't been given an underlying stream, build a new one for $stderr each time,
698
+ # since it can be swapped out from under us. This is the case only when testing commands in
699
+ # isolation; when the CLI runs normally, we have a real @stderr set.
700
+ return Stream.for($stderr) unless @stderr
411
701
 
412
- # The standard output object used to print messaging
702
+ @stderr_stream ||= Stream.for(@stderr)
703
+ end
704
+
705
+ # The standard input stream used for reading input
706
+ #
707
+ # @return [IO] the stream given to this command, or `$stdin`
413
708
  #
414
709
  # @example
415
710
  # class MyCommand
416
711
  # def call
417
- # out.puts "Hello World!"
418
- # exit(0)
712
+ # name = stdin.gets.chomp
713
+ # stdout.puts "Hello #{name}!"
419
714
  # end
420
715
  # end
421
716
  #
422
- # @since unreleased
423
- # @return [IO]
424
- attr_reader :out
717
+ # @since x.y.z
718
+ def stdin
719
+ @stdin || $stdin
720
+ end
721
+
722
+ # The standard output stream used for normal output
723
+ #
724
+ # @return [Dry::CLI::Stream] for the stream given to this command, or `$stdout`
725
+ #
726
+ # @example
727
+ # class MyCommand
728
+ # def call
729
+ # stdout.puts "Hello World!"
730
+ # end
731
+ # end
732
+ #
733
+ # @since x.y.z
734
+ def stdout
735
+ # When we haven't been given an underlying stream, build a new one for $stdout each time,
736
+ # since it can be swapped out from under us. This is the case only when testing commands in
737
+ # isolation; when the CLI runs normally, we have a real @stdout set.
738
+ return Stream.for($stdout) unless @stdout
739
+
740
+ @stdout_stream ||= Stream.for(@stdout)
741
+ end
742
+
743
+ # Returns a copy of this command, configured to write to the given streams.
744
+ #
745
+ # Called on a command registered as an instance, since it is constructed before the CLI is
746
+ # invoked, and therefore before it knows where its output should go.
747
+ #
748
+ # @api private
749
+ def with_streams(stderr:, stdin:, stdout:)
750
+ dup.send(:set_streams, stderr:, stdin:, stdout:)
751
+ end
752
+
753
+ private
754
+
755
+ # @see #with_streams
756
+ #
757
+ # @api private
758
+ def set_streams(stderr:, stdin:, stdout:)
759
+ @stderr = stderr
760
+ @stdin = stdin
761
+ @stdout = stdout
762
+ @stderr_stream = nil
763
+ @stdout_stream = nil
764
+
765
+ self
766
+ end
767
+
768
+ # Writes to the command's own {#stdout}, rather than the default `$stdout`.
769
+ #
770
+ # Commands are given the streams they write to, so `puts` inside one goes to the stream this
771
+ # command was given, not to `$stdout`. That's what keeps styling right when the two differ:
772
+ # text written here is styled for the stream it lands on.
773
+ #
774
+ # @example
775
+ # class MyCommand
776
+ # def call
777
+ # puts "Hello World!"
778
+ # end
779
+ # end
780
+ #
781
+ # @since x.y.z
782
+ def puts(*args)
783
+ stdout.puts(*args)
784
+ end
785
+
786
+ # Writes to the command's own {#stdout}, rather than the default `$stdout`.
787
+ #
788
+ # @see #puts
789
+ #
790
+ # @since x.y.z
791
+ def print(*args)
792
+ stdout.print(*args)
793
+ end
794
+
795
+ # Runs another command from within this one.
796
+ #
797
+ # The other command is built with this command's auto-initialized keywords, so it writes to
798
+ # the same streams and shares any standard dependencies your base command class adds. Each
799
+ # value is read back through the reader of the same name, so every auto-initialized keyword
800
+ # needs a reader.
801
+ #
802
+ # The other command's option defaults apply to any options not given (or given as nil), and
803
+ # it is given only the keywords its `#call` accepts, so you can pass along all of this
804
+ # command's own options. When you do, this command's option defaults are passed along too,
805
+ # and replace the other command's defaults for any options they share.
806
+ #
807
+ # Unlike running the other command from the command line, the given values are not cast to
808
+ # their option types or checked against `required:` or `values:`, and no `before` or `after`
809
+ # callbacks registered for the other command are run.
810
+ #
811
+ # @example
812
+ # class Migrate < MyApp::Command
813
+ # def call(...)
814
+ # invoke(Create, ...)
815
+ # # ...
816
+ # end
817
+ # end
818
+ #
819
+ # @param command_class [Class] the command to run
820
+ # @param kwargs [Hash] the options and arguments for the command's `#call`
821
+ #
822
+ # @return [Object] the result of the command's `#call`
823
+ #
824
+ # @see .auto_initialize_keywords
825
+ #
826
+ # @since 2.0.0
827
+ # @api public
828
+ private def invoke(command_class, **kwargs)
829
+ dependencies = (self.class.auto_initialize_keywords & command_class.auto_initialize_keywords)
830
+ .to_h { |keyword| [keyword, send(keyword)] }
831
+
832
+ command = command_class.new(**dependencies)
833
+ command.call(**Dispatch.command_accepted_kwargs(command, command_class.default_params.merge(kwargs.compact)))
834
+ end
425
835
  end
426
836
  end
427
837
  end
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "dry/cli/dispatch"
4
+
3
5
  module Dry
4
6
  class CLI
5
7
  # Command registry
@@ -255,7 +257,7 @@ module Dry
255
257
  # @api private
256
258
  def run(context, **args)
257
259
  chain.each do |callback|
258
- context.instance_exec(**args, &callback)
260
+ context.instance_exec(**Dispatch.accepted_kwargs(callback, args), &callback)
259
261
  end
260
262
  end
261
263
  end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dry
4
+ class CLI
5
+ # Matches the parsed keyword args against the params that a command or callback declares.
6
+ #
7
+ # Commands and callbacks only declare params for the keyword args they care about, but the
8
+ # parsed keyword args also carry whatever other gems have contributed to the same command (see
9
+ # {Registry#option}). This keeps each of them free of a catch-all `**` param just to tolerate
10
+ # keyword args they know nothing about.
11
+ #
12
+ # For public use, see {Dry::CLI.accepted_kwargs}.
13
+ #
14
+ # @api private
15
+ module Dispatch
16
+ # Param kinds that mean the callable can be given every keyword arg. See {.accepted_kwargs}.
17
+ WHOLE_HASH = %i[keyrest req opt rest].freeze
18
+
19
+ # The keyword args from `kwargs` that `callable` can accept.
20
+ #
21
+ # Two kinds of callable are given every keyword arg: one declaring a keyword splat param,
22
+ # which absorbs whatever it doesn't name; and one declaring a positional param, because `**`
23
+ # collapses to a single Hash when the callable declares no keyword params.
24
+ #
25
+ # Every other callable is given only the keyword args that match its keyword params. This also
26
+ # means that a callable declaring no params (e.g. `def call`) will receive no args.
27
+ #
28
+ # @param callable [Method, Proc] the command's `#call` method, or a callback
29
+ # @param kwargs [Hash] the parsed keyword args
30
+ #
31
+ # @return [Hash]
32
+ def self.accepted_kwargs(callable, kwargs)
33
+ params = callable.parameters
34
+ return kwargs if params.any? { |type, _| WHOLE_HASH.include?(type) }
35
+
36
+ kwargs.slice(*params.filter_map { |type, name| name if type == :key || type == :keyreq })
37
+ end
38
+
39
+ # The keyword args that `command` can accept, for commands implementing `#call`.
40
+ #
41
+ # Falls back to all of them for commands that answer `#call` via `method_missing`, and so have
42
+ # no params to inspect.
43
+ #
44
+ # @param command [Dry::CLI::Command] the command instance
45
+ # @param kwargs [Hash] the parsed keyword args
46
+ #
47
+ # @return [Hash]
48
+ def self.command_accepted_kwargs(command, kwargs)
49
+ accepted_kwargs(command.method(:call), kwargs)
50
+ rescue NameError
51
+ kwargs
52
+ end
53
+ end
54
+ end
55
+ end