From 8d8c51db697b8202410f3ff56f1d495101550539 Mon Sep 17 00:00:00 2001 From: Aaron Allen Date: Thu, 24 Jul 2025 16:56:01 -0500 Subject: [PATCH] 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. --- lib/dry/cli.rb | 7 +++++++ lib/dry/cli/command.rb | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/lib/dry/cli.rb b/lib/dry/cli.rb index 5f93860..458fdf6 100644 --- a/lib/dry/cli.rb +++ b/lib/dry/cli.rb @@ -97,6 +97,10 @@ def call(arguments: ARGV, out: $stdout, err: $stderr) # @api private def perform_command(arguments) command, args = parse(kommand, arguments, []) + + command.instance_variable_set(:@stderr, err) + command.instance_variable_set(:@stdout, out) + command.call(**args) end @@ -113,6 +117,9 @@ def perform_registry(arguments) command, args = parse(result.command, result.arguments, result.names) + command.instance_variable_set(:@stderr, err) + command.instance_variable_set(:@stdout, out) + result.before_callbacks.run(command, args) command.call(**args) result.after_callbacks.run(command, args) diff --git a/lib/dry/cli/command.rb b/lib/dry/cli/command.rb index 3e6a601..0e1049b 100644 --- a/lib/dry/cli/command.rb +++ b/lib/dry/cli/command.rb @@ -379,6 +379,39 @@ def self.superclass_options optional_arguments subcommands ] => "self.class" + + protected + + # The error output used to print error messaging + # + # @example + # class MyCommand + # def call + # stdout.puts "Hello World!" + # exit(0) + # rescue StandardError => e + # stderr.puts "Uh oh: #{e.message}" + # exit(1) + # end + # end + # + # @since unreleased + # @return [IO] + attr_reader :stderr + + # The standard output object used to print messaging + # + # @example + # class MyCommand + # def call + # stdout.puts "Hello World!" + # exit(0) + # end + # end + # + # @since unreleased + # @return [IO] + attr_reader :stdout end end end