class ProcessOutputWrapper::Command

Attributes

command[R]
line[R]

Public Class Methods

new(command) click to toggle source
# File lib/process_output_wrapper/command.rb, line 3
def initialize(command)
  @command = command
  @line = ""
  @print_normally = false
end

Public Instance Methods

execute() click to toggle source
# File lib/process_output_wrapper/command.rb, line 9
def execute
  if ENV['VERBOSE'] == 'true'
    execute_normally
  else
    execute_wrapped
  end
end
whenever(&blk) click to toggle source
# File lib/process_output_wrapper/command.rb, line 17
def whenever(&blk)
  Whenever.new(&blk).tap do |w|
    conditionals << w
  end
end

Private Instance Methods

check_conditionals() click to toggle source
# File lib/process_output_wrapper/command.rb, line 40
def check_conditionals
  return if @line.length == 0
  @line = without_color(@line)

  conditionals.each do |conditional|
    if instance_eval(&conditional.condition)
      instance_eval(&conditional.result)
    end
  end
end
conditionals() click to toggle source
# File lib/process_output_wrapper/command.rb, line 36
def conditionals
  @conditionals ||= []
end
execute_normally() click to toggle source
# File lib/process_output_wrapper/command.rb, line 55
def execute_normally
  system(command)
end
execute_wrapped() click to toggle source
# File lib/process_output_wrapper/command.rb, line 59
def execute_wrapped
  @output = ""
  @line = ""
  input_thread = nil

  IO.console.raw!

  PTY.spawn(command) do |read, write, pid|
    write.winsize = STDOUT.winsize
    Signal.trap(:WINCH) { write.winsize = STDOUT.winsize }
    input_thread = Thread.new { IO.copy_stream(STDIN, write) }

    read.each_char do |char|
      @output.concat(char)
      print(char) if @print_normally

      case char
      when "\n", "\r"
        IO.console.cooked!
        check_conditionals
        IO.console.raw!
        @line = ""
      else
        @line.concat(char)
      end
    end

    Process.wait(pid)
  end
  input_thread.kill if input_thread

  IO.console.cooked!

  $?.exitstatus
end
print_normally!() click to toggle source
print_wrapped!() click to toggle source
without_color(str) click to toggle source
# File lib/process_output_wrapper/command.rb, line 51
def without_color(str)
  str.gsub(/\x1B\[([0-9]{1,3}((;[0-9]{1,3})*)?)?[m|K]/, "")
end