Class: GLI::GLIOptionParser

Inherits:
Object
  • Object
show all
Defined in:
lib/gli/gli_option_parser.rb

Overview

Parses the command-line options using an actual OptionParser

Instance Method Summary collapse

Constructor Details

#initialize(commands, flags, switches, accepts, default_command = nil) ⇒ GLIOptionParser

Returns a new instance of GLIOptionParser.



4
5
6
7
8
9
10
# File 'lib/gli/gli_option_parser.rb', line 4

def initialize(commands,flags,switches,accepts,default_command = nil)
  @commands = commands
  @flags = flags
  @switches = switches
  @accepts = accepts
  @default_command = default_command
end

Instance Method Details

#parse_options(args) ⇒ Object

Given the command-line argument array, returns and array of size 4:

0

global options

1

command, as a Command

2

command-specific options

3

unparsed arguments



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
# File 'lib/gli/gli_option_parser.rb', line 18

def parse_options(args) # :nodoc:
  args_clone = args.clone
  global_options = {}
  command = nil
  command_options = {}
  remaining_args = nil

  global_options,command_name,args = parse_global_options(OptionParserFactory.new(@flags,@switches,@accepts), args)
  @flags.each do |name,flag|
    global_options[name] = flag.default_value unless global_options[name]
  end
  @switches.each do |name,switch|
    global_options[name] = switch.default_value if global_options[name].nil?
  end

  command_name ||= @default_command || :help
  command = find_command(command_name)
  if Array(command).empty?
    raise UnknownCommand.new("Unknown command '#{command_name}'")
  elsif command.kind_of? Array
    raise UnknownCommand.new("Ambiguous command '#{command_name}'. It matches #{command.sort.join(',')}")
  end

  command_options,args = parse_command_options(OptionParserFactory.new(command.flags,command.switches,@accepts),
                                               command,
                                               args)

  command.flags.each do |name,flag|
    command_options[name] = flag.default_value unless command_options[name]
  end
  command.switches.each do |name,switch|
    command_options[name] = switch.default_value if command_options[name].nil?
  end

  [global_options,command,command_options,args]
end