Class: Tootsie::CommandRunner
- Inherits:
-
Object
- Object
- Tootsie::CommandRunner
- Defined in:
- lib/tootsie/command_runner.rb
Instance Method Summary collapse
-
#initialize(command_line, options = {}) ⇒ CommandRunner
constructor
A new instance of CommandRunner.
- #run(params = {}, &block) ⇒ Object
Constructor Details
#initialize(command_line, options = {}) ⇒ CommandRunner
Returns a new instance of CommandRunner.
7 8 9 10 11 12 |
# File 'lib/tootsie/command_runner.rb', line 7 def initialize(command_line, = {}) @options = .symbolize_keys @options.assert_valid_keys(:ignore_exit_code, :output_encoding) @command_line = command_line @logger = Application.get.logger end |
Instance Method Details
#run(params = {}, &block) ⇒ Object
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 53 54 55 |
# File 'lib/tootsie/command_runner.rb', line 14 def run(params = {}, &block) command_line = @command_line if params.any? params = params.with_indifferent_access command_line = command_line.gsub(/(^|\s):(\w+)/) do pre, key, all = $1, $2, $~[0] if params.include?(key) value = params[key] value = "'#{value}'" if value =~ /\s/ "#{pre}#{value}" else all end end end command_line = "#{command_line} 2>&1" @logger.info("Running command: #{command_line}") if @logger.info? IO.popen(command_line, "r:#{@options[:output_encoding] || 'utf-8'}") do |output| output.each_line do |line| @logger.info("[Command output] #{line.strip}") if @logger.info? yield line if block_given? end end status = $? if status.exited? if status.exitstatus != 0 if @options[:ignore_exit_code] return false else raise CommandExecutionFailed, "Command failed with exit code #{status.exitstatus}: #{command_line}" end end elsif status.stopped? raise CommandExecutionFailed, "Command stopped unexpectedly with signal #{status.stopsig}: #{command_line}" elsif status.signaled? raise CommandExecutionFailed, "Command died unexpectedly by signal #{status.termsig}: #{command_line}" else raise CommandExecutionFailed, "Command died unexpectedly: #{command_line}" end true end |