Class: Halfshell::Terminal

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

Constant Summary collapse

TIMEOUT =
60 * 60
WAIT_INTERVAL =
1.0/1000
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.



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

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

  @tries = 0
  @max_tries = (TIMEOUT / WAIT_INTERVAL).to_i
end

Class Method Details

.defaultObject



9
10
11
# File 'lib/halfshell/terminal.rb', line 9

def Terminal.default
  Terminal.sh
end

.shObject



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

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

.zshObject



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

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

Instance Method Details

#getsObject



34
35
36
# File 'lib/halfshell/terminal.rb', line 34

def gets
  read_nonblock_loop(@stdout)
end

#gets_errObject



38
39
40
# File 'lib/halfshell/terminal.rb', line 38

def gets_err
  read_nonblock_loop(@stderr)
end

#puts(what) ⇒ Object



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

def puts(what)
  @stdin.puts what
end

#raise_errorObject

Raises:



65
66
67
68
# File 'lib/halfshell/terminal.rb', line 65

def raise_error
  binding.pry if $testing
  raise Error
end

#read_nonblock_loop(io) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/halfshell/terminal.rb', line 42

def read_nonblock_loop(io)
  got = ""
  loop do
    begin
      @tries += 1
      got << io.read_nonblock(1)
    rescue IO::EAGAINWaitReadable
      raise_error if too_many_tries?
      if got.empty?
        sleep(WAIT_INTERVAL)
        return read_nonblock_loop(io)
      else
        @tries = 0
        return got
      end
    end
  end
end

#too_many_tries?Boolean

Returns:

  • (Boolean)


61
62
63
# File 'lib/halfshell/terminal.rb', line 61

def too_many_tries?
  @tries >= @max_tries
end