Method: BatchKit::Helpers::Process.launch

Defined in:
lib/batch-kit/helpers/process.rb

.launch(cmd_line, options = {}, &block) ⇒ Object

Launch an external process with logging etc. By default, an exception will be raised if the process returns a non-zero exit code.

Parameters:

  • cmd_line (String, Array<String>)

    The command-line to be run, in the form of either a single String, or an Array of Strings.

  • options (Hash) (defaults to: {})

    An options hash.

Options Hash (options):

  • :raise_on_error (Boolean)

    If true (default), an exception is raised if the return code is not a success code.

  • The (Fixnum, Array<Fixnum>)

    return code(s) that the process can return if successful (default 0).

  • :show_duration (Boolean)

    If true (default), logs the duration taken by the process.

  • :logger (Logger)

    The logger to use; defaults to using a logger named after the process being executed.



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/batch-kit/helpers/process.rb', line 61

def launch(cmd_line, options = {}, &block)
    exe = cmd_line.is_a?(String) ?
        File.basename(Shellwords.shellwords(cmd_line.gsub(/\\/, '/')).first) :
        File.basename(cmd_line.first)

    raise_on_error = options.fetch(:raise_on_error, true)
    show_duration = options.fetch(:show_duration, true)
    success_code = options.fetch(:success_code, 0)
    log = options.fetch(:logger, BatchKit::LogManager.logger(exe))
    log_level = options.fetch(:log_level, :detail)
    unless block_given? || options[:callback]
        options = options.dup
        options[:callback] = lambda{ |line| log.send(log_level, line) }
    end

    log.trace("Executing command line: #{cmd_line}") if log
    begin
        start = Time.now
        rc = popen(cmd_line, options, &block)
    ensure
        if log && show_duration
            log.detail "#{exe} completed in #{Time.now - start} seconds with exit code #{rc}"
        end
    end

    if raise_on_error
        ok = case success_code
        when Fixnum then success_code == rc
        when Array then success_code.include?(rc)
        end
        raise "#{exe} returned failure exit code #{rc}" unless ok
    end
    rc
end