forked from alexellis/go-execute
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexec.go
More file actions
103 lines (82 loc) · 1.76 KB
/
Copy pathexec.go
File metadata and controls
103 lines (82 loc) · 1.76 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package execute
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"strings"
)
type ExecTask struct {
Command string
Args []string
Shell bool
Env []string
Cwd string
}
type ExecResult struct {
Stdout string
Stderr string
ExitCode int
}
func (et ExecTask) Execute() (ExecResult, error) {
argsSt := ""
if len(et.Args) > 0 {
argsSt = strings.Join(et.Args, " ")
}
fmt.Println("exec: ", et.Command, argsSt)
var cmd *exec.Cmd
if et.Shell {
args := []string{"-c", et.Command}
cmd = exec.Command("/bin/bash", args...)
} else {
if strings.Index(et.Command, " ") > 0 {
parts := strings.Split(et.Command, " ")
command := parts[0]
args := parts[1:]
cmd = exec.Command(command, args...)
} else {
cmd = exec.Command(et.Command, et.Args...)
}
}
cmd.Dir = et.Cwd
if len(et.Env) > 0 {
cmd.Env = os.Environ()
for _, env := range et.Env {
cmd.Env = append(cmd.Env, env)
}
}
stdoutPipe, stdoutPipeErr := cmd.StdoutPipe()
if stdoutPipeErr != nil {
return ExecResult{}, stdoutPipeErr
}
stderrPipe, stderrPipeErr := cmd.StderrPipe()
if stderrPipeErr != nil {
return ExecResult{}, stderrPipeErr
}
startErr := cmd.Start()
if startErr != nil {
return ExecResult{}, startErr
}
stdoutBytes, err := ioutil.ReadAll(stdoutPipe)
if err != nil {
return ExecResult{}, err
}
stderrBytes, err := ioutil.ReadAll(stderrPipe)
if err != nil {
return ExecResult{}, err
}
res := ExecResult{
Stdout: string(stdoutBytes),
Stderr: string(stderrBytes),
}
execErr := cmd.Wait()
if execErr != nil {
if exitError, ok := err.(*exec.ExitError); ok {
res.ExitCode = exitError.ExitCode()
}
fmt.Println("res: " + string(stderrBytes))
return res, execErr
}
fmt.Println("res: " + string(stdoutBytes))
return res, nil
}