Class: Toys::StandardMiddleware::HandleUsageErrors

Inherits:
Object
  • Object
show all
Includes:
Middleware
Defined in:
lib/toys/standard_middleware/handle_usage_errors.rb

Overview

This middleware handles the case of a usage error. If a usage error, such as an unrecognized flag or an unfulfilled required argument, is detected, this middleware intercepts execution and displays the error along with the short help string, and terminates execution with an error code.

Instance Method Summary collapse

Methods included from Middleware

#config

Constructor Details

#initialize(exit_code: -1,, stream: $stderr, styled_output: nil) ⇒ HandleUsageErrors

Create a HandleUsageErrors middleware.

Parameters:

  • exit_code (Intgeer) (defaults to: -1,)

    The exit code to return if a usage error occurs. Default is -1.

  • stream (IO) (defaults to: $stderr)

    Output stream to write to. Default is stderr.

  • styled_output (Boolean, nil) (defaults to: nil)

    Cause the tool to display help text with ansi styles. If nil, display styles if the output stream is a tty. Default is nil.



53
54
55
56
# File 'lib/toys/standard_middleware/handle_usage_errors.rb', line 53

def initialize(exit_code: -1, stream: $stderr, styled_output: nil)
  @exit_code = exit_code
  @terminal = Utils::Terminal.new(output: stream, styled: styled_output)
end

Instance Method Details

#run(tool) ⇒ Object

Intercept and handle usage errors during execution.



61
62
63
64
65
66
67
68
69
70
71
# File 'lib/toys/standard_middleware/handle_usage_errors.rb', line 61

def run(tool)
  if tool[Tool::Keys::USAGE_ERROR]
    help_text = Utils::HelpText.from_tool(tool)
    @terminal.puts(tool[Tool::Keys::USAGE_ERROR], :bright_red, :bold)
    @terminal.puts("")
    @terminal.puts(help_text.usage_string(wrap_width: @terminal.width))
    Tool.exit(@exit_code)
  else
    yield
  end
end