Skip to content

Commit 914acf9

Browse files
committed
Expose stderr and stdout for commands
Introduce `@stderr` and `@stdout` instance variables to make error and output streams accessible within commands. This enables more flexible error handling and message output customization.
1 parent 64d8b19 commit 914acf9

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

lib/dry/cli.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,10 @@ def call(arguments: ARGV, out: $stdout, err: $stderr)
9797
# @api private
9898
def perform_command(arguments)
9999
command, args = parse(kommand, arguments, [])
100+
101+
command.instance_variable_set(:@stderr, err)
102+
command.instance_variable_set(:@stdout, out)
103+
100104
command.call(**args)
101105
end
102106

@@ -113,6 +117,9 @@ def perform_registry(arguments)
113117

114118
command, args = parse(result.command, result.arguments, result.names)
115119

120+
command.instance_variable_set(:@stderr, err)
121+
command.instance_variable_set(:@stdout, out)
122+
116123
result.before_callbacks.run(command, args)
117124
command.call(**args)
118125
result.after_callbacks.run(command, args)

lib/dry/cli/command.rb

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,39 @@ def self.superclass_options
379379
optional_arguments
380380
subcommands
381381
] => "self.class"
382+
383+
protected
384+
385+
# The error output used to print error messaging
386+
#
387+
# @example
388+
# class MyCommand
389+
# def call
390+
# out.puts "Hello World!"
391+
# exit(0)
392+
# rescue StandardError => e
393+
# err.puts "Uh oh: #{e.message}"
394+
# exit(1)
395+
# end
396+
# end
397+
#
398+
# @since unreleased
399+
# @return [IO]
400+
attr_reader :stderr
401+
402+
# The standard output object used to print messaging
403+
#
404+
# @example
405+
# class MyCommand
406+
# def call
407+
# out.puts "Hello World!"
408+
# exit(0)
409+
# end
410+
# end
411+
#
412+
# @since unreleased
413+
# @return [IO]
414+
attr_reader :stdout
382415
end
383416
end
384417
end

0 commit comments

Comments
 (0)