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.
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dry
4
+ class CLI
5
+ # Yield to a block on a regular interval
6
+ #
7
+ # @api public
8
+ # @since x.y.z
9
+ class Ticker
10
+ attr_reader :interval
11
+
12
+ # @see #start
13
+ # @api public
14
+ # @since x.y.z
15
+ def self.start(interval: 1.0, &)
16
+ new(interval:).start(&)
17
+ end
18
+
19
+ def initialize(interval: 1.0)
20
+ @interval = interval
21
+ end
22
+
23
+ # Begin the ticker thread, which will yield to the given block on `interval` seconds.
24
+ #
25
+ # @api public
26
+ # @since x.y.z
27
+ #
28
+ # @yield The block to yield to on each tick
29
+ # @return [self]
30
+ def start
31
+ @running = true
32
+ @thread = Thread.new do
33
+ while @running
34
+ start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
35
+ yield
36
+ elapsed_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time
37
+ sleep([@interval - elapsed_time, 0].max)
38
+ end
39
+ end
40
+
41
+ self
42
+ end
43
+
44
+ # Stop the ticker thread.
45
+ #
46
+ # @api public
47
+ # @since x.y.z
48
+ #
49
+ # @return [void]
50
+ def stop
51
+ @running = false
52
+ @thread&.wakeup if @thread&.alive?
53
+ @thread&.join
54
+ end
55
+ end
56
+ end
57
+ end
data/lib/dry/cli/usage.rb CHANGED
@@ -33,15 +33,10 @@ module Dry
33
33
  def self.commands_and_arguments(result)
34
34
  max_length = 0
35
35
  ret = commands(result).each_with_object({}) do |(name, node), memo|
36
- args = if node.command && node.leaf? && node.children?
37
- ROOT_COMMAND_WITH_SUBCOMMANDS_BANNER
38
- elsif node.leaf?
39
- arguments(node.command)
40
- else
41
- SUBCOMMAND_BANNER
42
- end
43
-
44
- partial = " #{command_name(result, name)}#{args}"
36
+ args = arguments(node.command)
37
+ args_banner = arguments_banner(node, args)
38
+
39
+ partial = " #{command_name(result, name)}#{args_banner}"
45
40
  max_length = partial.bytesize if max_length < partial.bytesize
46
41
  memo[partial] = node
47
42
  end
@@ -54,20 +49,32 @@ module Dry
54
49
  def self.arguments(command)
55
50
  return unless CLI.command?(command)
56
51
 
57
- required_arguments = command.required_arguments
58
- optional_arguments = command.optional_arguments
52
+ args = command.arguments_sorted_by_usage_order
53
+ args.map! do |a|
54
+ # a.to_s raises deprecation warning that it will result in a frozen string in the future
55
+ name = a.required? ? "#{a.name}" : "[#{a.name}]" # rubocop:disable Style/RedundantInterpolation
56
+ name.upcase!
57
+ end
59
58
 
60
- required = required_arguments.map { |arg| arg.name.upcase }.join(" ") if required_arguments.any?
61
- optional = optional_arguments.map { |arg| "[#{arg.name.upcase}]" }.join(" ") if optional_arguments.any?
62
- result = [required, optional].compact
59
+ " #{args.join(" ")}" unless args.empty?
60
+ end
63
61
 
64
- " #{result.join(" ")}" unless result.empty?
62
+ # @since 2.0.0
63
+ # @api private
64
+ def self.arguments_banner(node, args) # rubocop:disable Metrics/PerceivedComplexity
65
+ if node.command && node.leaf? && node.children? && args
66
+ ROOT_COMMAND_WITH_SUBCOMMANDS_BANNER
67
+ elsif node.leaf? && args
68
+ args
69
+ elsif node.children?
70
+ SUBCOMMAND_BANNER
71
+ end
65
72
  end
66
73
 
67
74
  # @since 0.1.0
68
75
  # @api private
69
76
  def self.description(command)
