Class: Nomade::Shell

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

Class Method Summary collapse

Class Method Details

.exec(command, input = nil, allowed_exit_codes = [0]) ⇒ Object



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
# File 'lib/nomade/shell.rb', line 5

def self.exec(command, input = nil, allowed_exit_codes = [0])
  Nomade.logger.debug("+: #{command}")

  process, status, stdout, stderr = Open3.popen3(command) do |stdin, stdout, stderr, wait_thread|
    if input
      stdin.puts(input)
    end
    stdin.close

    threads = {}.tap do |it|
      it[:stdout] = Thread.new do
        output = []
        stdout.each do |l|
          output << l
          Nomade.logger.debug(l)
        end
        Thread.current[:output] = output.join
      end

      it[:stderr] = Thread.new do
        output = []
        stderr.each do |l|
          output << l
          Nomade.logger.debug(l)
        end
        Thread.current[:output] = output.join
      end
    end
    threads.values.map(&:join)

    [wait_thread.value, wait_thread.value.exitstatus, threads[:stdout][:output], threads[:stderr][:output]]
  end

  unless allowed_exit_codes.include?(status)
    raise "`#{command}` failed with status=#{status}"
  end

  return [status, stdout, stderr]
end