class ReplRunner::PtyParty

Constants

TIMEOUT

Attributes

input[RW]
output[RW]
pid[RW]

Public Class Methods

new(command) click to toggle source
# File lib/repl_runner/pty_party.rb, line 6
def initialize(command)
  @output, @input, @pid = PTY.spawn(command)
end

Public Instance Methods

close(timeout = TIMEOUT) click to toggle source
# File lib/repl_runner/pty_party.rb, line 21
def close(timeout = TIMEOUT)
  Timeout::timeout(timeout) do
    input.close
    output.close
  end
rescue Timeout::Error
  # do nothing
ensure
  Process.kill('TERM', pid)   if pid.present?
end
read(timeout = TIMEOUT, str = "") click to toggle source

There be dragons - (You’re playing with process deadlock)

We want to read the whole output of the command First pull all contents from stdout (except we don’t know how many there are) So we have to go until our process deadlocks, then we timeout and return the string

# File lib/repl_runner/pty_party.rb, line 38
def read(timeout = TIMEOUT, str = "")
  while true
    Timeout::timeout(timeout) do
      str << output.readline
      break if output.eof?
    end
  end

  return str
rescue Timeout::Error, EOFError, Errno::EIO
  return str
end
run(cmd, timeout = TIMEOUT) click to toggle source
# File lib/repl_runner/pty_party.rb, line 16
def run(cmd, timeout = TIMEOUT)
  write(cmd)
  return read(timeout)
end
write(cmd) click to toggle source
# File lib/repl_runner/pty_party.rb, line 10
def write(cmd)
  input.write(cmd)
rescue Errno::EIO => e
  raise e, "#{e.message} | trying to write '#{cmd}'"
end