Module: Hanami::CLI::Parser Private

Defined in:
lib/hanami/cli/parser.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Parse command line arguments and options

Since:

  • 0.1.0

Defined Under Namespace

Classes: Result

Class Method Summary collapse

Class Method Details

.call(command, arguments, names) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

rubocop:disable Metrics/AbcSize rubocop:disable Metrics/MethodLength

Since:

  • 0.1.0


16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/hanami/cli/parser.rb', line 16

def self.call(command, arguments, names)
  parsed_options = {}

  OptionParser.new do |opts|
    command.options.each do |option|
      opts.on(*option.parser_options) do |value|
        parsed_options[option.name.to_sym] = value
      end
    end

    opts.on_tail("-h", "--help") do
      return Result.help
    end
  end.parse!(arguments.dup)

  parsed_options = command.default_params.merge(parsed_options)
  parse_required_params(command, arguments, names, parsed_options)
rescue ::OptionParser::ParseError
  return Result.failure
end

.full_command_name(names) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Since:

  • 0.1.0


41
42
43
# File 'lib/hanami/cli/parser.rb', line 41

def self.full_command_name(names)
  ProgramName.call(names)
end

.parse_required_params(command, arguments, names, parsed_options) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

rubocop:disable Metrics/AbcSize rubocop:disable Metrics/MethodLength

Since:

  • 0.1.0


50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/hanami/cli/parser.rb', line 50

def self.parse_required_params(command, arguments, names, parsed_options)
  parse_params = Hash[command.arguments.map(&:name).zip(arguments)]
  parse_required_params = Hash[command.required_arguments.map(&:name).zip(arguments)]
  all_required_params_satisfied = command.required_arguments.all? { |param| !parse_required_params[param.name].nil? }

  unless all_required_params_satisfied
    parse_required_params_values = parse_required_params.values.compact

    usage = "\nUsage: \"#{full_command_name(names)} #{command.required_arguments.map(&:description_name).join(' ')}\""

    if parse_required_params_values.empty? # rubocop:disable Style/GuardClause
      return Result.failure("ERROR: \"#{full_command_name(names)}\" was called with no arguments#{usage}")
    else
      return Result.failure("ERROR: \"#{full_command_name(names)}\" was called with arguments #{parse_required_params_values}#{usage}")
    end
  end

  Result.success(parse_params.merge(parsed_options))
end