Module: CLAide::ARGV::Parser

Defined in:
lib/claide/argv.rb

Class Method Summary collapse

Class Method Details

.argument_type(argument) ⇒ Symbol

Returns the type of an argument. The types can be either: :arg, :flag, :option.

Parameters:

  • argument (String)

    The argument to check.

Returns:

  • (Symbol)

    Returns the type of an argument. The types can be either: :arg, :flag, :option.



278
279
280
281
282
283
284
285
286
287
288
# File 'lib/claide/argv.rb', line 278

def self.argument_type(argument)
  if argument.start_with?('--')
    if argument.include?('=')
      :option
    else
      :flag
    end
  else
    :arg
  end
end

.parse(argv) ⇒ Array<Array<Symbol, String, Array>>

Returns A list of tuples for each parameter, where the first entry is the type and the second entry the actual parsed parameter.

Examples:


list = parse(['tea', '--no-milk', '--sweetener=honey'])
list # => [[:arg, "tea"],
           [:flag, ["milk", false]],
           [:option, ["sweetener", "honey"]]]

Returns:

  • (Array<Array<Symbol, String, Array>>)

    A list of tuples for each parameter, where the first entry is the type and the second entry the actual parsed parameter.



259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/claide/argv.rb', line 259

def self.parse(argv)
  entries = []
  copy = argv.map(&:to_s)
  double_dash = false
  while argument = copy.shift
    next if !double_dash && double_dash = (argument == '--')
    type = double_dash ? :arg : argument_type(argument)
    parsed_argument = parse_argument(type, argument)
    entries << [type, parsed_argument]
  end
  entries
end

.parse_argument(type, argument) ⇒ String, Array<String, String>

Returns the argument itself for normal arguments (like commands) and a tuple with the key and the value for options and flags.

Parameters:

  • type (Symbol)

    The type of the argument.

  • argument (String)

    The argument to check.

Returns:

  • (String, Array<String, String>)

    Returns the argument itself for normal arguments (like commands) and a tuple with the key and the value for options and flags.



300
301
302
303
304
305
306
307
308
309
# File 'lib/claide/argv.rb', line 300

def self.parse_argument(type, argument)
  case type
  when :arg
    return argument
  when :flag
    return parse_flag(argument)
  when :option
    return argument[2..-1].split('=', 2)
  end
end

.parse_flag(argument) ⇒ String, Array<String, String>

Returns the parameter describing a flag arguments.

Parameters:

  • argument (String)

    The flag argument to check.

Returns:



317
318
319
320
321
322
323
324
325
326
# File 'lib/claide/argv.rb', line 317

def self.parse_flag(argument)
  if argument.start_with?('--no-')
    key = argument[5..-1]
    value = false
  else
    key = argument[2..-1]
    value = true
  end
  [key, value]
end