-
Notifications
You must be signed in to change notification settings - Fork 30
/
print.go
61 lines (51 loc) · 1.1 KB
/
print.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
package cmd
import (
"io"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
func printCmd() *cobra.Command {
cmd := cobra.Command{
Use: "print",
Short: "Print a selected snippet.",
Long: "Print will display the details of the corresponding command block based on its name.",
Args: cobra.ExactArgs(1),
ValidArgsFunction: validCmdNames,
RunE: func(cmd *cobra.Command, args []string) error {
blocks, err := getCodeBlocks()
if err != nil {
return err
}
block, err := lookupCodeBlock(blocks, args[0])
if err != nil {
return err
}
w := bulkWriter{
Writer: cmd.OutOrStdout(),
}
w.Write([]byte(block.Content()))
w.Write([]byte{'\n'})
return errors.Wrap(w.Err(), "failed to write to stdout")
},
}
return &cmd
}
type bulkWriter struct {
io.Writer
n int
err error
}
func (w *bulkWriter) Err() error {
return w.err
}
func (w *bulkWriter) Result() (int, error) {
return w.n, w.err
}
func (w *bulkWriter) Write(p []byte) {
if w.err != nil {
return
}
n, err := w.Writer.Write(p)
w.n += n
w.err = err
}