Top Level Namespace

Defined Under Namespace

Modules: Rack

Instance Method Summary collapse

Instance Method Details

#main(argv) ⇒ Object



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
# File 'bin/flgrep', line 12

def main(argv)
  options = {}
  opt = OptionParser.new
  opt.on('-c', '--column=s', 'column name to target') {|v| options[:column] = v }
  opt.on('-v', '--value=s', 'value for filtering') {|v| options[:value] = v }
  opt.on('-d', '--date[=s]', 'filtering by date') {|v| options[:date] = v }
  opt.on('--until[=s]', 'filtering by date until ...') {|v| options[:until] = v }
  opt.on('--since[=s]', 'filtering by date since ...') {|v| options[:since] = v }
  opt.on('-m', '--method=(regexp|gt|lt)', 'regexp (default): match by regexp, gt: greater than, lt: less than') {|v| options[:method] = v }
  opt.on('--mode=(filter|color)', 'filter (default): like grep, color: show colored line when match condition.') {|v| options[:mode] = v }
  opt.parse!(argv)
  if options[:column].nil? or options[:value].nil?
    warn opt.help
    exit(1)
  end
  
  options[:method] ||= 'regexp'
  options[:mode] ||= 'filter'
  
  regexp = Regexp.compile(options[:value], 'i')

  date_regexp = options[:date] ? Regexp.compile(options[:date], 'i') : nil
  since_date = options[:since] ? Time.parse(options[:since]) : nil
  until_date = options[:until] ? Time.parse(options[:until]) : nil
  
  tab_regexp = /\t/
  while line = STDIN.gets
    line.chomp!
    date, tag, data = line.split(tab_regexp)
    if date_regexp
      next if date !~ date_regexp
    end
    if since_date
      dt = Time.parse(date)
      next if dt < since_date
    end
    if until_date
      dt = Time.parse(date)
      next if dt > until_date
    end
    data = JSON.parse(data)
  
    case options[:method]
    when 'regexp'
      show_if_match(line, options) {|options| regexp.match(data[options[:column]].to_s) }
    when 'lt'
      show_if_match(line, options) {|options| data[options[:column]] <= options[:value].to_f }
    when 'gt'
      show_if_match(line, options) {|options| data[options[:column]] >= options[:value].to_f }
    else
    end
  end
end

#show_if_match(line, options, &block) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'bin/flgrep', line 66

def show_if_match(line, options, &block)
  if block.call(options)
    if options[:mode] == "color"
      puts "\033[31m#{line}\033[0m"
    else
      puts line
    end
  else
    if options[:mode] == "color"
      puts line
    end
  end
end