Module: ArgsParser::Parser

Defined in:
lib/argsparser/parser.rb

Class Method Summary collapse

Class Method Details

.parse(args, expected_opts, expected_switches) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
76
77
78
# File 'lib/argsparser/parser.rb', line 3

def self.parse(args, expected_opts, expected_switches)
  @@options = {}
  @@switches = {}
  @@data = []

  read = :new_arg
  rmode = nil
  args.each do |arg|
    if read == :new_arg
      if rmode == :data
        @@data << arg
      elsif arg == "--"
        rmode = :data
      elsif arg.start_with?("--")
        b = arg.sub("--", "").split("=")
        a = b[0].to_sym

        if expected_opts.keys.include?(a)
          if expected_opts[a][:has_argument]
            if b[1]
              @@options[a] = {arg: b[1]}
            else
              @@options[a] = {arg: :yes}
              read = {arg_for_opt: a}
            end
          else
            @@options[a] = {arg: :none}
          end
        end
      elsif arg.start_with?("-")
        b = arg.sub("-", "").split("=")
        a = b[0].split("")

        rmode = :new_switch
        c = 0
        a.each do |x|
          x = x.to_sym
          c = c + 1

          if rmode == :new_switch
            if expected_switches.keys.include?(x)
              if expected_switches[x][:has_argument]
                if b[1] && a.length == 1
                  @@switches[x] = {arg: b[1]}
                else
                  rmode = {arg_for_switch: x}
                  @@switches[x] = {arg: :yes}
                end
              else
                @@switches[x] = {arg: :none}
              end
            end
          elsif rmode[:arg_for_switch]
            @@switches[rmode[:arg_for_switch]][:arg] = arg[c..arg.length-1]
            rmode = :new_switch
            break
          end
        end

        if rmode.class == Hash
          read = rmode
        end
      else
        @@data << arg
      end
    elsif read[:arg_for_opt]
      @@options[read[:arg_for_opt]][:arg] = arg
      read = :new_arg
    elsif read[:arg_for_switch]
      @@switches[read[:arg_for_switch]][:arg] = arg
      read = :new_arg
    end
  end

  return [@@options, @@switches, @@data]
end