Module: Ukiryu::FriendlyCLI

Included in:
Cli
Defined in:
lib/ukiryu/thor_ext.rb

Overview

Configures Thor to behave more like a typical modern CLI.

Features:

  • Passing -h or –help to a command will show help for that command

  • Unrecognized options will be treated as errors (not silently ignored)

  • Error messages are printed to stderr in red, without stack trace

  • Full stack traces can be enabled with VERBOSE environment variable

  • Errors cause Thor to exit with non-zero status

  • Missing required arguments show help instead of errors

Start your CLI with:

Cli.start

In tests, prevent Kernel.exit from being called:

Cli.start(args, exit_on_failure: false)

Examples:

Extend your CLI with this module

class Cli < Thor
  extend FriendlyCLI
end

Constant Summary collapse

MISSING_ARGS_PATTERN =

Regex patterns for error message parsing

/"(\w+) (\w+)"/.freeze
HELP_OPTIONS =
%w[-h --help].freeze
TRACE_ENV_VARS =

Environment variables for trace mode

%w[UKIRYU_TRACE VERBOSE].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object



32
33
34
35
# File 'lib/ukiryu/thor_ext.rb', line 32

def self.extended(base)
  super
  base.check_unknown_options!
end

Instance Method Details

#handle_argument_error(command, error, _args, _arity) ⇒ Object

Override Thor’s handle_argument_error to show help for missing arguments

Parameters:

  • command (Thor::Command)

    the Thor command object

  • error (Exception)

    the error that was raised

  • _args (Array)

    the arguments that were passed (unused)

  • _arity (Integer)

    the arity of the command (unused)



59
60
61
62
63
64
65
# File 'lib/ukiryu/thor_ext.rb', line 59

def handle_argument_error(command, error, _args, _arity)
  return show_help_for_command(error) if missing_arguments_error?(error)
  return handle_argument_count_error(command, error) if wrong_argument_count_error?(error)

  # Otherwise, handle as normal error
  handle_exception_on_start(error, {})
end

#start(given_args = ARGV, config = {}) ⇒ Object

Override Thor’s start method to provide better CLI behavior

Parameters:

  • given_args (Array<String>) (defaults to: ARGV)

    the command-line arguments

  • config (Hash) (defaults to: {})

    configuration options

Options Hash (config):

  • :shell (Thor::Shell)

    the Thor shell instance

  • :exit_on_failure (Boolean)

    whether to exit on errors (default: true)



43
44
45
46
47
48
49
50
51
# File 'lib/ukiryu/thor_ext.rb', line 43

def start(given_args = ARGV, config = {})
  config[:shell] ||= Thor::Base.shell.new

  handle_help_switches(given_args) do |args|
    dispatch(nil, args, nil, config)
  end
rescue StandardError, Exception => e
  handle_exception_on_start(e, config)
end