Skip to content

Instantly share code, notes, and snippets.

@remogatto
Created February 23, 2010 21:25
Show Gist options
  • Save remogatto/312730 to your computer and use it in GitHub Desktop.
Save remogatto/312730 to your computer and use it in GitHub Desktop.
package makengo
import (
"os"
"exec"
"bytes"
"io"
"strings"
)
func System(command string) (out string, err os.Error) {
return run([]string { os.Getenv("SHELL"), "-c", command })
}
func copy(a []string) []string {
b := make([]string, len(a))
for i, s := range a {
b[i] = s
}
return b
}
func run(argv []string) (out string, err os.Error) {
if len(argv) < 1 {
err = os.EINVAL
goto Error
}
var cmd *exec.Cmd
cmd, err = exec.Run(argv[0], argv, os.Environ(), exec.DevNull, exec.Pipe, exec.MergeWithStdout)
if err != nil {
goto Error
}
defer cmd.Close()
var buf bytes.Buffer
_, err = io.Copy(&buf, cmd.Stdout)
out = buf.String()
if err != nil {
cmd.Wait(0)
goto Error
}
w, err := cmd.Wait(0)
if err != nil {
goto Error
}
if !w.Exited() || w.ExitStatus() != 0 {
err = w
goto Error
}
return
Error:
err = &runError{ copy(argv), err }
return
}
// A runError represents an error that occurred while running a command.
type runError struct {
cmd []string
err os.Error
}
func (e *runError) String() string { return strings.Join(e.cmd, " ") + ": " + e.err.String() }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment