Class: CLI::Kit::Args::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/cli/kit/args/parser.rb,
lib/cli/kit/args/parser/node.rb

Defined Under Namespace

Classes: InvalidOptionError, Node, OptionRequiresAnArgumentError

Constant Summary collapse

Error =
Class.new(Args::Error)

Instance Method Summary collapse

Constructor Details

#initialize(definition) ⇒ Parser

: (Definition definition) -> void



63
64
65
# File 'lib/cli/kit/args/parser.rb', line 63

def initialize(definition)
  @defn = definition
end

Instance Method Details

#parse(tokens) ⇒ Object

: (Array tokens) -> Array



28
29
30
31
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
57
58
59
60
# File 'lib/cli/kit/args/parser.rb', line 28

def parse(tokens)
  nodes = [] #: Array[Node]
  args = tokens #: Array[Tokenizer::Token?]
  args << nil # to make each_cons pass (args.last, nil) on the final round.
  state = :init
  # TODO: test that "--height -- 3" is parsed correctly.
  args.each_cons(2) do |(arg, next_arg)|
    case state
    when :skip
      state = :init
    when :init
      state, val = parse_token(
        arg, #: as !nil
        next_arg,
      )
      nodes << val
    when :unparsed
      unless arg.is_a?(Tokenizer::Token::UnparsedArgument)
        raise(Error, 'bug: non-unparsed argument after unparsed argument')
      end

      unparsed = nodes.last
      unless unparsed.is_a?(Node::Unparsed)
        # :nocov: not actually possible, in theory
        raise(Error, 'bug: parser failed to recognize first unparsed argument')
        # :nocov:
      end

      unparsed.value << arg.value
    end
  end
  nodes
end