-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhandle_args.go
152 lines (133 loc) · 4.09 KB
/
handle_args.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package donothing
import (
"bytes"
"fmt"
"io"
"os"
"path"
"strings"
"text/template"
)
// DefaultCLI is a default CLI for do-nothing scripts.
type DefaultCLI struct {
ExecName string
Pcd *Procedure
DefaultStep string
// The place we'll write output to. Can be swapped out for testing.
out io.Writer
}
// Usage returns the usage message.
func (cli *DefaultCLI) Usage() string {
tplStr := `USAGE: {{.ExecName}} [options] {{if .DefaultStep}}[STEP_NAME]{{else}}STEP_NAME{{end}}
{{if .Pcd.GetShort -}}
{{.Pcd.GetShort}}
{{end -}}
OPTIONS:
--markdown Instead of executing the procedure, print its Markdown documentation to stdout
--help Print usage message`
//tpl := template.Must(template.New("usage").Parse(tplStr))
tpl, err := template.New("usage").Parse(tplStr)
if err != nil {
return err.Error()
}
var buf bytes.Buffer
if err := tpl.Execute(&buf, cli); err != nil {
return err.Error()
}
return buf.String()
}
// Run parses arguments and runs the appropriate actions.
//
// args is the content of os.Args.
func (cli *DefaultCLI) Run(args []string) error {
if len(args) <= 0 {
return fmt.Errorf("Must have at least 1 argument")
}
flags := make([]string, 0)
nonFlags := make([]string, 0)
for _, arg := range args[1:] {
if strings.IndexRune(arg, '-') == 0 {
flags = append(flags, arg)
} else {
nonFlags = append(nonFlags, arg)
}
}
for _, flag := range flags {
if flag == "-h" || flag == "--help" {
fmt.Fprintln(cli.out, cli.Usage())
return nil
}
}
// Keys of opts are valid flags. Any other flag is an error.
//
// At the end of this stanza, the value corresponding to each flag will be true iff the flag was
// passed.
opts := map[string]bool{
"--markdown": false,
}
for _, flag := range flags {
if _, ok := opts[flag]; ok {
opts[flag] = true
} else {
fmt.Fprintln(cli.out, cli.Usage())
return fmt.Errorf("Unknown flag '%s'", flag)
}
}
if len(nonFlags) == 0 && cli.DefaultStep == "" {
fmt.Fprintln(cli.out, cli.Usage())
return fmt.Errorf("Must specify STEP_NAME")
}
if len(nonFlags) > 1 {
fmt.Fprintln(cli.out, cli.Usage())
return fmt.Errorf("Extraneous arguments passed: %v", nonFlags[1:])
}
stepName := cli.DefaultStep
if len(nonFlags) >= 1 {
stepName = nonFlags[0]
}
if opts["--markdown"] {
return cli.Pcd.RenderStep(cli.out, stepName)
}
return cli.Pcd.ExecuteStep(stepName)
}
// NewDefaultCLI returns a DefaultCLI instance initialized with the given executable name.
//
// execName is the name of the executable that has imported donothing. pcd is the procedure to run
// actions against. defaultStep is the step to execute if the user doesn't specify STEP_NAME; if
// defaultStep is "", omission of STEP_NAME from the invocation will trigger an error.
func NewDefaultCLI(execName string, pcd *Procedure, defaultStep string) (*DefaultCLI, error) {
if pcd == nil {
return nil, fmt.Errorf("failed to initialize default CLI: procedure must not be nil")
}
if _, err := pcd.Check(); err != nil {
return nil, err
}
return &DefaultCLI{
ExecName: execName,
Pcd: pcd,
DefaultStep: defaultStep,
out: os.Stdout,
}, nil
}
// HandleArgs parses command line arguments and runs the appropriate actions.
//
// In other words, this function implements a default CLI for do-nothing scripts. Packages that
// import donothing may use this default CLI, or may implement their own CLI by directly calling
// Procedure.Execute, Procedure.Render, and so on.
//
// For details of this default CLI, see the documentation of DefaultCLI and its methods.
//
// args is the content of os.Args. pcd is the procedure to run actions against. defaultStep is the
// step to execute if the user doesn't specify STEP_NAME; if defaultStep is "", omission of
// STEP_NAME from the invocation will trigger an error.
func HandleArgs(args []string, pcd *Procedure, defaultStep string) error {
args = args[:]
if len(args) <= 0 {
return fmt.Errorf("Failed to determine executable name from arguments: args slice too short")
}
cli, err := NewDefaultCLI(path.Base(args[0]), pcd, defaultStep)
if err != nil {
return err
}
return cli.Run(args)
}