1
2
3
4
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
|
# frozen_string_literal: true
module Jive
module Popen
Result = Struct.new(:command, :stdout, :stderr, :status, :duration)
def self.popen(command, path = nil, env = {}, &block)
result = popen_with_detail(command, path, env, &block)
["#{result.stdout}#{result.stderr}", result.status&.exitstatus]
end
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
end
end
|