forked from ghemawat/stream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
55 lines (53 loc) · 1.13 KB
/
command.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
package stream
import (
"fmt"
"os/exec"
"sync"
)
// Command executes "command args...".
//
// The filter's input items are fed as standard input to the command,
// one line per input item. The standard output of the command is
// split into lines and the lines form the output of the filter (with
// trailing newlines removed).
func Command(command string, args ...string) Filter[string] {
return FilterFunc[string](func(arg Arg[string]) error {
cmd := exec.Command(command, args...)
input, err := cmd.StdinPipe()
if err != nil {
return err
}
output, err := cmd.StdoutPipe()
if err != nil {
return err
}
if err := cmd.Start(); err != nil {
return err
}
var ierr error // Records error writing to command input
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for s := range arg.In {
_, ierr = fmt.Fprintln(input, s)
if ierr != nil {
input.Close()
return
}
}
ierr = input.Close()
}()
if err := splitIntoLines(output, arg); err != nil {
wg.Wait()
cmd.Wait()
return err
}
err = cmd.Wait()
wg.Wait()
if err != nil {
return err
}
return ierr
})
}