-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.go
132 lines (111 loc) · 2.22 KB
/
run.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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package main
import (
"bufio"
"io"
"os"
"os/exec"
"strings"
"syscall"
)
type RunningStatus int
const (
success RunningStatus = 0
stopped RunningStatus = 1
failure RunningStatus = 2
)
func printFromReader(
reader *io.ReadCloser,
print func(string),
status *RunningStatus,
) {
scannerErr := bufio.NewScanner(*reader)
for scannerErr.Scan() {
print(scannerErr.Text())
if status != nil {
*status = failure
}
}
}
func interruptProcess(cmd *exec.Cmd) {
err := cmd.Process.Signal(os.Interrupt)
if err != nil {
Crash(err)
}
err = cmd.Process.Signal(syscall.SIGINT)
if err != nil {
Crash(err)
}
err = cmd.Process.Kill()
if err != nil {
Crash(err)
}
if pgid, err := syscall.Getpgid(cmd.Process.Pid); err == nil {
syscall.Kill(-pgid, 15)
} else {
Crash(err)
}
}
func listenForStop(
cmd *exec.Cmd,
stopSignal chan bool,
status *RunningStatus,
) {
isStop := <-stopSignal
if isStop {
*status = stopped
interruptProcess(cmd)
}
}
func Run(executor string, stringCmd string, stopSignal chan bool) RunningStatus {
executionStatus := success
cmd := exec.Command(executor, "-c", stringCmd)
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
stdout, _ := cmd.StdoutPipe()
stderr, _ := cmd.StderrPipe()
cmd.Start()
go listenForStop(cmd, stopSignal, &executionStatus)
go printFromReader(&stdout, PrintStdIn, nil)
go printFromReader(&stderr, PrintStrErr, nil)
err := cmd.Wait()
if err != nil {
PrintError(
"Error during execution of %v: %v",
stringCmd,
err,
)
executionStatus = failure
}
Notify(stopSignal, false)
return executionStatus
}
func RunAll(
arg string,
isWatch bool,
config Config,
actions map[string][]string,
) func(stopSignal chan bool) {
return func(stopSignal chan bool) {
for _, cmdStr := range actions[arg] {
PrintAction(cmdStr)
}
cmd := strings.Join(actions[arg], "; ")
switch executionStatus := Run(config.engine, cmd, stopSignal); executionStatus {
case failure:
PrintError(
"Command '%v' is interrupted due to error",
arg,
)
if isWatch == false {
os.Exit(1)
}
return
case stopped:
return
case success:
}
PrintInfo("Action '%v' is finished.", arg)
if isWatch {
PrintInfo("Watching for new changes...")
}
}
}