Class: Pity::REPL

Inherits:
Object
  • Object
show all
Defined in:
lib/pity.rb

Constant Summary collapse

READ_CHUNK_SIZE =

Number of bytes to read at a time.

512
SELECT_TIMEOUT =

Seconds to wait in IO.select before retrying.

0.01
TIMEOUT =

How long to wait before giving up on a read.

5
PROMPT_CAPTURE_TIMEOUT =

How long to wait before giving up on a prompt capture.

1

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(command = "bash", prompt: nil, logger: self.class.logger) ⇒ REPL

Returns a new instance of REPL.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/pity.rb', line 26

def initialize(command = "bash", prompt: nil, logger: self.class.logger)
  @logger = logger
  @stdout, @stdin, @pid = PTY.spawn(command)
  @stdout.sync = true
  @stdin.sync = true
  logger.debug "Spawned process with PID #{@pid} using command: #{command}"

  captured = prompt || capture_initial_prompt
  @prompt = Regexp.new(Regexp.escape(captured) + '\z')
  logger.debug "Captured prompt: #{captured.inspect}"

  begin
    yield self
  ensure
    cleanup
  end
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



12
13
14
# File 'lib/pity.rb', line 12

def logger
  @logger
end

#stdinObject (readonly)

Returns the value of attribute stdin.



12
13
14
# File 'lib/pity.rb', line 12

def stdin
  @stdin
end

#stdoutObject (readonly)

Returns the value of attribute stdout.



12
13
14
# File 'lib/pity.rb', line 12

def stdout
  @stdout
end

Instance Method Details

#expect(expectation) ⇒ Object



53
54
55
# File 'lib/pity.rb', line 53

def expect(expectation, **)
  read_until(**) { |buf| buf.match(expectation) }
end

#getsObject



49
50
51
# File 'lib/pity.rb', line 49

def gets(**)
  expect(@prompt, **)
end

#puts(input) ⇒ Object



44
45
46
47
# File 'lib/pity.rb', line 44

def puts(input)
  @stdin.puts(input)
  logger.debug "Sent: #{input}"
end