Created
March 26, 2010 20:55
-
-
Save eventualbuddha/345380 to your computer and use it in GitHub Desktop.
Execute shell commands and raise if it fails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Command | |
attr_accessor :command, :stdout, :stderr, :process | |
class Error < RuntimeError | |
def initialize(command) | |
error = "command failed" | |
error << " ($?=#{command.process.exitstatus})" if command.process | |
error << ": #{command.command_string}" | |
error << "\n\nOUTPUT:\n\n#{command.stdout}" if command.stdout && !command.stdout.empty? | |
super error | |
end | |
end | |
def initialize(*command) | |
@command = command.flatten | |
yield self if block_given? | |
end | |
def run | |
self.stdout = %x{#{command_string} 2>&1} | |
self.process = $? | |
end | |
def command_string | |
command.join(' ') | |
end | |
def system_or_raise | |
puts "+ #{command_string}" | |
system(*command) | |
self.process = $? | |
return self if $?.success? | |
raise Command::Error, self | |
end | |
def run_or_raise | |
run | |
return self if process.success? | |
raise Command::Error, self | |
end | |
def capture | |
run_or_raise.stdout | |
end | |
def self.capture(*cmd) | |
new(*cmd).capture | |
end | |
def self.system_or_raise(*cmd) | |
new(*cmd).system_or_raise | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment