BigW Consortium Gitlab

popen.rb 742 Bytes
Newer Older
1
require 'fileutils'
2
require 'open3'
3

4 5
module Gitlab
  module Popen
6 7
    extend self

8
    def popen(cmd, path = nil)
9 10 11 12
      unless cmd.is_a?(Array)
        raise "System commands must be given as an array of strings"
      end

13
      path ||= Dir.pwd
14
      vars = { "PWD" => path }
15
      options = { chdir: path }
16

17
      unless File.directory?(path)
Dale Hamel committed
18
        FileUtils.mkdir_p(path)
19 20
      end

21 22
      cmd_output = ""
      cmd_status = 0
23
      Open3.popen3(vars, *cmd, options) do |stdin, stdout, stderr, wait_thr|
24
        yield(stdin) if block_given?
25
        stdin.close
26

27 28 29
        cmd_output << stdout.read
        cmd_output << stderr.read
        cmd_status = wait_thr.value.exitstatus
30 31
      end

32
      [cmd_output, cmd_status]
33 34 35
    end
  end
end