BigW Consortium Gitlab

popen.rb 832 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 25 26
        # We are not using stdin so we should close it, in case the command we
        # are running waits for input.
        stdin.close
27 28
        @cmd_output << stdout.read
        @cmd_output << stderr.read
29
        @cmd_status = wait_thr.value.exitstatus
30 31 32 33 34 35
      end

      return @cmd_output, @cmd_status
    end
  end
end