Module: Jive::Popen

Defined in:
lib/jive/popen.rb

Defined Under Namespace

Classes: Result

Class Method Summary collapse

Class Method Details

.popen(command, path = nil, env = {}, &block) ⇒ Object



7
8
9
10
11
# File 'lib/jive/popen.rb', line 7

def self.popen(command, path = nil, env = {}, &block)
  result = popen_with_detail(command, path, env, &block)

  ["#{result.stdout}#{result.stderr}", result.status&.exitstatus]
end

.popen_with_detail(command, path = Dir.pwd, env = {}) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/jive/popen.rb', line 13

def self.popen_with_detail(command, path = Dir.pwd, env = {})
  FileUtils.mkdir_p(path) unless File.directory?(path)

  captured_stdout = ""
  captured_stderr = ""
  exit_status = nil
  start = Time.now

  Open3.popen3(env.merge("PWD" => path), *Array(command),
               { chdir: path }) do |stdin, stdout, stderr, wait_thr|
                 out_reader = Thread.new { stdout.read }
                 err_reader = Thread.new { stderr.read }

                 yield(stdin) if block_given?

                 stdin.close
                 captured_stdout = out_reader.value
                 captured_stderr = err_reader.value
                 exit_status = wait_thr.value
               end
  Result.new(command, captured_stdout, captured_stderr, exit_status,
             Time.now - start)
end