-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd.go
66 lines (58 loc) · 1.28 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package oslib
import (
"fmt"
"io"
"os/exec"
"sync"
"syscall"
)
// TODO: Find a way to make this safer/more secure.
func BashCmd(cmdStr string) *exec.Cmd {
return exec.Command("bash", "-c", cmdStr)
}
// TODO: Find a way to make this safer/more secure.
func BashCmdf(cmdStr string, args ...interface{}) *exec.Cmd {
return BashCmd(fmt.Sprintf(cmdStr, args...))
}
func AttachCmd(cmd *exec.Cmd, stdout io.Writer, stderr io.Writer, stdin io.Reader) (*sync.WaitGroup, error) {
var wg sync.WaitGroup
wg.Add(2)
stdinIn, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
stdoutOut, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderrOut, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
go func() {
io.Copy(stdinIn, stdin)
stdinIn.Close()
}()
go func() {
io.Copy(stdout, stdoutOut)
wg.Done()
}()
go func() {
io.Copy(stderr, stderrOut)
wg.Done()
}()
return &wg, nil
}
func ExitStatus(err error) (uint32, error) {
if err != nil {
if exiterr, ok := err.(*exec.ExitError); ok {
// There is no platform independent way to retrieve
// the exit code, but the following will work on Unix.
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
return uint32(status.ExitStatus()), nil
}
}
return 0, err
}
return 0, nil
}