-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcallback.go
68 lines (61 loc) · 1.55 KB
/
callback.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
package main
import (
"bytes"
"log"
"os/exec"
"strings"
"syscall"
)
// Run a shell command
// envs format is "a=1 b=c"
func RunCommand(envs string, dir string, command string, args ...string) (exitCode int, stdout string, stderr string) {
cmd := exec.Command(command, args...)
// parse envs
if envs != "" {
envList := strings.Fields(strings.TrimSpace(envs))
for _, env := range envList {
cmd.Env = append(cmd.Env, env)
}
}
// parse work directory
if dir != "" {
cmd.Dir = dir
}
log.Printf("cmd: %v", cmd)
var outbuf, errbuf bytes.Buffer
cmd.Stdout = &outbuf
cmd.Stderr = &errbuf
err := cmd.Run()
stdout = outbuf.String()
stderr = errbuf.String()
if err != nil {
// try to get the exit code
if exitError, ok := err.(*exec.ExitError); ok {
ws := exitError.Sys().(syscall.WaitStatus)
exitCode = ws.ExitStatus()
} else {
// This will happen (in OSX) if `name` is not available in $PATH,
// in this situation, exit code could not be get, and stderr will be
// empty string very likely, so we use the default fail code, and format err
// to string and set to stderr
exitCode = -1
if stderr == "" {
stderr = err.Error()
}
}
} else {
// success, exitCode should be 0
ws := cmd.ProcessState.Sys().(syscall.WaitStatus)
exitCode = ws.ExitStatus()
}
return exitCode, stdout, stderr
}
func RunSimpleCommand(command string) (int, string, string) {
split := strings.Fields(command)
l := len(split)
if l > 1 {
return RunCommand("", "", split[0], split[1:]...)
} else {
return RunCommand("", "", split[0])
}
}