-
Notifications
You must be signed in to change notification settings - Fork 3
/
command.go
338 lines (321 loc) · 8.85 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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
package climate
import (
"context"
"errors"
"fmt"
"reflect"
"runtime/debug"
"strconv"
"strings"
"text/tabwriter"
"time"
"github.com/avamsi/ergo"
"github.com/avamsi/ergo/assert"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"golang.org/x/mod/module"
"github.com/avamsi/climate/internal"
)
type command struct {
delegate cobra.Command
}
func newCommand(name string, md *internal.Metadata, params []internal.ParamType) *command {
delegate := cobra.Command{
Use: md.Usage(name, params),
Aliases: md.Aliases(),
Short: md.Short(),
Long: md.Long(),
}
delegate.Flags().SortFlags = false
delegate.PersistentFlags().SortFlags = false
if md != nil {
delegate.DisableFlagsInUseLine = true
}
return &command{delegate}
}
func (cmd *command) addCommand(sub *command) {
cmd.delegate.AddCommand(&sub.delegate)
}
func version() string {
info, ok := debug.ReadBuildInfo()
if !ok {
return ""
}
if info.Main.Version != "(devel)" {
return info.Main.Version
}
var (
rev string
t time.Time
modified bool
)
for _, kv := range info.Settings {
switch kv.Key {
case "vcs.revision":
rev = kv.Value[:12]
case "vcs.time":
t = assert.Ok(time.Parse(time.RFC3339Nano, kv.Value))
case "vcs.modified":
modified = assert.Ok(strconv.ParseBool(kv.Value))
}
}
if t.IsZero() || rev == "" {
return ""
}
if modified {
rev += "*"
}
return module.PseudoVersion("", "", t, rev)
}
func flagUsages(fset *pflag.FlagSet) string {
var (
b strings.Builder
t = tabwriter.NewWriter(&b, 0, 0, 0, ' ', 0)
)
fset.VisitAll(func(f *pflag.Flag) {
var short string
if f.Shorthand != "" {
short = fmt.Sprintf("-%v, ", f.Shorthand)
}
var (
qtype, usage = pflag.UnquoteUsage(f)
value string
)
if qtype != "" {
qtype += " "
}
if _, ok := f.Annotations[nonZeroDefault]; ok {
value = fmt.Sprintf("(default %v) ", f.DefValue)
}
fmt.Fprintf(t, " %v\t--%v\t %v\t%v \t%v\n", short, f.Name, qtype, value, usage)
})
t.Flush()
return b.String()
}
func versionCommand(name, v string) *cobra.Command {
help := fmt.Sprintf("Display %v's version information", name)
return &cobra.Command{
Use: "version",
Short: help,
Long: help + ".",
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, _ []string) {
cmd.Println(v)
},
}
}
func (cmd *command) run(ctx context.Context) error {
normalize := func(_ *pflag.FlagSet, name string) pflag.NormalizedName {
return pflag.NormalizedName(internal.NormalizeToKebabCase(name))
}
// While we prefer kebab-case for flags, we do support other well-formed,
// cases through normalization (but only kebab-case shows up in --help).
cmd.delegate.SetGlobalNormalizationFunc(normalize)
if v := version(); v != "" {
// Add the version subcommand only when the root command already has
// subcommands (similar to how Cobra does it for help / completion).
if cmd.delegate.HasSubCommands() {
cmd.delegate.AddCommand(versionCommand(cmd.delegate.Name(), v))
}
cmd.delegate.Version = v
}
// Align the flag usages as a table (pflag's FlagUsages already does this to
// some extent but doesn't align types and default values).
cobra.AddTemplateFunc("flagUsages", flagUsages)
t := cmd.delegate.UsageTemplate()
t = strings.ReplaceAll(t, ".FlagUsages", " | flagUsages")
cmd.delegate.SetUsageTemplate(t)
return cmd.delegate.ExecuteContext(ctx)
}
type funcCommandBuilder struct {
name string
reflection
md *internal.Metadata
}
type runSignature struct {
numIn int
inCtx bool
inOpts *reflect.Value
inArgs internal.ParamType
outErr bool
}
func (fcb *funcCommandBuilder) run(sig *runSignature) func(*cobra.Command, []string) error {
return func(cmd *cobra.Command, args []string) error {
var in []reflect.Value
if sig.inCtx {
in = append(in, reflect.ValueOf(cmd.Context()))
}
if sig.inOpts != nil {
in = append(in, *sig.inOpts)
}
switch sig.inArgs {
case internal.RequiredParam:
in = append(in, reflect.ValueOf(args[0]))
case internal.OptionalParam:
var ptr *string
if len(args) == 1 {
ptr = &args[0]
}
in = append(in, reflect.ValueOf(ptr))
case internal.FixedLengthParam:
arr := reflect.New(fcb.t().In(sig.numIn - 1)).Elem()
reflect.Copy(arr, reflect.ValueOf(args))
in = append(in, arr)
case internal.ArbitraryLengthParam:
in = append(in, reflect.ValueOf(args))
}
out := fcb.v().Call(in)
if sig.outErr {
if out[0].IsNil() { // if _no_ error
return nil
}
err := out[0].Interface().(error)
if uerr := new(usageError); errors.As(err, &uerr) {
// Let Cobra print both the error and usage information.
return err
}
// err is not a usage error (anymore), so set SilenceUsage to true
// to prevent Cobra from printing usage information.
cmd.SilenceUsage = true
// exitError may just be used to exit with a particular exit code
// and not necessarily have anything to print.
if eerr := new(exitError); errors.As(err, &eerr) {
cmd.SilenceErrors = len(eerr.errs) == 0
}
return err
}
return nil
}
}
func (fcb *funcCommandBuilder) build() *command {
var (
cmd = newCommand(fcb.name, fcb.md, internal.ParamTypes(fcb.t()))
i = 0
n = fcb.t().NumIn()
inCtx bool
inOpts *reflect.Value
inArgs = internal.NoParam
)
// We support the signatures (excuse the partial [optional] notation)
// func([ctx context.Context], [opts *T], [args []string]) [(err error)],
// which is to say all of ctx, opts, args and error are optional. If opts is
// present, T must be a struct (and we use its fields as flags).
// TODO: maybe support variadic, array and normal string arguments too.
if i < n && typeIsContext(fcb.t().In(i)) {
i++
inCtx = true
}
if i < n {
if t := fcb.t().In(i); typeIsStructPointer(t) {
var (
r = reflection{ptr: &reflection{ot: t}}
opts = &options{
r,
nil, // no parent
cmd.delegate.Flags(),
fcb.md.LookupType(t.Elem()),
}
)
opts.declare()
i++
inOpts = r.ptr.v()
}
}
if i < n {
switch t := fcb.t().In(i); t.Kind() {
case reflect.String:
i++
inArgs = internal.RequiredParam
cmd.delegate.Args = cobra.ExactArgs(1)
case reflect.Pointer, reflect.Array, reflect.Slice:
if t.Elem().Kind() != reflect.String {
break
}
i++
switch t.Kind() {
case reflect.Pointer:
inArgs = internal.OptionalParam
cmd.delegate.Args = cobra.MaximumNArgs(1)
case reflect.Array:
inArgs = internal.FixedLengthParam
cmd.delegate.Args = cobra.ExactArgs(t.Len())
case reflect.Slice:
inArgs = internal.ArbitraryLengthParam
}
}
} else {
cmd.delegate.Args = cobra.ExactArgs(0)
}
outErr := fcb.t().NumOut() == 1 && typeIsError(fcb.t().Out(0))
if i != n || fcb.t().IsVariadic() || (fcb.t().NumOut() != 0 && !outErr) {
ergo.Panicf("not func([context.Context], [*struct], [[]string]) [error]: %v", fcb.t())
}
cmd.delegate.RunE = fcb.run(&runSignature{n, inCtx, inOpts, inArgs, outErr})
return cmd
}
type structCommandBuilder struct {
reflection
parent *reflection
md *internal.Metadata
}
func validateNoArgs(cmd *cobra.Command, args []string) error {
cmd.SilenceUsage = true
err := cobra.NoArgs(cmd, args)
if err == nil { // if _no_ error
return cmd.Help()
}
var b strings.Builder
fmt.Fprintf(&b, "%v", err)
if suggestions := cmd.SuggestionsFor(args[0]); len(suggestions) > 0 {
b.WriteString("\n\nDid you mean this?\n")
for _, s := range suggestions {
fmt.Fprintf(&b, "\t%v\n", s)
}
}
fmt.Fprintf(&b, "\nRun '%v --help' for usage.", cmd.CommandPath())
return errors.New(b.String())
}
func (scb *structCommandBuilder) build() *command {
var (
cmd = newCommand(scb.t().Name(), scb.md, nil)
opts = &options{
scb.reflection,
scb.parent,
cmd.delegate.PersistentFlags(),
scb.md,
}
)
opts.declare()
for i := 0; i < scb.ptr.v().NumMethod(); i++ {
var (
m = scb.ptr.t().Method(i)
v = scb.ptr.v().Method(i)
fcb = &funcCommandBuilder{
m.Name,
reflection{ov: &v},
scb.md.Child(m.Name),
}
)
// TODO: maybe provide an option to default to a subcommand.
cmd.addCommand(fcb.build())
}
// This should ideally be as simple as setting cobra.NoArgs, but for
// whatever reason, Cobra doesn't really honor that for subcommands
// (see spf13/cobra#706, spf13/cobra#981) -- so, we do it ourselves.
cmd.delegate.RunE = validateNoArgs
// We only make this command "runnable" to validate NoArgs, so hack the
// usage template and pretend it's not really runnable.
// Note: Cobra subcommands will inherit any custom attributes set on the
// parent command, so we need to be careful here to only apply the changes
// to the parent command and not any subcommands.
defaultHelpFunc := cmd.delegate.HelpFunc()
cmd.delegate.SetHelpFunc(func(c *cobra.Command, _ []string) {
if c == &cmd.delegate {
t := cmd.delegate.UsageTemplate()
t = strings.ReplaceAll(t, "{{if .Runnable}}", "{{if false}}")
c.SetUsageTemplate(t)
}
defaultHelpFunc(c, nil)
})
return cmd
}