70
- return unless CLI.command?(command)
77
+ return unless CLI.command?(command) || CLI.namespace?(command)
71
78
 
72
79
  " # #{command.description}" unless command.description.nil?
73
80
  end
@@ -3,6 +3,6 @@
3
3
  module Dry
4
4
  class CLI
5
5
  # @since 0.1.0
6
- VERSION = "1.4.1"
6
+ VERSION = "2.0.0.rc1"
7
7
  end
8
8
  end
data/lib/dry/cli.rb CHANGED
@@ -10,6 +10,11 @@ module Dry
10
10
  class CLI
11
11
  require "dry/cli/version"
12
12
  require "dry/cli/errors"
13
+ require "dry/cli/namespace"
14
+ require "dry/cli/ansi"
15
+ require "dry/cli/style"
16
+ require "dry/cli/stream"
17
+ require "dry/cli/style_mixin"
13
18
  require "dry/cli/command"
14
19
  require "dry/cli/registry"
15
20
  require "dry/cli/parser"
@@ -17,24 +22,86 @@ module Dry
17
22
  require "dry/cli/spell_checker"
18
23
  require "dry/cli/banner"
19
24
  require "dry/cli/inflector"
25
+ require "dry/cli/dispatch"
26
+
27
+ autoload :Spinner, "dry/cli/spinner"
20
28
 
21
29
  # Check if command
22
30
  #
23
31
  # @param command [Object] the command to check
24
32
  #
25
- # @return [TrueClass,FalseClass] true if instance of `Dry::CLI::Command`
33
+ # @return [Boolean] true if instance of `Dry::CLI::Command`
26
34
  #
27
35
  # @since 0.1.0
28
36
  # @api private
29
37
  def self.command?(command)
30
- case command
38
+ inherits?(command, Command)
39
+ end
40
+
41
+ # Check if namespace
42
+ #
43
+ # @param namespace [Object] the namespace to check
44
+ #
45
+ # @return [Boolean] true if instance of `Dry::CLI::Namespace`
46
+ #
47
+ # @since 1.1.1
48
+ # @api private
49
+ def self.namespace?(namespace)
50
+ inherits?(namespace, Namespace)
51
+ end
52
+
53
+ # Check if `obj` inherits from `klass`
54
+ #
55
+ # @param obj [Object] object to check
56
+ # @param klass [Object] class that should be inherited
57
+ #
58
+ # @return [Boolean] true if `obj` inherits from `klass`
59
+ #
60
+ # @since 1.1.1
61
+ # @api private
62
+ def self.inherits?(obj, klass)
63
+ case obj
31
64
  when Class
32
- command.ancestors.include?(Command)
65
+ obj.ancestors.include?(klass)
33
66
  else
34
- command.is_a?(Command)
67
+ obj.is_a?(klass)
35
68
  end
36
69
  end
37
70
 
71
+ # Returns the keyword args from `kwargs` that `callable` can accept, based on the params it
72
+ # declares.
73
+ #
74
+ # A callable declaring a keyword splat param (`**`) or a positional param gets every keyword
75
+ # arg. Any other callable gets only the keyword args that match its keyword params.
76
+ #
77
+ # Dry CLI uses this to call each command's `#call` and callbacks with only the keyword args that
78
+ # they accept. Use this yourself if you wrap a command's `#call`, to ensure that you only pass
79
+ # on the keyword args that the next `#call` accepts.
80
+ #
81
+ # @example
82
+ # class Deploy < Dry::CLI::Command
83
+ # def call(target:, force: false) = ...
84
+ # end
85
+ #
86
+ # kwargs = {target: "production", env: "test"}
87
+ #
88
+ # Dry::CLI.accepted_kwargs(Deploy.new.method(:call), kwargs)
89
+ # # => {target: "production"}
90
+ #
91
+ # Dry::CLI.accepted_kwargs(proc { |**opts| opts }, kwargs)
92
+ # # => {target: "production", env: "test"}
93
+ #
94
+ # @param callable [Method, Proc] the method or proc to be called
95
+ # @param kwargs [Hash] the keyword args to choose from
96
+ #
97
+ # @return [Hash] the keyword args that `callable` can accept
98
+ #
99
+ # @since 2.0.0
100
+ # @api public
101
+ def self.accepted_kwargs(callable, kwargs)
102
+ Dispatch.accepted_kwargs(callable, kwargs)
103
+ end
104
+
38
105
  # Create a new instance
