/
inout.go
70 lines (60 loc) · 1.4 KB
/
inout.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
import (
"context"
"io"
"io/ioutil"
"github.com/spf13/cobra"
)
type outCommand interface {
Run(ctx context.Context, args []string) ([]byte, error)
}
type inOutCommand interface {
Run(ctx context.Context, in []byte, args []string) ([]byte, error)
}
func runOut(cmd outCommand) func(cobraCmd *cobra.Command, args []string) error {
return func(cobraCmd *cobra.Command, args []string) error {
cobraCmd.SilenceUsage = true
out, err := cmd.Run(cobraCmd.Context(), args)
if err != nil {
return err
}
if _, err := cobraCmd.OutOrStdout().Write(out); err != nil {
return err
}
return nil
}
}
func runInOut(cmd inOutCommand) func(cobraCmd *cobra.Command, args []string) error {
return func(cobraCmd *cobra.Command, args []string) error {
cobraCmd.SilenceUsage = true
in, err := readAll(cobraCmd.Context(), cobraCmd.InOrStdin())
if err != nil {
return err
}
out, err := cmd.Run(cobraCmd.Context(), in, args)
if err != nil {
return err
}
if _, err := cobraCmd.OutOrStdout().Write(out); err != nil {
return err
}
return nil
}
}
func readAll(ctx context.Context, r io.Reader) ([]byte, error) {
type result struct {
in []byte
err error
}
resultCh := make(chan result, 1)
go func() {
in, err := ioutil.ReadAll(r)
resultCh <- result{in: in, err: err}
}()
select {
case r := <-resultCh:
return r.in, r.err
case <-ctx.Done():
return nil, ctx.Err()
}
}