Module: Command

Defined in:
lib/prick/command.rb

Defined Under Namespace

Classes: Error

Class Method Summary collapse

Class Method Details

.command(cmd, stderr: false, fail: true) ⇒ Object

Execute the shell command ‘cmd’ and return the output as an array of strings

If :stderr is true, it returns return a tuple of [stdout, stderr] instead

The shell command is executed with the ‘errexit` and `pipefail` bash options. It raises a Command::Error exception if the command fails unless :fail is true. The exit status of the last command is stored in ::status



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/prick/command.rb', line 26

def command(cmd, stderr: false, fail: true)
  cmd = "set -o errexit\nset -o pipefail\n#{cmd}"

  pw = IO::pipe   # pipe[0] for read, pipe[1] for write
  pr = IO::pipe
  pe = IO::pipe

  STDOUT.flush

  pid = fork {
    pw[1].close
    pr[0].close
    pe[0].close

    STDIN.reopen(pw[0])
    pw[0].close

    STDOUT.reopen(pr[1])
    pr[1].close

    STDERR.reopen(pe[1])
    pe[1].close

    exec(cmd)
  }

  pw[0].close
  pr[1].close
  pe[1].close

  @status = Process.waitpid2(pid)[1].exitstatus

  out = pr[0].readlines.collect { |line| line.chop }
  err = pe[0].readlines.collect { |line| line.chop }

  pw[1].close
  pr[0].close
  pe[0].close

  if @status == 0 || fail == false
    stderr ? [out, err] : out
  else
    raise Command::Error.new((out + err).join("\n") + "\n", status, out, err)
  end
end

.command?(cmd, expect: 0) ⇒ Boolean

Like command but returns true if the command exited with the expected status

Returns:

  • (Boolean)


76
77
78
79
# File 'lib/prick/command.rb', line 76

def command?(cmd, expect: 0)
  command(cmd, fail: false)
  @status == expect
end

.statusObject

Exit status of the last command



73
# File 'lib/prick/command.rb', line 73

def status() @status end