-
Notifications
You must be signed in to change notification settings - Fork 147
/
exec.go
75 lines (62 loc) · 1.4 KB
/
exec.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
package utils
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"os/exec"
"sync"
)
// Change terminal colors
const colorReset = "\x1b[0m"
const colorGreen = "\x1b[32;1m"
const colorCyan = "\x1b[36;1m"
const colorWhite = "\x1b[37;1m"
//nolint
func ExecCommand(showLogs bool, envVariables []string, commandName string, args ...string) (string, error) {
if showLogs {
fmt.Println()
fmt.Printf("%s", colorGreen)
fmt.Print(commandName + " ")
fmt.Printf("%s", colorCyan)
fmt.Printf("%v", args)
fmt.Printf("%s", colorWhite)
fmt.Printf("%s", colorReset)
fmt.Println("")
}
cmd := exec.Command(commandName, args...)
env := os.Environ()
if envVariables != nil {
env = append(env, envVariables...)
}
cmd.Env = env
var stdoutBuf, stderrBuf bytes.Buffer
stdoutIn, _ := cmd.StdoutPipe()
stderrIn, _ := cmd.StderrPipe()
var errStdout, errStderr error
stdout := io.MultiWriter(os.Stdout, &stdoutBuf)
stderr := io.MultiWriter(os.Stderr, &stderrBuf)
if err := cmd.Start(); err != nil {
return "", err
}
if showLogs {
var wg sync.WaitGroup
wg.Add(1)
go func() {
_, errStdout = io.Copy(stdout, stdoutIn)
wg.Done()
}()
_, errStderr = io.Copy(stderr, stderrIn)
wg.Wait()
}
if err := cmd.Wait(); err != nil {
return "", err
}
if showLogs {
if errStdout != nil || errStderr != nil {
return "", errors.New("unable to capture stdOut or stdErr")
}
}
return stdoutBuf.String(), nil
}