-
Notifications
You must be signed in to change notification settings - Fork 0
/
commands.go
74 lines (60 loc) · 1.81 KB
/
commands.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
package goutils
import (
"bytes"
"errors"
"io"
"os"
"os/exec"
"syscall"
)
// SpawnCommand runs a command. It will show the output if 'quiet' is true, otherwise,
// it won't show anything.
func SpawnCommand(workingDir, cmdStr string) error {
cmd := exec.Command("bash", "-c", cmdStr)
cmd.Dir = workingDir
var stdout, stderr bytes.Buffer
cmd.Stdout = io.MultiWriter(os.Stdout, &stdout)
cmd.Stderr = io.MultiWriter(os.Stderr, &stderr)
return cmd.Run()
}
// ExecCommand runs a command and shows its output. It's going to start the command and give
// control to that process, so if we, say, do Ctrl+C, we're basically existing from the whole
// application and we won't return to our original process.
func ExecCommand(workingDir, cmd string) error {
bash, err := exec.LookPath("bash")
if err != nil {
return err
}
if err := syscall.Chdir(workingDir); err != nil {
return err
}
return syscall.Exec(bash, []string{"bash", "-c", cmd}, os.Environ())
}
// RunCommand runs a shell command as a subprocess and returns its output.
func RunCommand(cmdString string) (string, error) {
cmd := exec.Command("bash", "-c", cmdString)
combined, err := cmd.CombinedOutput()
if err != nil {
return "", errors.New(string(combined))
}
return string(combined), nil
}
// StartCommand uses StartProcess to start a command. It's going to start the command, but the
// "control" is still in the calling process, so when the command finishes, we return back
// to our original process.
func StartCommand(workingDir, cmdStr string) error {
bash, err := exec.LookPath("bash")
if err != nil {
return err
}
var attr os.ProcAttr
attr.Files = []*os.File{
os.Stdin,
os.Stderr,
os.Stdout,
}
attr.Dir = workingDir
proc, err := os.StartProcess(bash, []string{"bash", "-c", cmdStr}, &attr)
proc.Wait()
return err
}