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

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
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

Methods included from T::Sig

sig

Constructor Details

#initialize(definition) ⇒ Parser

Returns a new instance of Parser.



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

def initialize(definition)
  @defn = definition
end

Instance Method Details

#parse(tokens) ⇒ Object



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
61
# File 'lib/cli/kit/args/parser.rb', line 32

def parse(tokens)
  nodes = T.let([], T::Array[Node])
  args = T.let(tokens, T::Array[T.nilable(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(T.must(arg), 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