/
pipecommand.go
70 lines (58 loc) · 1.54 KB
/
pipecommand.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
package main
// utility class that helps to wrap a command line tool into a pipe-like structure
import (
"io"
"os/exec"
)
type pipeCommandReader struct {
cmd *exec.Cmd
pipe io.ReadCloser
}
func (r pipeCommandReader) Read(p []byte) (n int, err error) {
return r.pipe.Read(p)
}
func (r pipeCommandReader) Close() error {
_ = r.pipe.Close()
return r.cmd.Wait()
}
// newPipeCommandReader creates a new pipe command
// r becomes STDIN for the command
// the function returns a reader that contains information from the command STDOUT
func newPipeCommandReader(r io.Reader, app string, args ...string) (io.ReadCloser, error) {
cmd := exec.Command(app, args...)
cmd.Stdin = r
pipe, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, err
}
return pipeCommandReader{cmd, pipe}, nil
}
type pipeCommandWriter struct {
cmd *exec.Cmd
pipe io.WriteCloser
}
func (w pipeCommandWriter) Write(p []byte) (n int, err error) {
return w.pipe.Write(p)
}
func (w pipeCommandWriter) Close() error {
_ = w.pipe.Close()
return w.cmd.Wait()
}
// newPipeCommandWriter creates a new pipe command
// w becomes STDOUT for the command
// the function returns a writer that becomes STDIN for the command
func newPipeCommandWriter(w io.Writer, app string, args ...string) (io.WriteCloser, error) {
cmd := exec.Command(app, args...)
cmd.Stdout = w
pipe, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, err
}
return pipeCommandWriter{cmd, pipe}, nil
}