Skip to content

Instantly share code, notes, and snippets.

@eventualbuddha
Created March 26, 2010 20:55
Show Gist options
  • Save eventualbuddha/345380 to your computer and use it in GitHub Desktop.
Save eventualbuddha/345380 to your computer and use it in GitHub Desktop.
Execute shell commands and raise if it fails
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