Class: CommandLineUtils::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/command-line-utils/cli.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCLI

Returns a new instance of CLI.



6
7
8
9
10
# File 'lib/command-line-utils/cli.rb', line 6

def initialize
  @options = Hash.new
  @options[:debug] = false
  @commands = Commands.new
end

Class Method Details

.run(argv) ⇒ Object



60
61
62
# File 'lib/command-line-utils/cli.rb', line 60

def run(argv)
  self.new.execute(argv)
end

Instance Method Details

#dispatch(cmd, cmd_argv) ⇒ Object



12
13
14
# File 'lib/command-line-utils/cli.rb', line 12

def dispatch(cmd,cmd_argv)
  @commands.send(cmd.sub(/:/,"_"))
end

#execute(argv) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/command-line-utils/cli.rb', line 24

def execute(argv)
  begin
    @opt = options
    cmd_argv = @opt.order!(argv)
    cmd = cmd_argv.shift
    raise "command is not specified" unless cmd
    @commands.options = @options
    @commands.command_options = cmd_argv
    dispatch(cmd,cmd_argv)
  rescue UsageException => e
    usage
    raise e if @options[:debug]
  rescue => e
    puts "Message: #{e}"
    # puts ""
    # usage unless @options[:debug]
    raise e if @options[:debug]
  end
end

#optionsObject



16
17
18
19
20
21
22
# File 'lib/command-line-utils/cli.rb', line 16

def options
  OptionParser.new {|opt|
    opt.on('--version', 'show version') { version;exit }
    opt.on('--help', 'show this message') { usage;exit }
    opt.on('--debug', 'debug mode') { @options[:debug] = true }
  }
end

#usage(e = nil) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/command-line-utils/cli.rb', line 44

def usage(e=nil)
  puts @opt
  puts "\nCommands:\n"
  @commands.commands.each { |c|
    puts "    " + c
  }
end

#versionObject



52
53
54
55
56
57
# File 'lib/command-line-utils/cli.rb', line 52

def version
  File.open(File.join(File.dirname(__FILE__) ,
                      "..","..","VERSION"),"r") { |file|
    puts file.gets
  }
end