Class: Mercenary::Program

Inherits:
Command
  • Object
show all
Defined in:
lib/mercenary/program.rb

Instance Attribute Summary collapse

Attributes inherited from Command

#actions, #aliases, #commands, #description, #map, #name, #options, #parent, #syntax, #trace

Instance Method Summary collapse

Methods inherited from Command

#action, #add_default_options, #alias, #command, #default_command, #execute, #full_name, #has_command?, #ident, #identity, #logger, #names_and_aliases, #option, #process_options, #summarize, #to_s, #version

Constructor Details

#initialize(name) ⇒ Program

Public: Creates a new Program

name - the name of the program

Returns nothing



13
14
15
16
# File 'lib/mercenary/program.rb', line 13

def initialize(name)
  @config = {}
  super(name)
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



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

def config
  @config
end

#optparseObject (readonly)

Returns the value of attribute optparse.



5
6
7
# File 'lib/mercenary/program.rb', line 5

def optparse
  @optparse
end

Instance Method Details

#go(argv) ⇒ Object

Public: Run the program

argv - an array of string args (usually ARGV)

Returns nothing



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
54
55
56
57
58
59
60
61
62
63
# File 'lib/mercenary/program.rb', line 23

def go(argv)
  if argv.empty?
    default_command.execute
    abort
  end

  logger.debug("Using args passed in: #{argv.inspect}")

  cmd = nil

  @optparse = OptionParser.new do |opts|
    cmd = super(argv, opts, @config)
  end

  if cmd.actions.compact.empty?
    logger.error 'Invalid command.'
    abort
  end

  begin
    @optparse.parse!(argv)
  rescue OptionParser::InvalidOption => e
    logger.error "Whoops, we can't understand your command."
    logger.error e.message.to_s
    logger.error "Run your command again with the --help switch to see available options."
    abort
  end

  logger.debug("Parsed config: #{@config.inspect}")

  begin
    cmd.execute(argv, @config)
  rescue => e
    if cmd.trace
      raise e
    else
      logger.error e.message
      abort
    end
  end
end