Class: CommandUtils

Inherits:
Object
  • Object
show all
Defined in:
lib/command_utils.rb,
lib/command_utils/non_zero_status.rb

Overview

Class to assist calling external commands, while processing its output and return code. All methods which execute given command, raise NonZeroStatus if its return is not 0.

Defined Under Namespace

Classes: NonZeroStatus

Instance Method Summary collapse

Constructor Details

#initialize(*command) ⇒ CommandUtils

Takes command in same format supported by Process#spawn



8
9
10
# File 'lib/command_utils.rb', line 8

def initialize *command
  @command = command
end

Instance Method Details

#each_outputObject

Execute command, yielding to given block, each time there is output.

stream

either :stdout or :stderr.

data

data read from respective stream.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/command_utils.rb', line 15

def each_output # :yields: stream, data
  run do
    loop do
      io_list = [@stdout_read, @stderr_read].keep_if{|io| not io.closed?}
      break if io_list.empty?
      IO.select(io_list).first.each do |io|
        if io.eof?
          io.close
          next
        end
        label = case io
        when @stdout_read
          :stdout
        when @stderr_read
          :stderr
        end
        yield label, io.read
      end
    end
  end
end

#logger_exec(options) ⇒ Object

Execute command, logging its output to given Logger object. Must receive a hash, containing at least:

:logger

Logger instance.

:stdout_level

Logger level to log stdout.

:stderr_level

Logger level to log stderr.

and optionally:

:stdout_prefix

Prefix to use for all stdout messages.

:stderr_prefix

Prefix to use for all stderr messages.



45
46
47
48
49
50
51
52
# File 'lib/command_utils.rb', line 45

def logger_exec options
  logger = options[:logger]
  each_output do |stream, data|
    level = options["#{stream}_level".to_sym]
    prefix = options["#{stream}_prefix".to_sym]
    logger.send(level, "#{prefix}#{data}")
  end
end