-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
shell.go
90 lines (78 loc) · 1.98 KB
/
shell.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package shell
import (
"bytes"
"os"
"os/exec"
)
type Command struct {
command string
args []string
env []string
dir string
stdo, stde bytes.Buffer
}
func NewCommand(command string) *Command {
return &Command{
command: command,
env: os.Environ(),
}
}
func (c *Command) Dir(dir string) {
c.dir = dir
}
func (c *Command) Env(name string, value string) {
c.env = append(c.env, name+"="+value)
}
func (c *Command) Run() error {
cmd := exec.Command(c.command, c.args...)
if c.dir != "" {
cmd.Dir = c.dir
}
cmd.Stdout = &c.stdo
cmd.Stderr = &c.stde
return cmd.Run()
}
func (c *Command) Stdout() string {
return c.stdo.String()
}
func (c *Command) Stderr() string {
return c.stde.String()
}
func (c *Command) AddArgs(args []string) {
for _, arg := range args {
c.args = append(c.args, arg)
}
}
// CreateCommand returns a *Cmd struct that when run, will run the given command + args in the given directory
func CreateCommand(directory string, command string, args ...string) *exec.Cmd {
cmd := exec.Command(command, args...)
cmd.Dir = directory
return cmd
}
// RunCommand will run the given command + args in the given directory
// Will return stdout, stderr and error
func RunCommand(directory string, command string, args ...string) (string, string, error) {
cmd := CreateCommand(directory, command, args...)
var stdo, stde bytes.Buffer
cmd.Stdout = &stdo
cmd.Stderr = &stde
err := cmd.Run()
return stdo.String(), stde.String(), err
}
// RunCommandVerbose will run the given command + args in the given directory
// Will return an error if one occurs
func RunCommandVerbose(directory string, command string, args ...string) error {
cmd := CreateCommand(directory, command, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
return err
}
// CommandExists returns true if the given command can be found on the shell
func CommandExists(name string) bool {
_, err := exec.LookPath(name)
if err != nil {
return false
}
return true
}