summaryrefslogtreecommitdiffstats
path: root/lib/terrapin/multi_pipe_extensions.rb
blob: 51d7de37c596329da4d866a7408a962a75d59c67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# frozen_string_literal: false
# Fix adapted from https://github.com/thoughtbot/terrapin/pull/5

module Terrapin
  module MultiPipeExtensions
    def read
      read_streams(@stdout_in, @stderr_in)
    end

    def close_read
      begin
        @stdout_in.close
      rescue IOError
        # Do nothing
      end

      begin
        @stderr_in.close
      rescue IOError
        # Do nothing
      end
    end

    def read_streams(output, error)
      @stdout_output = ''
      @stderr_output = ''

      read_fds = [output, error]

      until read_fds.empty?
        to_read, = IO.select(read_fds)

        if to_read.include?(output)
          @stdout_output << read_stream(output)
          read_fds.delete(output) if output.closed?
        end

        if to_read.include?(error)
          @stderr_output << read_stream(error)
          read_fds.delete(error) if error.closed?
        end
      end
    end

    def read_stream(io)
      result = ''

      begin
        while (partial_result = io.read_nonblock(8192))
          result << partial_result
        end
      rescue EOFError, Errno::EPIPE
        io.close
      rescue Errno::EINTR, Errno::EWOULDBLOCK, Errno::EAGAIN
        # Do nothing
      end

      result
    end
  end
end

Terrapin::CommandLine::MultiPipe.prepend(Terrapin::MultiPipeExtensions)