Class: Makitzo::CLI

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

Instance Method Summary collapse

Instance Method Details

#run(args) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/makitzo/cli.rb', line 3

def run(args)
  
  # TODO: locate this automatically or allow it from a configuration file
  worldfile = 'Worldfile'
  root_directory = File.dirname(worldfile)
  
  app = Application.new
  app.root_directory = root_directory
  
  query = World::Query.new
  config = app.config
  
  trace = false
  opts = OptionParser.new do |opts|
    opts.banner = "Usage: makitzo [options] command"
    
    opts.on("--trace", "Show backtrace on error") do
      trace = true
    end
    
    opts.on("--role [ROLE]", "Restrict command to role (may appear multiple times)") do |r|
      query.roles << r
    end
    
    opts.on("--host [HOST]", "Restrict command to host (may appear multiple times)") do |h|
      query.hosts << h
    end
    
    opts.on("-c", "--concurrency [NUM]", "Maximum number of connections to open in parallel") do |c|
      config.concurrency = c.to_i
    end
    
    opts.on_tail("-h", "--help", "Show this message") do
      puts opts
      exit
    end
  end
  
  opts.parse!(args)
  
  app.query = query
  
  config.instance_eval(File.read(worldfile))
  
  if $stdin.isatty
    command = ARGV
  else
    command = ['stream', $stdin]
  end
  
  if command.empty?
    $stderr.puts "Error: no command specified"
    $stderr.puts "  Valid commands: #{app.valid_commands.join(', ')}"
    exit 1
  end
  
  result = app.invoke(*command)

rescue => e
  $stderr.puts "#{e.message} (#{e.class})"
  if trace
    $stderr.puts e.backtrace.join("\n")
  else
    $stderr.puts "(run with --trace for detailed error information)"
  end
  exit 1
end