/
run.go
268 lines (232 loc) · 5.56 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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package project
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"log"
"net"
"os/exec"
"path/filepath"
"strings"
"sync"
"github.com/igorhub/devcard"
)
type UpdateMessage interface{ updateMessage() }
type MsgReady struct{}
type MsgError struct {
Title string
Err error
}
type MsgInfo struct {
Title string
}
type MsgCell struct {
Id string
Cell devcard.Cell
}
const (
PipeStdout = "Stdout"
PipeStderr = "Stderr"
)
type MsgPipeOut struct {
Pipe string
Line string
}
func (MsgReady) updateMessage() {}
func (MsgError) updateMessage() {}
func (MsgInfo) updateMessage() {}
func (MsgCell) updateMessage() {}
func (MsgPipeOut) updateMessage() {}
// Run uses "go run" to produce and return a devcard.
//
// If errors occur, they're written into devcard.Error field of the devcard.
func (r *Repo) Run(ctx context.Context, control <-chan string, updates chan<- UpdateMessage) {
r.runLock.Lock()
defer r.runLock.Unlock()
defer close(updates)
err := r.Prepare()
if err != nil {
updates <- MsgReady{}
updates <- MsgError{Title: "Failed to prepare the repo", Err: err}
return
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
listener, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
updates <- MsgReady{}
updates <- MsgError{Title: "Failed to create TCP listener", Err: err}
return
}
defer listener.Close()
wg := sync.WaitGroup{}
go func() {
conn, err := listener.Accept()
if err != nil && errors.Is(err, net.ErrClosed) {
return
} else if err != nil {
updates <- MsgReady{}
updates <- MsgError{Title: "Failed to accept TCP connection from the devcard", Err: err}
cancel()
return
}
defer conn.Close()
updates <- MsgReady{}
go func() {
wg.Add(1)
defer wg.Done()
r := bufio.NewReader(conn)
for {
s, err := r.ReadString('\n')
if err != nil && errors.Is(err, io.EOF) {
return
} else if err != nil {
log.Printf("Failed to read from the devcard's TCP connection: %s\n%#v", err, err)
updates <- MsgError{Title: "Failed to read from the devcard's TCP connection", Err: err}
cancel()
return
}
updates <- unmarshalDevcardMessage(s)
}
}()
for {
select {
case <-ctx.Done():
_, err := conn.Write([]byte("exit\n"))
if err != nil {
log.Println("Error writing \"exit\" to conn:", err)
}
conn.Close()
return
case s, ok := <-control:
if ok {
_, err := conn.Write([]byte(s + "\n"))
if err != nil {
log.Printf("Error writing %q to conn: %s", s, err)
cancel()
return
}
}
}
}
}()
cmd := exec.CommandContext(ctx, "go", "run", ".", r.Dir, listener.Addr().String())
cmd.Dir = filepath.Join(r.Dir, FindMainDir(r.DevcardInfo))
stdout, err := cmd.StdoutPipe()
if err != nil {
updates <- MsgReady{}
updates <- MsgError{Title: "Failed to create stdout pipe", Err: err}
return
}
stderr, err := cmd.StderrPipe()
if err != nil {
updates <- MsgReady{}
updates <- MsgError{Title: "Failed to create stderr pipe", Err: err}
return
}
stderrC := readFromPipe(stderr, PipeStderr)
stdoutC := readFromPipe(stdout, PipeStdout)
wg.Add(2)
go func() {
for msg := range stdoutC {
updates <- msg
}
wg.Done()
}()
go func() {
for msg := range stderrC {
updates <- msg
}
wg.Done()
}()
err = cmd.Run()
if err != nil {
err := fmt.Errorf("go run: %w", err)
updates <- MsgError{Title: "Execution failure", Err: err}
}
wg.Wait()
}
func readFromPipe(pipe io.Reader, pipeName string) <-chan UpdateMessage {
updates := make(chan UpdateMessage)
go func() {
defer close(updates)
var initialized bool
r := bufio.NewReader(pipe)
for {
line, err := r.ReadString('\n')
if err == io.EOF || errors.Is(err, fs.ErrClosed) {
break
}
if err != nil {
updates <- MsgError{Title: "Failed to read from devcard's " + pipeName, Err: err}
break
}
if !initialized {
updates <- MsgReady{}
initialized = true
}
updates <- MsgPipeOut{Pipe: pipeName, Line: line}
}
}()
return updates
}
func unmarshalDevcardMessage(msg string) UpdateMessage {
x := struct {
MsgType string `json:"msg_type"`
// Cell type
Id string
CellType string `json:"cell_type"`
Cell json.RawMessage
// Info type
Title string
}{}
err := json.Unmarshal([]byte(msg), &x)
if err != nil {
err = fmt.Errorf("error: %s\n\nmessage: %s", err, msg)
return MsgError{Title: "Failed to decode message from the devcard", Err: err}
}
switch x.MsgType {
case devcard.MessageTypeCell:
cell, err := devcard.UnmarshalCell(x.CellType, x.Cell)
if err != nil {
err = fmt.Errorf("error: %s\n\ncell type: %s\n\ncell: %s", err, x.CellType, string(x.Cell))
return MsgError{Title: "Failed to decode a cell from the devcard", Err: err}
}
return MsgCell{Id: x.Id, Cell: cell}
case devcard.MessageTypeInfo:
return MsgInfo{
Title: x.Title,
}
case devcard.MessageTypeError:
return MsgError{
Title: "Internal error",
Err: fmt.Errorf("message type %q is not supported", x.MsgType),
}
default:
return MsgError{
Title: "Internal error: malformed message from the devcard",
Err: fmt.Errorf("message type %q is not supported", x.MsgType),
}
}
}
func (r *Repo) Test(ctx context.Context) int {
r.runLock.Lock()
defer r.runLock.Unlock()
cmd := exec.CommandContext(ctx, "go", "test", r.DevcardInfo.ImportPath)
cmd.Dir = r.Dir
b, err := cmd.CombinedOutput()
if err == nil {
return 0
}
failedTests := 0
for _, line := range strings.Split(string(b), "\n") {
if strings.HasPrefix(line, "--- FAIL:") {
failedTests++
}
}
return failedTests
}