summaryrefslogtreecommitdiff
path: root/misc/dashboard/builder/exec.go
blob: 6236c915a5e882149651245ecd21f646dc340b05 (plain)
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main

import (
	"bytes"
	"exec"
	"io"
	"os"
	"strings"
)

// run is a simple wrapper for exec.Run/Close
func run(envv []string, dir string, argv ...string) os.Error {
	bin, err := pathLookup(argv[0])
	if err != nil {
		return err
	}
	p, err := exec.Run(bin, argv, envv, dir,
		exec.DevNull, exec.DevNull, exec.PassThrough)
	if err != nil {
		return err
	}
	return p.Close()
}

// runLog runs a process and returns the combined stdout/stderr, 
// as well as writing it to logfile (if specified).
func runLog(envv []string, logfile, dir string, argv ...string) (output string, exitStatus int, err os.Error) {
	bin, err := pathLookup(argv[0])
	if err != nil {
		return
	}
	p, err := exec.Run(bin, argv, envv, dir,
		exec.DevNull, exec.Pipe, exec.MergeWithStdout)
	if err != nil {
		return
	}
	defer p.Close()
	b := new(bytes.Buffer)
	var w io.Writer = b
	if logfile != "" {
		f, err := os.Open(logfile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
		if err != nil {
			return
		}
		defer f.Close()
		w = io.MultiWriter(f, b)
	}
	_, err = io.Copy(w, p.Stdout)
	if err != nil {
		return
	}
	wait, err := p.Wait(0)
	if err != nil {
		return
	}
	return b.String(), wait.WaitStatus.ExitStatus(), nil
}

// Find bin in PATH if a relative or absolute path hasn't been specified
func pathLookup(s string) (string, os.Error) {
	if strings.HasPrefix(s, "/") || strings.HasPrefix(s, "./") || strings.HasPrefix(s, "../") {
		return s, nil
	}
	return exec.LookPath(s)
}