Module: Spud::Args

Defined in:
lib/args.rb

Class Method Summary collapse

Class Method Details

.default_optionsObject



10
11
12
13
14
15
16
17
# File 'lib/args.rb', line 10

def default_options
  {
    help: false,
    version: false,
    watches: [],
    debug: false,
  }
end

.parse_args(args) ⇒ Object



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
# File 'lib/args.rb', line 31

def parse_args(args)
  options = default_options.dup
  rule_name = nil
  index = 0
  while index < args.length
    arg = args[index]

    if arg[0] != '-'
      rule_name = arg
      index += 1
      break
    end

    options, index = parse_option(options, index, args)
  end

  positional = []
  keyword = {}
  while index < args.length
    arg = args[index]

    if arg[0] == '-'
      value = args[index + 1]
      raise Error, "missing value for arg #{arg}" unless value

      keyword[arg.sub(/^-+/, '').to_sym] = value
      index += 2
    else
      positional << arg
      index += 1
    end
  end

  {
    options: options,
    rule: rule_name,
    positional: positional,
    keyword: keyword
  }
end

.parse_args!Object



6
7
8
# File 'lib/args.rb', line 6

def parse_args!
  parse_args(ARGV)
end

.parse_option(options, index, args) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/args.rb', line 19

def parse_option(options, index, args)
  arg = args[index]

  case arg
  when '-h', '--help' then [options.merge(help: true), index + 1]
  when '-v', '--version' then [options.merge(version: true), index + 1]
  #when '-w', '--watch' then [options.merge(watches: options[:watches] + [args[index + 1]]), index + 2]
  when '--debug' then [options.merge(debug: true), index + 1]
  else raise Error, "invalid option '#{arg}'"
  end
end