-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipc.go
107 lines (96 loc) · 2.1 KB
/
ipc.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
package ipc
import (
"bufio"
"encoding/json"
"os/exec"
)
type Request struct {
Kind string
Data interface{}
}
type Response struct {
Kind string
Data json.RawMessage
}
// NewCommand starts a new IPC command.
func NewCommand(args ...string) (stdin chan Request, stdout chan Response, stderr chan string, err error) {
cmd := exec.Command(args[0], args[1:]...)
stdinPipe, err := cmd.StdinPipe()
if err != nil {
return nil, nil, nil, err
}
stdoutPipe, err := cmd.StdoutPipe()
if err != nil {
return nil, nil, nil, err
}
stderrPipe, err := cmd.StderrPipe()
if err != nil {
return nil, nil, nil, err
}
stdin = make(chan Request)
go func() {
defer stdinPipe.Close()
for msg := range stdin {
bstr, err := json.Marshal(msg)
if err != nil {
panic(err)
}
// Add an EOF so 'await stdin()' can process
stdinPipe.Write(append(bstr, '\n'))
}
}()
stdout = make(chan Response)
go func() {
defer func() {
stdoutPipe.Close()
close(stdout)
}()
// Increase the buffer
scanner := bufio.NewScanner(stdoutPipe)
buf := make([]byte, 1024*1024)
scanner.Buffer(buf, len(buf))
for scanner.Scan() {
// var res Response
// if err := json.Unmarshal(scanner.Bytes(), &res); err != nil {
// panic(err)
// }
// stdout <- res
if bstr := scanner.Bytes(); len(bstr) > 0 {
var res Response
if err := json.Unmarshal(bstr, &res); err != nil {
panic(err)
}
stdout <- res
}
}
if err := scanner.Err(); err != nil {
panic(err)
}
}()
stderr = make(chan string)
go func() {
defer func() {
stderrPipe.Close()
close(stderr)
}()
// Read from start-to-end
// https://golang.org/pkg/bufio/#SplitFunc
scanner := bufio.NewScanner(stderrPipe)
scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
return len(data), data, nil
})
for scanner.Scan() {
if str := scanner.Text(); str != "" {
stderr <- str
}
}
if err := scanner.Err(); err != nil {
panic(err)
}
}()
// Start the command
if err := cmd.Start(); err != nil {
return nil, nil, nil, err
}
return stdin, stdout, stderr, nil
}