Module: Elixir::OptionParser

Defined in:
lib/elixir/option_parser.rb

Class Method Summary collapse

Class Method Details

.next(argv, switches = []) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/elixir/option_parser.rb', line 8

def next argv, switches = []
  # TODO: switches
  argv = argv.dup

  option = argv.shift
  return [:error, argv] unless option

  if option.start_with? '-'
    key = option.sub(/\-{,2}/, '').gsub(/\-/, '_').to_sym

    if argv.empty? || argv.first.start_with?('-')
      value = true
    else
      value = argv.shift
    end

    [:ok, key, value, argv]
  else
    [:error, argv.unshift(option)]
  end
end

.parse(argv, switches = []) ⇒ Object



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
# File 'lib/elixir/option_parser.rb', line 30

def parse argv, switches = []
  # TODO: switches
  parsed = {}
  argv = argv.dup
  extras = []
  errors = {}
  
  loop do
    option_tuple = self.next argv

    case option_tuple.first
    when :ok
      _, key, value, argv = option_tuple
  
      parsed[key] = value
    when :error
      _, string = option_tuple
      argv.shift
      extra = string.shift

      extras << extra if extra
    end

    break [parsed, extras, errors] if option_tuple.last.empty?
  end
end

.parse_head(argv, switches = []) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/elixir/option_parser.rb', line 57

def parse_head argv, switches = []
  # TODO: switches
  parsed = {}
  argv = argv.dup
  errors = {}

  loop do
    option_tuple = self.next argv

    case option_tuple.first
    when :ok
      _, key, value, argv = option_tuple

      parsed[key] = value
    when :error
      _, argv = option_tuple

      break [parsed, argv, errors]
    end
  end
end

.split(string) ⇒ Object



79
80
81
# File 'lib/elixir/option_parser.rb', line 79

def split string
  Shellwords.shellsplit string
end

.to_argv(enum) ⇒ Object



83
84
85
86
87
88
89
# File 'lib/elixir/option_parser.rb', line 83

def to_argv enum
  enum.flat_map do |k, v|
    return unless v

    v == true ? "--#{k}" : ["--#{k}", v]
  end.compact
end