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 helper
import (
"fmt"
"io"
"os"
"os/exec"
"syscall"
)
// Command encapsulates operations with commands creates with NewCommand
type Command struct {
io.Reader
*exec.Cmd
}
// Kill cleans the subprocess group of the command. Callers should defer a call
// to kill after they get the command from NewCommand
func (c *Command) Kill() {
CleanUpProcessGroup(c.Cmd)
}
// GitCommandReader creates a git Command with the given args
func GitCommandReader(args ...string) (*Command, error) {
return NewCommand(exec.Command("git", args...), nil, nil, nil)
}
// NewCommand creates a Command from an exec.Cmd
func NewCommand(cmd *exec.Cmd, stdin io.Reader, stdout, stderr io.Writer, env ...string) (*Command, error) {
command := &Command{Cmd: cmd}
// Explicitly set the environment for the command
cmd.Env = []string{
fmt.Sprintf("HOME=%s", os.Getenv("HOME")),
fmt.Sprintf("PATH=%s", os.Getenv("PATH")),
fmt.Sprintf("LD_LIBRARY_PATH=%s", os.Getenv("LD_LIBRARY_PATH")),
}
cmd.Env = append(cmd.Env, env...)
// Start the command in its own process group (nice for signalling)
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if stdin != nil {
cmd.Stdin = stdin
}
if stdout != nil {
// We don't assign a reader if an stdout override was passed. We assume
// output is going to be directly handled by the caller.
cmd.Stdout = stdout
} else {
pipe, err := cmd.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("GitCommand: stdout: %v", err)
}
command.Reader = pipe
}
if stderr != nil {
cmd.Stderr = stderr
} else {
// If we don't do something with cmd.Stderr, Git errors will be lost
cmd.Stderr = os.Stderr
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("start %v: %v", cmd.Args, err)
}
return command, nil
}
// CleanUpProcessGroup will send a SIGTERM signal to the process group
// belonging to the `cmd` process
func CleanUpProcessGroup(cmd *exec.Cmd) {
if cmd == nil {
return
}
process := cmd.Process
if process != nil && process.Pid > 0 {
// Send SIGTERM to the process group of cmd
syscall.Kill(-process.Pid, syscall.SIGTERM)
}
// reap our child process
cmd.Wait()
}
// ExitStatus will return the exit-code from an error
func ExitStatus(err error) (int, bool) {
exitError, ok := err.(*exec.ExitError)
if !ok {
return 0, false
}
waitStatus, ok := exitError.Sys().(syscall.WaitStatus)
if !ok {
return 0, false
}
return waitStatus.ExitStatus(), true
}
|