39
106
  #
40
107
  # @param command_or_registry [Dry::CLI::Registry, Dry::CLI::Command]
@@ -56,14 +123,59 @@ module Dry
56
123
 
57
124
  # Invoke the CLI
58
125
  #
126
+ # A command (or a before/after callback) can stop the CLI with an exit code by throwing `:exit`:
127
+ #
128
+ # ```
129
+ # def call(**)
130
+ # stderr.puts "Something went wrong"
131
+ # throw :exit, 1
132
+ # end
133
+ # ```
134
+ #
135
+ # The CLI catches the throw and calls `exit` with the given code. A bare `throw :exit` exits
136
+ # with 0. The CLI also exits this way after printing help (0) and after an error such as an
137
+ # unknown option or command (1).
138
+ #
139
+ # A command can also raise {ExitError} (or a subclass). The CLI prints the error's message to
140
+ # stderr, with no backtrace, then calls `exit` with the error's `exit_code`.
141
+ #
142
+ # When nothing throws `:exit` or raises {ExitError}, the CLI returns normally and does not call
143
+ # `exit`.
144
+ #
59
145
  # @param arguments [Array<string>] the command line arguments (defaults to `ARGV`)
60
- # @param out [IO] the standard output (defaults to `$stdout`)
61
- # @param err [IO] the error output (defaults to `$stderr`)
146
+ # @param stderr [IO] the error output (defaults to `$stderr`)
147
+ # @param stdin [IO] the standard input (defaults to `$stdin`)
148
+ # @param stdout [IO] the standard output (defaults to `$stdout`)
149
+ # @param exit [#call] called with the exit code when the CLI exits (defaults to `Kernel#exit`)
150
+ #
151
+ # @example Checking the exit code in a test
152
+ # exit_code = nil
153
+ # cli.call(arguments: ["foo", "--unknown"], exit: ->(code) { exit_code = code })
154
+ # exit_code # => 1
62
155
  #
63
156
  # @since 0.1.0
64
- def call(arguments: ARGV, out: $stdout, err: $stderr)
65
- @out, @err = out, err
66
- kommand ? perform_command(arguments) : perform_registry(arguments)
157
+ def call(
158
+ arguments: ARGV,
159
+ stderr: $stderr,
160
+ stdin: $stdin,
161
+ stdout: $stdout,
162
+ exit: Kernel.method(:exit)
163
+ )
164
+ @stderr, @stdin, @stdout, @exit = Stream.for(stderr), stdin, Stream.for(stdout), exit
165
+
166
+ code = catch(:exit) do
167
+ return kommand ? perform_command(arguments) : perform_registry(arguments)
168
+ rescue ExitError => exception
169
+ begin
170
+ @stderr.puts(exception.message)
171
+ rescue Errno::EPIPE
172
+ # Exit with the error's code even when stderr is closed
173
+ end
174
+ exception.exit_code
175
+ end
176
+
177
+ # Ensure a bare `throw :exit` (which gives a nil code) becomes a success.
178
+ @exit.call(code.nil? ? 0 : code)
67
179
  rescue SignalException => exception
68
180
  signal_exception(exception)
69
181
  rescue Errno::EPIPE
@@ -80,13 +192,14 @@ module Dry
80
192
  # @api private
81
193
  attr_reader :kommand
82
194
 
83
- # @since 0.6.0
84
195
  # @api private
85
- attr_reader :out
196
+ attr_reader :stderr
86
197
 
