Module: JSE::CLI

Defined in:
lib/jse/cli.rb

Class Method Summary collapse

Class Method Details

.execute(stdout, arguments = []) ⇒ 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
# File 'lib/jse/cli.rb', line 5

def self.execute(stdout, arguments = [])
  print = []
  ignore_case = false
  parser = OptionParser.new do |opts|
    opts.banner = <<-BANNER.gsub(/^[ \t]*/, '')
    Json Stream Editor.

    Usage: #{File.basename($0)} [options]

    Options are:
  BANNER
    opts.separator ""
    opts.on("-f", "--fields a,b,c", Array,
            "List of fields to return") do |fields|
      print = fields
    end
    opts.on("-i", "--ignore-case",
            "Make all matches case insensitive") do
      ignore_case = true
    end
    opts.on("-h", "--help",
            "Show this help message.") { stdout.puts opts; exit }
    opts.parse!(arguments)
  end

  if File.exist?(arguments.last)
    stream = JSE::Stream.new(File.open(arguments.pop, 'r'))
  else
    stream = JSE::Stream.new(STDIN)
  end

  arguments.each do |arg|
    field, text = arg.split(':')
    stream.filter!(field, text, ignore_case)
  end

  unless print.empty?
    stream.print!(*print)
  end

  begin
    stream.each_line do |line|
      stdout.puts line
    end
  rescue Errno::EPIPE, Interrupt
    # Catch broken pipes so we can use head etc.
  end
end