-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommand.go
71 lines (63 loc) · 1.2 KB
/
command.go
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
66
67
68
69
70
71
package building
import (
"io"
"os"
"os/exec"
"path/filepath"
"strings"
)
type Command struct {
name string
dir string
env []string
output io.Writer
success bool
}
func (b *B) MakeCommand(name string, args ...string) Command {
c := Command{
name: name,
}
if len(args) > 0 {
c.Run(args...)
}
return c
}
func (c Command) WithDir(dir string) Command {
dir = filepath.Clean(dir)
if filepath.IsAbs(dir) {
b.Fatalln("dir must be relative", dir)
}
if strings.Contains(dir, "..") {
b.Fatalln("dir must be a folder under project root", dir)
}
c.dir = dir
return c
}
func (c Command) WithEnv(env ...string) Command {
c.env = append(c.env, env...)
return c
}
func (c Command) WithOutput(w io.Writer) Command {
c.output = w
return c
}
func (c Command) WithSuccess() Command {
c.success = true
return c
}
func (c Command) Run(args ...string) int {
b.Println("running", append([]string{c.name}, args...))
if c.output == nil {
c.output = os.Stdout
}
cmd := exec.Command(c.name, args...)
cmd.Dir = c.dir
cmd.Env = append(os.Environ(), c.env...)
cmd.Stderr = os.Stderr
cmd.Stdout = c.output
code, err := run(cmd, c.success)
if err != nil {
b.Fatalln(err)
}
return code
}