87
- # @since 0.6.0
88
198
  # @api private
89
- attr_reader :err
199
+ attr_reader :stdin
200
+
201
+ # @api private
202
+ attr_reader :stdout
90
203
 
91
204
  # Invoke the CLI if singular command passed
92
205
  #
@@ -97,11 +210,7 @@ module Dry
97
210
  # @api private
98
211
  def perform_command(arguments)
99
212
  command, args = parse(kommand, arguments, [])
100
-
101
- command.instance_variable_set(:@err, err) unless command.instance_variable_defined?(:@err)
102
- command.instance_variable_set(:@out, out) unless command.instance_variable_defined?(:@out)
103
-
104
- command.call(**args)
213
+ command.call(**Dispatch.command_accepted_kwargs(command, args))
105
214
  end
106
215
 
107
216
  # Invoke the CLI if registry passed
@@ -116,21 +225,22 @@ module Dry
116
225
  return spell_checker(result, arguments) unless result.found?
117
226
 
118
227
  command, args = parse(result.command, result.arguments, result.names)
119
-
120
- command.instance_variable_set(:@err, err) unless command.instance_variable_defined?(:@err)
121
- command.instance_variable_set(:@out, out) unless command.instance_variable_defined?(:@out)
228
+ return stderr.puts(Usage.call(result)) unless command.respond_to?(:call)
122
229
 
123
230
  result.before_callbacks.run(command, **args)
124
- command.call(**args)
231
+ command.call(**Dispatch.command_accepted_kwargs(command, args))
125
232
  result.after_callbacks.run(command, **args)
126
233
  end
127
234
 
128
235
  # Parse arguments for a command.
129
236
  #
130
- # It may exit in case of error, or in case of help.
237
+ # When the arguments include `--help` or `-h`, it prints the command's help to stdout and exits
238
+ # with 0. When the arguments are invalid (such as an unknown option or a missing required
239
+ # argument), it prints the error to stderr and exits with 1.
131
240
  #
132
- # @param result [Dry::CLI::CommandRegistry::LookupResult]
133
- # @param out [IO] sta output
241
+ # @param command [Dry::CLI::Command, Class] the command to parse arguments for
242
+ # @param arguments [Array<String>] the command line arguments for the command
243
+ # @param names [Array<String>] the names used to find the command, for the program name
134
244
  #
135
245
  # @return [Array<Dry:CLI::Command, Array>] returns an array where the
136
246
  # first element is a command and the second one is the list of arguments
@@ -142,7 +252,7 @@ module Dry
142
252
 
143
253
  result = Parser.call(command, arguments, prog_name)
144
254
 
145
- return help(command, prog_name) if result.help?
255
+ return help(command, prog_name, long: result.long_help?) if result.help?
146
256
 
147
257
  return error(result) if result.error?
148
258
 
@@ -152,29 +262,37 @@ module Dry
152
262
  # @since 0.6.0
153
263
  # @api private
154
264
  def build_command(command)
155
- command.is_a?(Class) ? command.new : command
265
+ unless command.is_a?(Class)
266
+ return command unless command.is_a?(Command)
267
+
268
+ return command.with_streams(stderr:, stdin:, stdout:)
269
+ end
270
+
271
+ return command.new(stderr:, stdin:, stdout:) if CLI.command?(command)
272
+
273
+ command.new
156
274
  end
157
275
 
158
276
  # @since 0.6.0
159
277
  # @api private
160
- def help(command, prog_name)
161
- out.puts Banner.call(command, prog_name)
162
- exit(0) # Successful exit
278
+ def help(command, prog_name, long: false)
279
+ stdout.puts Banner.call(command, prog_name, long: long)
280
+ throw :exit, 0
163
281
  end
164
282
 
165
283
  # @since 0.6.0
166
284
  # @api private
167
285
  def error(result)
168
- err.puts(result.error)
169
- exit(1)
286
+ stderr.puts(result.error)
287
+ throw :exit, 1
170
288
  end
