Module: Cmd2Json

Defined in:
lib/cmd2json.rb,
lib/cmd2json/version.rb

Constant Summary collapse

VERSION =
"0.2.1"

Class Method Summary collapse

Class Method Details

.extract_options!(argv, parser) ⇒ Object

split options from argv so we can reuse the rest as command -a 1 echo hello -> -a 1 + echo hello



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/cmd2json.rb', line 31

def self.extract_options!(argv, parser)
  list = parser.top.list
  options = []
  loop do
    arg = argv.first
    break unless option = list.detect { |o| o.short.include?(arg) || o.long.include?(arg) }

    options << argv.shift
    options << argv.shift if option.arg
  end
  options
end

.run(argv, options = {}) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/cmd2json.rb', line 5

def self.run(argv, options={})
  out = ""
  begin
    IO.popen(argv, err: [:child, :out]) { |io| out = io.read }

    # log when subprocess was killed, need manual testing as integration test
    unless status = $?.exitstatus
      out << "\nKilled"
      status = 1
    end
  rescue Errno::ENOENT # executable not found
    out = $!.message
    status = 1
  rescue SignalException # need manual testing as integration test
    out << "\nKilled #{$!}"
    status = 1
  end

  result = {message: out, exit: status}
  result['@timestamp'] = Time.now if options[:timestamp]
  result[:host] = Socket.gethostname if options[:host]
  [status, result.merge(options[:add] || {}).to_json]
end