Module: Command
- Defined in:
- lib/prick/command.rb
Defined Under Namespace
Classes: Error
Class Method Summary collapse
-
.command(cmd, stderr: false, fail: true) ⇒ Object
Execute the shell command ‘cmd’ and return standard output as an array of strings while stderr is passed through unless stderr: is false.
-
.command?(cmd, expect: 0) ⇒ Boolean
Like command but returns true if the command exited with the expected status.
-
.status ⇒ Object
Exit status of the last command.
Class Method Details
.command(cmd, stderr: false, fail: true) ⇒ Object
Execute the shell command ‘cmd’ and return standard output as an array of strings while stderr is passed through unless stderr: is false. If stderr: is true, it returns 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
25 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 71 72 73 74 75 76 77 78 |
# File 'lib/prick/command.rb', line 25 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 result = case stderr when true; [out, err] when false; out when NilClass; $stderr.puts err else raise Internal, "Unexpected value for :stderr - #{stderr.inspect}" end if @status == 0 || fail == false result elsif fail raise Command::Error.new("\n" + cmd + "\n" + (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
84 85 86 87 |
# File 'lib/prick/command.rb', line 84 def command?(cmd, expect: 0) command(cmd, fail: false) @status == expect end |
.status ⇒ Object
Exit status of the last command
81 |
# File 'lib/prick/command.rb', line 81 def status() @status end |