Module: Cmd2Json

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

Constant Summary collapse

VERSION =
"0.1.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



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/cmd2json.rb', line 22

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
# File 'lib/cmd2json.rb', line 5

def self.run(argv, options={})
  begin
    out = ""
    IO.popen(argv, err: [:child, :out]) { |io| out = io.read }
    status = $?.exitstatus
  rescue Errno::ENOENT
    out = $!.message
    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