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.
( name string, newScanner NewScannerFunc, f LinewiseStageFunc, )
| 23 | // be passed input, one line at a time, and may emit output. See the |
| 24 | // definition of `LinewiseStageFunc` for more information. |
| 25 | func ScannerFunction( |
| 26 | name string, newScanner NewScannerFunc, f LinewiseStageFunc, |
| 27 | ) Stage { |
| 28 | return Function( |
| 29 | name, |
| 30 | func(ctx context.Context, env Env, stdin io.Reader, stdout io.Writer) (theErr error) { |
| 31 | scanner, err := newScanner(stdin) |
| 32 | if err != nil { |
| 33 | return err |
| 34 | } |
| 35 | |
| 36 | var out *bufio.Writer |
| 37 | if stdout != nil { |
| 38 | out = bufio.NewWriter(stdout) |
| 39 | defer func() { |
| 40 | err := out.Flush() |
| 41 | if err != nil && theErr == nil { |
| 42 | // Note: this sets the named return value, |
| 43 | // thereby causing the whole stage to report |
| 44 | // the error. |
| 45 | theErr = err |
| 46 | } |
| 47 | }() |
| 48 | } |
| 49 | |
| 50 | for scanner.Scan() { |
| 51 | if ctx.Err() != nil { |
| 52 | return ctx.Err() |
| 53 | } |
| 54 | err := f(ctx, env, scanner.Bytes(), out) |
| 55 | if err != nil { |
| 56 | return err |
| 57 | } |
| 58 | } |
| 59 | if err := scanner.Err(); err != nil { |
| 60 | return err |
| 61 | } |
| 62 | |
| 63 | return nil |
| 64 | // `p.AddFunction()` arranges for `stdout` to be closed. |
| 65 | }, |
| 66 | ) |
| 67 | } |