-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor.go
More file actions
100 lines (85 loc) · 1.84 KB
/
Copy pathexecutor.go
File metadata and controls
100 lines (85 loc) · 1.84 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
package executor
import (
"fmt"
"io"
"github.com/go-cmd/cmd"
"github.com/google/shlex"
)
type Executor struct {
State *state `json:"state"`
StateCh chan struct{} `json:"stateCh"`
StopCh chan struct{} `json:"stopCh"`
}
type state struct {
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
Error error `json:"error"`
IsRunning bool `json:"isRunning"`
}
func (e *Executor) Run(stdin io.Reader, stdout io.Writer, stderr io.Writer, script string) (chan struct{}, error) {
e.resetState()
e.State.IsRunning = true
frags, err := shlex.Split(script)
if err != nil {
return nil, err
}
c := cmd.NewCmdOptions(cmd.Options{
Buffered: false,
Streaming: true,
}, frags[0], frags[1:]...)
finStatusCh := c.StartWithStdin(stdin)
stdioStatusCh := make(chan struct{})
go func() {
defer close(stdioStatusCh)
for c.Stdout != nil || c.Stderr != nil {
select {
case line, open := <-c.Stdout:
if !open {
c.Stdout = nil
continue
}
e.State.Stdout = fmt.Sprintln(e.State.Stdout, line)
fmt.Fprintln(stdout, line)
case line, open := <-c.Stderr:
if !open {
c.Stderr = nil
continue
}
e.State.Stderr = fmt.Sprintln(e.State.Stderr, line)
fmt.Fprintln(stderr, line)
}
e.StateCh <- struct{}{}
}
}()
go func() {
select {
case <-e.StopCh:
c.Stop()
case <-stdioStatusCh:
}
}()
finishedCh := make(chan struct{})
go func() {
finalStatus := <-finStatusCh
e.State.Error = finalStatus.Error
<-stdioStatusCh
e.State.IsRunning = false
e.StateCh <- struct{}{}
close(finishedCh)
}()
return finishedCh, nil
}
func NewExecutor() Executor {
return Executor{
StateCh: make(chan struct{}),
StopCh: make(chan struct{}),
}
}
func (e *Executor) resetState() {
e.State = &state{
Stdout: "",
Stderr: "",
Error: nil,
IsRunning: false,
}
}