Class: Thor::Options

Inherits:
Arguments show all
Defined in:
lib/thor/parser/options.rb

Overview

:nodoc: # rubocop:disable ClassLength

Constant Summary collapse

LONG_RE =
/^(--\w+(?:-\w+)*)$/
SHORT_RE =
/^(-[a-z])$/i
EQ_RE =
/^(--\w+(?:-\w+)*|-[a-z])=(.*)$/i
SHORT_SQ_RE =

Allow either -x -v or -xv style for single char args

/^-([a-z]{2,})$/i
SHORT_NUM =
/^(-[a-z])#{NUMERIC}$/i
OPTS_END =
"--".freeze

Constants inherited from Arguments

Arguments::NUMERIC

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Arguments

parse, split

Constructor Details

#initialize(hash_options = {}, defaults = {}, stop_on_unknown = false, disable_required_check = false) ⇒ Options

Takes a hash of Thor::Option and a hash with defaults.

If stop_on_unknown is true, #parse will stop as soon as it encounters an unknown option or a regular argument.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/thor/parser/options.rb', line 32

def initialize(hash_options = {}, defaults = {}, stop_on_unknown = false, disable_required_check = false)
  @stop_on_unknown = stop_on_unknown
  @disable_required_check = disable_required_check
  options = hash_options.values
  super(options)

  # Add defaults
  defaults.each do |key, value|
    @assigns[key.to_s] = value
    @non_assigned_required.delete(hash_options[key])
  end

  @shorts = {}
  @switches = {}
  @extra = []

  options.each do |option|
    @switches[option.switch_name] = option

    option.aliases.each do |short|
      name = short.to_s.sub(/^(?!\-)/, "-")
      @shorts[name] ||= option.switch_name
    end
  end
end

Class Method Details

.to_switches(options) ⇒ Object

Receives a hash and makes it switches.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/thor/parser/options.rb', line 11

def self.to_switches(options)
  options.map do |key, value|
    case value
    when true
      "--#{key}"
    when Array
      "--#{key} #{value.map(&:inspect).join(' ')}"
    when Hash
      "--#{key} #{value.map { |k, v| "#{k}:#{v}" }.join(' ')}"
    when nil, false
      nil
    else
      "--#{key} #{value.inspect}"
    end
  end.compact.join(" ")
end

Instance Method Details

#check_unknown!Object



122
123
124
125
126
# File 'lib/thor/parser/options.rb', line 122

def check_unknown!
  # an unknown option starts with - or -- and has no more --'s afterward.
  unknown = @extra.select { |str| str =~ /^--?(?:(?!--).)*$/ }
  raise UnknownArgumentError, "Unknown switches '#{unknown.join(', ')}'" unless unknown.empty?
end

#current_is_switch?Boolean (protected)

Check if the current value in peek is a registered switch.

Two booleans are returned. The first is true if the current value starts with a hyphen; the second is true if it is a registered switch.

Returns:

  • (Boolean)


134
135
136
137
138
139
140
141
142
143
# File 'lib/thor/parser/options.rb', line 134

def current_is_switch?
  case peek
  when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM
    [true, switch?($1)]
  when SHORT_SQ_RE
    [true, $1.split("").any? { |f| switch?("-#{f}") }]
  else
    [false, false]
  end
end

#current_is_switch_formatted?Boolean (protected)

Returns:

  • (Boolean)


145
146
147
148
149
150
151
152
# File 'lib/thor/parser/options.rb', line 145

def current_is_switch_formatted?
  case peek
  when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM, SHORT_SQ_RE
    true
  else
    false
  end
end

#current_is_value?Boolean (protected)

Returns:

  • (Boolean)


154
155
156
# File 'lib/thor/parser/options.rb', line 154

def current_is_value?
  peek && (!parsing_options? || super)
end

#normalize_switch(arg) ⇒ Object (protected)

Check if the given argument is actually a shortcut.



172
173
174
# File 'lib/thor/parser/options.rb', line 172

def normalize_switch(arg)
  (@shorts[arg] || arg).tr("_", "-")
end

#parse(args) ⇒ Object

rubocop:disable MethodLength



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/thor/parser/options.rb', line 75

def parse(args) # rubocop:disable MethodLength
  @pile = args.dup
  @parsing_options = true

  while peek
    if parsing_options?
      match, is_switch = current_is_switch?
      shifted = shift

      if is_switch
        case shifted
        when SHORT_SQ_RE
          unshift($1.split("").map { |f| "-#{f}" })
          next
        when EQ_RE, SHORT_NUM
          unshift($2)
          switch = $1
        when LONG_RE, SHORT_RE
          switch = $1
        end

        switch = normalize_switch(switch)
        option = switch_option(switch)
        @assigns[option.human_name] = parse_peek(switch, option)
      elsif @stop_on_unknown
        @parsing_options = false
        @extra << shifted
        @extra << shift while peek
        break
      elsif match
        @extra << shifted
        @extra << shift while peek && peek !~ /^-/
      else
        @extra << shifted
      end
    else
      @extra << shift
    end
  end

  check_requirement! unless @disable_required_check

  assigns = Thor::CoreExt::HashWithIndifferentAccess.new(@assigns)
  assigns.freeze
  assigns
end

#parse_boolean(switch) ⇒ Object (protected)

Parse boolean values which can be given as –foo=true, –foo or –no-foo.



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/thor/parser/options.rb', line 183

def parse_boolean(switch)
  if current_is_value?
    if ["true", "TRUE", "t", "T", true].include?(peek)
      shift
      true
    elsif ["false", "FALSE", "f", "F", false].include?(peek)
      shift
      false
    else
      !no_or_skip?(switch)
    end
  else
    @switches.key?(switch) || !no_or_skip?(switch)
  end
end

#parse_peek(switch, option) ⇒ Object (protected)

Parse the value at the peek analyzing if it requires an input or not.



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/thor/parser/options.rb', line 201

def parse_peek(switch, option)
  if parsing_options? && (current_is_switch_formatted? || last?)
    if option.boolean?
      # No problem for boolean types
    elsif no_or_skip?(switch)
      return nil # User set value to nil
    elsif option.string? && !option.required?
      # Return the default if there is one, else the human name
      return option.lazy_default || option.default || option.human_name
    elsif option.lazy_default
      return option.lazy_default
    else
      raise MalformattedArgumentError, "No value provided for option '#{switch}'"
    end
  end

  @non_assigned_required.delete(option)
  send(:"parse_#{option.type}", switch)
end

#parsing_options?Boolean (protected)

Returns:

  • (Boolean)


176
177
178
179
# File 'lib/thor/parser/options.rb', line 176

def parsing_options?
  peek
  @parsing_options
end

#peekObject



62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/thor/parser/options.rb', line 62

def peek
  return super unless @parsing_options

  result = super
  if result == OPTS_END
    shift
    @parsing_options = false
    super
  else
    result
  end
end

#remainingObject



58
59
60
# File 'lib/thor/parser/options.rb', line 58

def remaining
  @extra
end

#switch?(arg) ⇒ Boolean (protected)

Returns:

  • (Boolean)


158
159
160
# File 'lib/thor/parser/options.rb', line 158

def switch?(arg)
  switch_option(normalize_switch(arg))
end

#switch_option(arg) ⇒ Object (protected)



162
163
164
165
166
167
168
# File 'lib/thor/parser/options.rb', line 162

def switch_option(arg)
  if match = no_or_skip?(arg) # rubocop:disable AssignmentInCondition
    @switches[arg] || @switches["--#{match}"]
  else
    @switches[arg]
  end
end