Class: By2::Options

Inherits:
Object
  • Object
show all
Defined in:
lib/by2/options.rb

Constant Summary collapse

OptionsError =
Class.new(RuntimeError)

Class Method Summary collapse

Class Method Details

.parse(argv) ⇒ Object



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
70
71
72
73
74
75
# File 'lib/by2/options.rb', line 5

def self.parse(argv)
  options = { start_date: 2.weeks.ago }
  req_options = {}

  opts = OptionParser.new do |x|
    x.banner = "Usage: by2 [options]"

    x.separator ""
    x.separator "Required options (at least one is required):"

    x.on("-i IP", String, "source or destination ip w/optional port") do |ip|
      req_options[:ip], req_options[:port] = ip.split(":")
    end

    x.on("-s SRC_IP", String, "source ip w/optional port") do |ip|
      req_options[:src_ip], req_options[:src_port] = ip.split(":")
    end

    x.on("-d DST_IP", String, "destination ip w/optional port") do |ip|
      req_options[:dst_ip], req_options[:dst_port] = ip.split(":")
    end

    x.on("-m DUMP_STR", String, "dump string: \"src_ip:src_port -> dst_ip:dst_port\"") do |ips|
      src_ip, dst_ip = ips.split("->")
      req_options[:src_ip], req_options[:src_port] = src_ip.strip.split(":")
      req_options[:dst_ip], req_options[:dst_port] = dst_ip.strip.split(":")
    end

    x.on("-t DATE", String, "date (yyyy-mm-dd)") do |date|
      if date.include?(":")
        req_options[:start_date], req_options[:end_date] = date.split(":")
      else
        req_options[:date] = date
        options.delete(:start_date)
      end
    end


    x.separator ""
    x.separator "Additional options:"

    x.on("-l LIMIT", Integer, "limit number of returned records") do |l|
      options[:limit] = l
    end

    x.on("-D", TrueClass, "debug flag") do
      options[:debug] = true
    end

    x.on("-C", TrueClass, "only print number of records found") do
      options[:count] = true
    end

    x.on("-h", "Show this message") do
      $stdout.puts(opts); exit
    end

    x.on("-H", "Show man page") do
      $stdout.puts(File.read("#{::By2.root}/man/by2.1.txt")); exit
    end
  end

  opts.parse!(argv)

  raise OptionsError if req_options.empty?

  options.merge(req_options)
rescue OptionParser::ParseError, OptionsError => err
  raise OptionsError.new(opts) if err.is_a?(OptionsError)
  raise OptionsError.new(err)
end