Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 40 lines (33 sloc) 0.974 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
module SafeShell
  class CommandFailedException < RuntimeError; end

  def self.execute(command, *args)
    opts = args.last.kind_of?(Hash) ? args.pop : {}
    read_end, write_end = IO.pipe
    new_stdout = opts[:stdout] ? File.open(opts[:stdout], "w+") : write_end
    new_stderr = opts[:stderr] ? File.open(opts[:stderr], "w+") : write_end
    pid = fork do
      read_end.close
      STDOUT.reopen(new_stdout)
      STDERR.reopen(new_stderr)
      exec(command, *(args.map { |a| a.to_s }))
    end
    write_end.close
    output = read_end.read
    Process.waitpid(pid)
    read_end.close
    output
  end

  def self.execute?(*args)
    execute(*args)
    $?.success?
  end

  def self.execute!(*args)
    execute(*args).tap do
      raise_command_failed_exception(*args) unless $?.success?
    end
  end

private

  def self.raise_command_failed_exception(*args)
    raise CommandFailedException.new("Shell command #{args.inspect} failed with status #{$?}")
  end

end
Something went wrong with that request. Please try again.