Class: Envo::CliParser

Inherits:
Object
  • Object
show all
Defined in:
lib/envo/cli_parser.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ CliParser

Returns a new instance of CliParser.



19
20
21
22
# File 'lib/envo/cli_parser.rb', line 19

def initialize(opts)
  @known_cmds = {}
  @known_opts = opts
end

Class Method Details

.filter_opts(args) ⇒ Object



16
17
18
# File 'lib/envo/cli_parser.rb', line 16

def self.filter_opts(args)
  filter_opts_front(args) + filter_opts_back(args)
end

.filter_opts_back(args) ⇒ Object



11
12
13
14
15
# File 'lib/envo/cli_parser.rb', line 11

def self.filter_opts_back(args)
  back_opts = args.reverse.take_while { |a| opt?(a) }.reverse
  args.pop(back_opts.size)
  back_opts
end

.filter_opts_front(args) ⇒ Object



6
7
8
9
10
# File 'lib/envo/cli_parser.rb', line 6

def self.filter_opts_front(args)
  front_opts = args.take_while { |a| opt?(a) }
  args.shift(front_opts.size)
  front_opts
end

.opt?(opt) ⇒ Boolean

Returns:

  • (Boolean)


3
4
5
# File 'lib/envo/cli_parser.rb', line 3

def self.opt?(opt)
  opt =~ /^-/
end

Instance Method Details

#add_cmd(name, parse_func) ⇒ Object



23
24
25
26
# File 'lib/envo/cli_parser.rb', line 23

def add_cmd(name, parse_func)
  raise Envo::Error "cmd #{name} is already added to parser" if @known_cmds[name]
  @known_cmds[name] = parse_func
end

#parse(argv) ⇒ Object



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
# File 'lib/envo/cli_parser.rb', line 27

def parse(argv)
  result = ParseResult.new
  cmd = nil
  while !argv.empty?
    arg = argv.shift
    if CliParser.opt?(arg)
      result.opts.merge! @known_opts.parse_cli(arg)
    else
      break cmd = arg
    end
  end

  raise Envo::Error.new 'missing command' if !cmd
  raise Envo::Error.new "unknown command '#{cmd}'" if !@known_cmds[cmd]

  parsed_cmd = @known_cmds[cmd].(cmd, argv)

  cmd_opts = {}
  parsed_cmd.opts.each do |opt|
    cmd_opts.merge! @known_opts.parse_cli(opt)
  end
  parsed_cmd.opts = cmd_opts

  result.cmds << parsed_cmd
  result
end