Class: TTY::Option::Parser::Options

Inherits:
Object
  • Object
show all
Includes:
ParamTypes
Defined in:
lib/tty/option/parser/options.rb

Constant Summary collapse

LONG_OPTION_RE =
/^(--[^=]+)(\s+|=)?(.*)?$/.freeze
SHORT_OPTION_RE =
/^(-.)(.*)$/.freeze

Constants included from ParamTypes

ParamTypes::ARGUMENT_PARAMETER, ParamTypes::ENV_VAR_PARAMETER, ParamTypes::KEYWORD_PARAMETER, ParamTypes::OPTION_PARAMETER

Instance Method Summary collapse

Methods included from ParamTypes

#argument?, #env_var?, #keyword?, #option?

Constructor Details

#initialize(options, check_invalid_params: true, raise_on_parse_error: false) ⇒ Options

Create a command line env variables parser

Parameters:

  • options (Array<Option>)

    the list of options

  • config (Hash)

    the configuration settings



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/tty/option/parser/options.rb', line 27

def initialize(options, check_invalid_params: true,
               raise_on_parse_error: false)
  @options = options
  @check_invalid_params = check_invalid_params
  @error_aggregator =
    ErrorAggregator.new(raise_on_parse_error: raise_on_parse_error)
  @required_check = RequiredCheck.new(@error_aggregator)
  @arity_check = ArityCheck.new(@error_aggregator)
  @pipeline = Pipeline.new(@error_aggregator)
  @parsed = {}
  @remaining = []
  @shorts = {}
  @longs = {}
  @arities = Hash.new(0)

  setup_opts
end

Instance Method Details

#parse(argv) ⇒ Object

Read option(s) from command line

Parameters:

  • argv (Array<String>)


74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/tty/option/parser/options.rb', line 74

def parse(argv)
  @argv = argv.dup

  loop do
    opt, value = next_option
    if !opt.nil?
      @required_check.delete(opt)
      @arities[opt.key] += 1

      if block_given?
        yield(opt, value)
      else
        assign_option(opt, value)
      end
    end
    break if @argv.empty?
  end

  @arity_check.(@arities)
  @required_check.()

  [@parsed, @remaining, @error_aggregator.errors]
end

#setup_optsObject

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.

Configure list of returned options



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/tty/option/parser/options.rb', line 48

def setup_opts
  @options.each do |opt|
    @shorts[opt.short_name] = opt
    @longs[opt.long_name] = opt
    @arity_check << opt if opt.multiple?

    if opt.default?
      case opt.default
      when Proc
        assign_option(opt, opt.default.())
      else
        assign_option(opt, opt.default)
      end
    elsif !(opt.argument_optional? || opt.argument_required?)
      assign_option(opt, false)
    elsif opt.required?
      @required_check << opt
    end
  end
end