/
scanner.go
67 lines (60 loc) · 1.54 KB
/
scanner.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
package pipe
import (
"bufio"
"context"
"io"
)
// Scanner defines the interface (which is implemented by
// `bufio.Scanner`) that is needed by `AddScannerFunction()`. See
// `bufio.Scanner` for how these methods should behave.
type Scanner interface {
Scan() bool
Bytes() []byte
Err() error
}
// NewScannerFunc is used to create a `Scanner` for scanning input
// that is coming from `r`.
type NewScannerFunc func(r io.Reader) (Scanner, error)
// ScannerFunction creates a function-based `Stage`. The function will
// be passed input, one line at a time, and may emit output. See the
// definition of `LinewiseStageFunc` for more information.
func ScannerFunction(
name string, newScanner NewScannerFunc, f LinewiseStageFunc,
) Stage {
return Function(
name,
func(ctx context.Context, env Env, stdin io.Reader, stdout io.Writer) (theErr error) {
scanner, err := newScanner(stdin)
if err != nil {
return err
}
var out *bufio.Writer
if stdout != nil {
out = bufio.NewWriter(stdout)
defer func() {
err := out.Flush()
if err != nil && theErr == nil {
// Note: this sets the named return value,
// thereby causing the whole stage to report
// the error.
theErr = err
}
}()
}
for scanner.Scan() {
if ctx.Err() != nil {
return ctx.Err()
}
err := f(ctx, env, scanner.Bytes(), out)
if err != nil {
return err
}
}
if err := scanner.Err(); err != nil {
return err
}
return nil
// `p.AddFunction()` arranges for `stdout` to be closed.
},
)
}