Method: Moonshot::Shell.sh_out

Defined in:
lib/moonshot/shell.rb

.sh_out(cmd, fail = true, stdin = '') ⇒ Object

Run a command, returning stdout. Stderr is suppressed unless the command returns non-zero.



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
# File 'lib/moonshot/shell.rb', line 22

def sh_out(cmd, fail = true, stdin = '')
  r_in, w_in = IO.pipe
  r_out, w_out = IO.pipe
  r_err, w_err = IO.pipe
  w_in.write(stdin)
  w_in.close
  pid = Process.spawn(cmd, in: r_in, out: w_out, err: w_err)
  Process.wait(pid)

  r_in.close
  w_out.close
  w_err.close
  stdout = r_out.read
  r_out.close
  stderr = r_err.read
  r_err.close

  if fail && $CHILD_STATUS.exitstatus != 0
    raise CommandError, "`#{cmd}` exited #{$CHILD_STATUS.exitstatus}\n" \
         "stdout:\n" \
         "#{stdout}\n" \
         "stderr:\n" \
         "#{stderr}\n"
  end
  stdout
end