Class: Triglav::Agent::Base::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/triglav/agent/base/cli.rb

Overview

A base class for cli option parser

You usually do not need to customize this class, but if you want to implement your original, configure

Triglav::Agent::Configuration.cli_class =

Instance Method Summary collapse

Instance Method Details

#default_optsObject



25
26
27
28
29
30
31
# File 'lib/triglav/agent/base/cli.rb', line 25

def default_opts
  {
    config: 'config.yml',
    dotenv: false,
    debug: false,
  }
end

#option_parser(opts = {}) ⇒ Object



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
70
71
72
73
# File 'lib/triglav/agent/base/cli.rb', line 33

def option_parser(opts = {})
  op = OptionParser.new

  self.class.module_eval do
    define_method(:usage) do |msg = nil|
      puts op.to_s
      puts "error: #{msg}" if msg
      exit 1
    end
  end

  op.on('-c', '--config VALUE', "Config file (default: #{opts[:config]})") {|v|
    opts[:config] = v
  }
  op.on('-s', '--status VALUE', "Status stroage file (default: status.yml)") {|v|
    opts[:status] = v
  }
  op.on('-t', '--token VALUE', "Triglav access token storage file (default: token.yml)") {|v|
    opts[:token] = v
  }
  op.on('--dotenv', "Load environment variables from .env file (default: #{opts[:dotenv]})") {|v|
    opts[:dotenv] = v
  }
  op.on('--debug', "Debug mode (default: #{opts[:debug]})") {|v|
    opts[:debug] = v
  }
  op.on('-h', '--help', "help") {|v|
    opts[:help] = v
  }
  # serverengine options
  op.on('--log VALUE', "Log path (default: #{Setting::DEFAULT_LOG})") {|v|
    opts[:log] = v
  }
  op.on('--log-level VALUE', "Log level (default: #{Setting::DEFAULT_LOG_LEVEL})") {|v|
    opts[:log_level] = v
  }

  op.banner += ''

  op
end

#parse_options(argv = ARGV) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/triglav/agent/base/cli.rb', line 75

def parse_options(argv = ARGV)
  opts = default_opts
  op = option_parser(opts)

  begin
    args = op.parse(argv)
  rescue OptionParser::InvalidOption => e
    usage e.message
  end

  if opts[:help]
    usage
  end

  if opts[:config].nil?
    usage "--config VALUE is required"
  end
  if !File.readable?(opts[:config])
    usage "Config file '#{opts[:config]}' does not exist or not readable"
  end

  [opts, args]
end

#runObject



15
16
17
18
19
20
21
22
23
# File 'lib/triglav/agent/base/cli.rb', line 15

def run
  opts, _ = parse_options(ARGV)
  $setting = Configuration.setting_class.new(opts)
  $logger = $setting.logger
  se = ServerEngine.create(nil, Configuration.worker_module) do
    $setting.serverengine_options
  end
  se.run
end