-
Notifications
You must be signed in to change notification settings - Fork 30
/
print.go
77 lines (63 loc) · 1.46 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package cmd
import (
"io"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/stateful/runme/internal/project"
)
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 {
proj, err := getProject()
if err != nil {
return err
}
generateBlocks:
blocks, err := loadTasks(proj, cmd.OutOrStdout(), cmd.InOrStdin(), true)
if err != nil {
return err
}
fileBlock, err := lookupCodeBlockWithPrompt(cmd, args[0], blocks)
if err != nil {
if project.IsCodeBlockNotFoundError(err) && !fAllowUnnamed {
fAllowUnnamed = true
goto generateBlocks
}
return err
}
block := fileBlock.Block
w := bulkWriter{
Writer: cmd.OutOrStdout(),
}
w.Write([]byte(block.Value()))
w.Write([]byte{'\n'})
return errors.Wrap(w.Err(), "failed to write to stdout")
},
}
setDefaultFlags(&cmd)
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
}