-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.go
294 lines (235 loc) · 5.29 KB
/
command.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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package main
import (
"errors"
"fmt"
"io"
"os"
"reflect"
flag "github.com/ogier/pflag"
)
var (
ErrBadArgs = errors.New("bad args")
)
type Env struct {
Stdin io.Writer
Stdout io.Writer
Stderr io.Writer
LogTo io.Writer
}
type CommandSet struct {
Name string
commands []*Command
}
func NewCommandSet(name string, commands ...*Command) *CommandSet {
return &CommandSet{
Name: name,
commands: commands,
}
}
func (cs *CommandSet) Run(name string, args []string) error {
return cs.RunWithEnv(name, args, &Env{
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
})
}
func (cs *CommandSet) RunWithEnv(name string, args []string, env *Env) error {
c := cs.findByName(name)
if c == nil {
cs.Usage()
return errors.New("no such command " + name)
}
var help bool
fs := flag.NewFlagSet(name, flag.ContinueOnError)
fs.Usage = c.usage
fs.BoolVarP(&help, "help", "h", false, "Show this help page")
c.opts.addToFlagSet(fs)
err := fs.Parse(args)
if err != nil {
return err
}
if help {
c.usage()
return nil
}
err = c.run(c.opts, fs.Args(), env)
if err != nil {
if err == ErrBadArgs {
c.usage()
}
return err
}
return nil
}
func (cs *CommandSet) Usage() {
width := 0
marginLeft := 2
marginRight := 7
for _, c := range cs.commands {
if w := len(c.name); w > width {
width = w
}
}
fmt.Println("Usage:", cs.Name, "[command] [...]")
fmt.Println()
fmt.Println("Available Commands:")
for _, c := range cs.commands {
fmt.Printf("%*s%-*s %s\n", marginLeft, "", width+marginRight, c.name, c.desc)
}
fmt.Println()
fmt.Printf("Use \"%s <command> --help\" for help with individual commands.\n", cs.Name)
}
func (cs *CommandSet) findByName(name string) *Command {
for _, c := range cs.commands {
if c.name == name || c.alias == name {
return c
}
}
return nil
}
type Command struct {
name string
run func(Options, []string, *Env) error
desc string
alias string
syntax string
opts Options
}
func NewCommand(name string, fn func(Options, []string, *Env) error, modifiers ...func(*Command)) *Command {
if fn == nil {
fn = func(Options, []string, *Env) error {
return errors.New(name + " is not implemented")
}
}
c := &Command{
name: name,
run: fn,
desc: "No description provided for " + name,
syntax: "unknown",
}
for _, fn := range modifiers {
fn(c)
}
return c
}
func WithDescription(val string) func(*Command) {
return func(c *Command) {
c.desc = val
}
}
func WithAlias(val string) func(*Command) {
return func(c *Command) {
c.alias = val
}
}
func WithSyntax(val string) func(*Command) {
return func(c *Command) {
c.syntax = val
}
}
func WithOption(name string, usage string, value interface{}) func(*Command) {
return WithOptionAlias(name, "", usage, value)
}
func WithOptionAlias(name string, alias string, usage string, value interface{}) func(*Command) {
return func(c *Command) {
c.opts = append(c.opts, newOption(name, alias, value, usage))
}
}
func (c *Command) usage() {
fmt.Println("Usage:", c.syntax)
fmt.Println(c.desc + ".")
if len(c.opts) > 0 {
fmt.Println("\nOptions:")
c.opts.print()
}
}
type Options []*Option
func (opts Options) Get(name string) *Option {
for _, o := range opts {
if o.Name == name {
return o
}
}
return nil
}
func (opts Options) addToFlagSet(fs *flag.FlagSet) {
for _, o := range opts {
o.addToFlagSet(fs)
}
}
func (opts Options) print() {
fs := flag.NewFlagSet("", flag.ContinueOnError)
for _, o := range opts {
o.addToFlagSet(fs)
}
fs.PrintDefaults()
}
type Option struct {
Name string
alias string
usage string
value interface{}
}
func newOption(name string, alias string, value interface{}, usage string) *Option {
if name == "" {
panic("Invalid name for flag: name cannot be blank")
}
if value == nil {
panic(fmt.Sprintf("Invalid default for flag %q: value cannot be nil", name))
}
// Create a pointer to a new value of the desired type.
p := reflect.New(reflect.TypeOf(value))
// Set the new value to the provided value.
p.Elem().Set(reflect.ValueOf(value))
return &Option{
Name: name,
alias: alias,
usage: usage,
value: p.Interface(),
}
}
func (o *Option) Bool() bool {
return *o.value.(*bool)
}
func (o *Option) Float() float64 {
return *o.value.(*float64)
}
func (o *Option) Int() int {
return *o.value.(*int)
}
func (o *Option) String() string {
return *o.value.(*string)
}
func (o *Option) Uint() uint {
return *o.value.(*uint)
}
// The flag.Getter interface is not defined in the
// pflag package so we have to use our own.
type getter interface {
Get() interface{}
}
func (o *Option) Value() interface{} {
if getter, ok := o.value.(getter); ok {
return getter.Get()
}
// Remember to dereference the ptr.
return reflect.ValueOf(o.value).Elem().Interface()
}
func (o *Option) addToFlagSet(fs *flag.FlagSet) {
switch v := o.value.(type) {
case *bool:
fs.BoolVarP(v, o.Name, o.alias, *v, o.usage)
case *float64:
fs.Float64VarP(v, o.Name, o.alias, *v, o.usage)
case *int:
fs.IntVarP(v, o.Name, o.alias, *v, o.usage)
case *string:
fs.StringVarP(v, o.Name, o.alias, *v, o.usage)
case *uint:
fs.UintVarP(v, o.Name, o.alias, *v, o.usage)
case flag.Value:
fs.VarP(v, o.Name, o.alias, o.usage)
default:
panic(fmt.Sprintf("Invalid default for flag %q: unsupported type %T", o.Name, o.value))
}
}