171
289
 
172
290
  # @since 1.1.1
173
291
  def spell_checker(result, arguments)
174
292
  spell_checker = SpellChecker.call(result, arguments)
175
- err.puts "#{spell_checker}\n\n" if spell_checker
176
- err.puts Usage.call(result)
177
- exit(1)
293
+ stderr.puts "#{spell_checker}\n\n" if spell_checker
294
+ stderr.puts Usage.call(result)
295
+ throw :exit, 1
178
296
  end
179
297
 
180
298
  # Handles Exit codes for signals
@@ -183,14 +301,14 @@ module Dry
183
301
  # @since 0.7.0
184
302
  # @api private
185
303
  def signal_exception(exception)
186
- exit(128 + exception.signo)
304
+ @exit.call(128 + exception.signo)
187
305
  end
188
306
 
189
307
  # Check if command
190
308
  #
191
309
  # @param command [Object] the command to check
192
310
  #
193
- # @return [TrueClass,FalseClass] true if instance of `Dry::CLI::Command`
311
+ # @return [Boolean] true if instance of `Dry::CLI::Command`
194
312
  #
195
313
  # @since 0.1.0
196
314
  # @api private
metadata CHANGED
@@ -1,11 +1,11 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: dry-cli
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.4.1
4
+ version: 2.0.0.rc1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Hanakai team
8
- bindir: bin
8
+ bindir: exe
9
9
  cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
@@ -66,24 +66,38 @@ files:
66
66
  - README.md
67
67
  - dry-cli.gemspec
68
68
  - lib/dry/cli.rb
69
+ - lib/dry/cli/ansi.rb
69
70
  - lib/dry/cli/banner.rb
70
71
  - lib/dry/cli/command.rb
71
72
  - lib/dry/cli/command_registry.rb
73
+ - lib/dry/cli/dispatch.rb
72
74
  - lib/dry/cli/errors.rb
73
75
  - lib/dry/cli/inflector.rb
74
76
  - lib/dry/cli/inline.rb
77
+ - lib/dry/cli/namespace.rb
75
78
  - lib/dry/cli/option.rb
76
79
  - lib/dry/cli/parser.rb
77
80
  - lib/dry/cli/program_name.rb
78
81
  - lib/dry/cli/registry.rb
79
82
  - lib/dry/cli/spell_checker.rb
83
+ - lib/dry/cli/spinner.rb
84
+ - lib/dry/cli/spinner/dsl.rb
85
+ - lib/dry/cli/stream.rb
86
+ - lib/dry/cli/style.rb
87
+ - lib/dry/cli/style/attribute.rb
88
+ - lib/dry/cli/style/color.rb
89
+ - lib/dry/cli/style/color_level.rb
90
+ - lib/dry/cli/style/formatter.rb
91
+ - lib/dry/cli/style/palette.rb
92
+ - lib/dry/cli/style/text.rb
93
+ - lib/dry/cli/style_mixin.rb
94
+ - lib/dry/cli/ticker.rb
80
95
  - lib/dry/cli/usage.rb
81
96
  - lib/dry/cli/version.rb
82
97
  homepage: https://dry-rb.org/gems/dry-cli
83
98
  licenses:
84
99
  - MIT
85
100
  metadata:
86
- allowed_push_host: https://rubygems.org
87
101
  changelog_uri: https://github.com/dry-rb/dry-cli/blob/main/CHANGELOG.md
88
102
  source_code_uri: https://github.com/dry-rb/dry-cli
89
103
  bug_tracker_uri: https://github.com/dry-rb/dry-cli/issues
@@ -95,7 +109,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
95
109
  requirements:
96
110
  - - ">="
97
111
  - !ruby/object:Gem::Version
98
- version: '3.2'
112
+ version: '3.3'
99
113
  required_rubygems_version: !ruby/object:Gem::Requirement
100
114
  requirements:
101
115
  - - ">="