Class: Fig::ExternalProgram

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

Class Method Summary collapse

Class Method Details

.capture(command_line, input = nil) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/fig/external_program.rb', line 40

def self.capture(command_line, input = nil)
  output = nil
  errors = nil

  result = popen(*command_line) do
    |stdin, stdout, stderr|

    if ! input.nil?
      stdin.puts input # Potential deadlock if input is bigger than pipe size.
    end
    stdin.close

    output = StringIO.new
    errors = StringIO.new
    input_to_output = {stdout => output, stderr => errors}
    while ! input_to_output.empty?
      ready, * = IO.select input_to_output.keys
      ready.each do
        |handle|

        begin
          # #readpartial() is busted in that it is returning a byte array in
          # a String with a bogus Encoding, even though the bytes may not be
          # valid in the Encoding.
          input_to_output[handle] << handle.readpartial(4096)
        rescue EOFError
          input_to_output.delete handle
        end
      end
    end
  end

  output_string = string_io_byte_array_to_utf8_string output
  errors_string = string_io_byte_array_to_utf8_string errors

  return output_string, errors_string, result
end

.popen(*cmd) ⇒ Object



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
# File 'lib/fig/external_program.rb', line 10

def self.popen(*cmd)
  exit_code = nil

  options = {}
  stdin_read, stdin_write = IO.pipe Encoding::UTF_8, Encoding::UTF_8
  options[:in] = stdin_read
  stdin_write.sync = true

  stdout_read, stdout_write = IO.pipe Encoding::UTF_8, Encoding::UTF_8
  options[:out] = stdout_write

  stderr_read, stderr_write = IO.pipe Encoding::UTF_8, Encoding::UTF_8
  options[:err] = stderr_write

  popen_run(
    cmd,
    options,
    [stdin_read, stdout_write, stderr_write],
    [stdin_write, stdout_read, stderr_read],
  ) do
    |stdin, stdout, stderr, wait_thread|

    yield stdin, stdout, stderr

    exit_code = wait_thread.value
  end

  return exit_code
end