Class: Alerty::CLI

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

Instance Method Summary collapse

Instance Method Details

#parse_options(argv = ARGV) ⇒ Object



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
# File 'lib/alerty/cli.rb', line 6

def parse_options(argv = ARGV)
  op = OptionParser.new
  op.banner += ' -- command'

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

  opts = {}
  op.on('-c', '--config CONFIG_FILE', "config file path (default: /etc/alerty/alerty.yml)") {|v|
    opts[:config_path] = v
  }
  op.on('--log LOG_FILE', "log file path (default: STDOUT)") {|v|
    opts[:log_path] = v
  }
  op.on('-l', '--log-level LOG_LEVEL', "log level (default: warn)") {|v|
    opts[:log_level] = v
  }
  op.on('--log-shift-age SHIFT_AGE', "Number of old log files to keep (default: 0 which means no log rotation)") {|v|
    opts[:log_shift_age] = Integer(v)
  }
  op.on('--log-shift-size SHIFT_SIZE', "Maximum logfile size in bytes (default: 1048576)") {|v|
    opts[:log_shift_age] = Integer(v)
  }
  op.on('-t', '--timeout SECONDS', "timeout the command (default: no timeout)") {|v|
    opts[:timeout] = v.to_f
  }
  op.on('--lock LOCK_FILE', "exclusive lock file to prevent running a command duplicatedly (default: no lock)") {|v|
    opts[:lock_path] = v
  }
  op.on('--retry-limit NUMBER', "number of retries (default: 0)") {|v|
    opts[:retry_limit] = v.to_i
  }
  op.on('--retry-wait SECONDS', "retry interval = retry wait +/- 12.5% randomness (default: 1.0)") {|v|
    opts[:retry_wait] = v.to_f
  }
  op.on('-d', '--debug', "debug mode") {|v|
    opts[:debug] = true
  }
  op.on('--dotenv', "Load environment variables from .env file with dotenv") {|v|
    opts[:dotenv] = true
  }

  op.parse!(argv)
  opts[:command] = argv.join(' ')

  if opts[:command].empty?
    raise OptionParser::InvalidOption.new("No command is given")
  end

  opts
end

#runObject



63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/alerty/cli.rb', line 63

def run
  begin
    opts = parse_options
  rescue OptionParser::InvalidOption => e
    usage e.message
  end
  
  Config.configure(opts)
  Config.plugins # load plugins in early stage
  command = Command.new(command: opts[:command])
  command.run!
end