Class: ConfigKit::Cli::Command

Inherits:
Object
  • Object
show all
Defined in:
lib/config_kit/cli/command.rb

Direct Known Subclasses

Bootstrap, Deploy, Describe, Get, Init, Rollback

Defined Under Namespace

Classes: CommandFailure

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ Command

Returns a new instance of Command.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/config_kit/cli/command.rb', line 23

def initialize(args)
  if Hash === args
    args.each do |k, v| 
      instance_variable_set "@#{k}", v.to_s if v
    end
  else

    @options = options do |opts|
      opts.on("-h", "Show this help") {  raise CommandFailure, opts.to_s }
    end
    raise CommandFailure, @options.to_s if args.empty?
    @leftover = @options.parse(args)
  end
rescue OptionParser::ParseError => e
  raise CommandFailure.new(e.message, @options)
end

Instance Attribute Details

#leftoverObject (readonly)

Returns the value of attribute leftover.



14
15
16
# File 'lib/config_kit/cli/command.rb', line 14

def leftover
  @leftover
end

Class Method Details

.inherited(subclass) ⇒ Object



41
42
43
# File 'lib/config_kit/cli/command.rb', line 41

def self.inherited(subclass)
  @commands << subclass
end

.runObject



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
# File 'lib/config_kit/cli/command.rb', line 48

def self.run
  @command_names = @commands.map{ |c| c.command}

  extra = []

  options = ARGV.options do |opts|
    script_name = File.basename($0)
    opts.banner = "Usage: #{script_name} [ #{ @command_names.join(" | ")} ] [options]"
    opts.separator "use '#{script_name} <command> -h' to see detailed command options"
    opts
  end
  extra = options.order!
  command = extra.shift

  if command.nil?
    ConfigKit.logger.error "No command provided"
    STDOUT.puts options.to_s
  elsif !@command_names.include?(command)
    ConfigKit.logger.error "Unrecognized command: #{command}"
    ConfigKit.logger.error options
  else
    command_class = @commands.find{ |c| c.command == command}
    command_class.new(extra).run
  end
rescue OptionParser::InvalidOption => e
  raise CommandFailure.new(e.message)
end