Class: Hammer::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/hammer/parser.rb

Overview

Parses ARGV into positional args and an options hash, given a set of ‘Option` definitions.

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Parser

Returns a new instance of Parser.



7
8
9
10
11
12
13
14
15
# File 'lib/hammer/parser.rb', line 7

def initialize(options)
  @options    = options
  @by_switch  = {}
  options.each do |opt|
    @by_switch[opt.switch] = opt
    @by_switch[opt.negation] = opt if opt.boolean?
    opt.aliases.each { |a| @by_switch[a] = opt }
  end
end

Instance Method Details

#parse(argv) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/hammer/parser.rb', line 17

def parse(argv)
  positional = []
  values     = {}
  i = 0
  argv = argv.dup

  while i < argv.length
    token = argv[i]

    if token == '--'
      positional.concat(argv[(i + 1)..])
      break
    end

    if token.start_with?('--') && token.include?('=')
      key, val = token.split('=', 2)
      opt = lookup!(key)
      values[opt.name] = opt.cast(val)
      i += 1
      next
    end

    if @by_switch.key?(token)
      opt = @by_switch[token]
      if opt.boolean?
        values[opt.name] = !token.start_with?('--no-')
        i += 1
      else
        val = argv[i + 1]
        raise Error, "missing value for #{token}" if val.nil?
        values[opt.name] = opt.cast(val)
        i += 2
      end
      next
    end

    if token.start_with?('-') && token.length > 1
      raise Error, "unknown option: #{token}"
    end

    positional << token
    i += 1
  end

  # Fill un-set non-boolean opts from positional args in declaration
  # order. Booleans always need an explicit flag.
  @options.each do |opt|
    break if positional.empty?
    next if opt.boolean? || values.key?(opt.name)
    values[opt.name] = opt.cast(positional.shift)
  end

  @options.each do |opt|
    values[opt.name] = opt.default if !values.key?(opt.name) && !opt.default.nil?
    raise Error, "missing required --#{opt.name}" if opt.required && !values.key?(opt.name)
  end

  [positional, values]
end