-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcmd.go
49 lines (44 loc) · 1.05 KB
/
cmd.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
package wasp
import (
"bufio"
"io"
"os/exec"
"strings"
"github.com/rs/zerolog/log"
)
// ExecCmd executes os command, logging both streams
func ExecCmd(command string) error {
return ExecCmdWithStreamFunc(command, func(m string) {
log.Info().Str("Text", m).Msg("Command output")
})
}
// readStdPipe continuously read a pipe from the command
func readStdPipe(pipe io.ReadCloser, streamFunc func(string)) {
scanner := bufio.NewScanner(pipe)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
m := scanner.Text()
if streamFunc != nil {
streamFunc(m)
}
}
}
// ExecCmdWithStreamFunc executes command with stream function
func ExecCmdWithStreamFunc(command string, outputFunction func(string)) error {
c := strings.Split(command, " ")
cmd := exec.Command(c[0], c[1:]...)
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
if err := cmd.Start(); err != nil {
return err
}
go readStdPipe(stderr, outputFunction)
go readStdPipe(stdout, outputFunction)
return cmd.Wait()
}