Class: Halfshell::Terminal

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

Constant Summary collapse

OPEN4_RETURNS =
[:pid, :stdin, :stdout, :stderr]

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(stdin:, stdout:, stderr:, pid:) ⇒ Terminal

Returns a new instance of Terminal.



16
17
18
19
20
21
# File 'lib/halfshell/terminal.rb', line 16

def initialize(stdin:, stdout:, stderr:, pid:)
  @stdin, @stdout, @stderr, @pid = stdin, stdout, stderr, pid

  @try = 0
  @limit = 1000
end

Class Method Details

.defaultObject



6
7
8
# File 'lib/halfshell/terminal.rb', line 6

def Terminal.default
  Terminal.popen4
end

.popen4Object



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

def Terminal.popen4
  Terminal.new(**OPEN4_RETURNS.zip(Open4::popen4("sh 2>&1")).to_h)
end

Instance Method Details

#getsObject



27
28
29
# File 'lib/halfshell/terminal.rb', line 27

def gets
  read_nonblock_loop(@stdout)
end

#gets_errObject



31
32
33
# File 'lib/halfshell/terminal.rb', line 31

def gets_err
  read_nonblock_loop(@stderr)
end

#puts(what) ⇒ Object



23
24
25
# File 'lib/halfshell/terminal.rb', line 23

def puts(what)
  @stdin.puts what
end

#raise_errorObject

Raises:



57
58
59
60
# File 'lib/halfshell/terminal.rb', line 57

def raise_error
  binding.pry if $testing
  raise Error
end

#read_nonblock_loop(io) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/halfshell/terminal.rb', line 35

def read_nonblock_loop(io)
  got = ""
  loop do
    begin
      got << io.read_nonblock(1)
    rescue IO::EAGAINWaitReadable
      raise_error if too_many_tries?
      if got.empty?
        sleep(1.0/1000) #sleep(WAIT*@backoff.next)
        return read_nonblock_loop(io)
      else
        @try = 0
        return got
      end
    end
  end
end

#too_many_tries?Boolean

Returns:

  • (Boolean)


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

def too_many_tries?
  @try >= @limit
end