Class: ShellOpts::Interpreter

Inherits:
Object
  • Object
show all
Defined in:
lib/shellopts/interpreter.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(grammar, argv, float: true, exception: false) ⇒ Interpreter

Returns a new instance of Interpreter.



7
8
9
10
11
12
# File 'lib/shellopts/interpreter.rb', line 7

def initialize(grammar, argv, float: true, exception: false)
  constrain grammar, Grammar::Program
  constrain argv, [String]
  @grammar, @argv = grammar, argv.dup
  @float, @exception = float, exception
end

Instance Attribute Details

#argsObject (readonly)

Returns the value of attribute args.



5
6
7
# File 'lib/shellopts/interpreter.rb', line 5

def args
  @args
end

#exprObject (readonly)

Returns the value of attribute expr.



4
5
6
# File 'lib/shellopts/interpreter.rb', line 4

def expr
  @expr
end

Class Method Details

.interpret(grammar, argv, **opts) ⇒ Object



38
39
40
# File 'lib/shellopts/interpreter.rb', line 38

def self.interpret(grammar, argv, **opts)
  self.new(grammar, argv, **opts).interpret
end

Instance Method Details

#interpretObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/shellopts/interpreter.rb', line 14

def interpret
  @expr = command = Program.new(@grammar)
  @seen = {} # Set of seen options by UID (using UID is needed when float is true)
  @args = []

  while arg = @argv.shift
    if arg == "--"
      break
    elsif arg.start_with?("-")
      interpret_option(command, arg)
    elsif @args.empty? && subcommand_grammar = command.__grammar__[:"#{arg}!"]
      command = Command.add_command(command, Command.new(subcommand_grammar))
    else
      if @float
        @args << arg # This also signals that no more commands are accepted
      else
        @argv.unshift arg
        break
      end
    end
  end
  [@expr, Args.new(@args + @argv, exception: @exception)]
end