Permalink
Browse files

Added some actual, you know, code and stuff.

  • Loading branch information...
1 parent 3e3cfa4 commit c2b62f3e49e69178b7e530f7d0b8299230c8e5e1 @notahat notahat committed Nov 8, 2010
Showing with 40 additions and 2 deletions.
  1. +24 −0 lib/safe_shell.rb
  2. +16 −2 spec/safe_shell_spec.rb
View
24 lib/safe_shell.rb
@@ -0,0 +1,24 @@
+module SafeShell
+ 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)
+ end
+ write_end.close
+ output = read_end.read
+ Process.waitpid(pid)
+ read_end.close
+ output
+ end
+
+ def self.execute?(*args)
+ execute(*args)
+ $?.success?
+ end
+end
View
18 spec/safe_shell_spec.rb
@@ -1,7 +1,21 @@
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "SafeShell" do
- it "fails" do
- fail "hey buddy, you should probably rename this file and start specing for real"
+
+ it "should return the output of the command" do
+ SafeShell.execute("echo", "Hello, world!").should == "Hello, world!\n"
+ end
+
+ it "should set $? to the exit status of the command" do
+ SafeShell.execute("test", "a", "=", "a")
+ $?.exitstatus.should == 0
+
+ SafeShell.execute("test", "a", "=", "b")
+ $?.exitstatus.should == 1
end
+
+ it "should safely handle dangerous characters in command arguments" do
+ SafeShell.execute("echo", ";date").should == ";date\n"
+ end
+
end

0 comments on commit c2b62f3

Please sign in to comment.