blob: 6236c915a5e882149651245ecd21f646dc340b05 [file] [log] [blame]
Andrew Gerrand3e8cc7f2010-09-13 10:46:17 +10001package main
2
3import (
4 "bytes"
5 "exec"
Andrew Gerrandb3601a52010-10-21 15:33:31 +11006 "io"
Andrew Gerrand3e8cc7f2010-09-13 10:46:17 +10007 "os"
Andrew Gerrand96d6f9d2010-09-22 15:18:41 +10008 "strings"
Andrew Gerrand3e8cc7f2010-09-13 10:46:17 +10009)
10
11// run is a simple wrapper for exec.Run/Close
12func run(envv []string, dir string, argv ...string) os.Error {
Andrew Gerrand96d6f9d2010-09-22 15:18:41 +100013 bin, err := pathLookup(argv[0])
Andrew Gerrand3e8cc7f2010-09-13 10:46:17 +100014 if err != nil {
15 return err
16 }
17 p, err := exec.Run(bin, argv, envv, dir,
18 exec.DevNull, exec.DevNull, exec.PassThrough)
19 if err != nil {
20 return err
21 }
22 return p.Close()
23}
24
Andrew Gerrandb3601a52010-10-21 15:33:31 +110025// runLog runs a process and returns the combined stdout/stderr,
26// as well as writing it to logfile (if specified).
27func runLog(envv []string, logfile, dir string, argv ...string) (output string, exitStatus int, err os.Error) {
Andrew Gerrand96d6f9d2010-09-22 15:18:41 +100028 bin, err := pathLookup(argv[0])
Andrew Gerrand3e8cc7f2010-09-13 10:46:17 +100029 if err != nil {
30 return
31 }
32 p, err := exec.Run(bin, argv, envv, dir,
33 exec.DevNull, exec.Pipe, exec.MergeWithStdout)
34 if err != nil {
35 return
36 }
37 defer p.Close()
38 b := new(bytes.Buffer)
Andrew Gerrandb3601a52010-10-21 15:33:31 +110039 var w io.Writer = b
40 if logfile != "" {
41 f, err := os.Open(logfile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
42 if err != nil {
43 return
44 }
45 defer f.Close()
46 w = io.MultiWriter(f, b)
47 }
48 _, err = io.Copy(w, p.Stdout)
Andrew Gerrand3e8cc7f2010-09-13 10:46:17 +100049 if err != nil {
50 return
51 }
Andrew Gerrandb3601a52010-10-21 15:33:31 +110052 wait, err := p.Wait(0)
Andrew Gerrand3e8cc7f2010-09-13 10:46:17 +100053 if err != nil {
54 return
55 }
Andrew Gerrandb3601a52010-10-21 15:33:31 +110056 return b.String(), wait.WaitStatus.ExitStatus(), nil
Andrew Gerrand3e8cc7f2010-09-13 10:46:17 +100057}
Andrew Gerrand96d6f9d2010-09-22 15:18:41 +100058
59// Find bin in PATH if a relative or absolute path hasn't been specified
60func pathLookup(s string) (string, os.Error) {
Robert Griesemer34788912010-10-22 10:06:33 -070061 if strings.HasPrefix(s, "/") || strings.HasPrefix(s, "./") || strings.HasPrefix(s, "../") {
Andrew Gerrand96d6f9d2010-09-22 15:18:41 +100062 return s, nil
Robert Griesemer34788912010-10-22 10:06:33 -070063 }
Andrew Gerrand96d6f9d2010-09-22 15:18:41 +100064 return exec.LookPath(s)
65}