Class: XCCache::Sh

Inherits:
Object
  • Object
show all
Extended by:
Config::Mixin
Defined in:
lib/xccache/core/sh.rb

Defined Under Namespace

Classes: ExecError

Class Method Summary collapse

Methods included from Config::Mixin

config

Class Method Details

.capture_output(cmd) ⇒ Object



14
15
16
# File 'lib/xccache/core/sh.rb', line 14

def capture_output(cmd)
  run(cmd, capture: true, log_cmd: false)[0].strip
end

.run(*args, env: nil, **options) ⇒ Object



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
44
45
46
47
48
# File 'lib/xccache/core/sh.rb', line 18

def run(*args, env: nil, **options)
  cmd = args.join(" ")
  UI.message("$ #{cmd}".cyan.dark) if config.verbose? && options[:log_cmd] != false

  out, err = [], []
  handle_out = proc do |line|
    if options[:capture]
      out << line
    else
      UI.puts line
    end
  end
  handle_err = proc do |line|
    if options[:capture]
      err << line
    else
      UI.puts line.strip.yellow unless options[:suppress_err]&.match(line)
    end
  end

  popen3_args = env ? [env, cmd] : [cmd]
  Open3.popen3(*popen3_args) do |_stdin, stdout, stderr, wait_thr|
    stdout_thread = Thread.new { stdout.each { |l| handle_out.call(l) } }
    stderr_thread = Thread.new { stderr.each { |l| handle_err.call(l) } }
    [stdout_thread, stderr_thread].each(&:join)
    result = wait_thr.value
    result.exitstatus
    raise ExecError, "Command '#{cmd}' failed with status: #{result.exitstatus}" unless result.success?
  end
  [out.join("\n"), err.join("\n")]
end