-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecorators.go
620 lines (521 loc) · 16.2 KB
/
decorators.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
// Copyright © 2024 Meroxa, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ecdysis
import (
"bufio"
"context"
"errors"
"fmt"
"log/slog"
"os"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
var DefaultDecorators = []Decorator{
CommandWithLoggerDecorator{},
CommandWithAliasesDecorator{},
CommandWithFlagsDecorator{},
// CommandWithConfigDecorator needs to be after CommandWithFlagsDecorator to make sure the flags are parsed.
CommandWithConfigDecorator{},
CommandWithDocsDecorator{},
CommandWithHiddenDecorator{},
CommandWithSubCommandsDecorator{},
CommandWithDeprecatedDecorator{},
CommandWithArgsDecorator{},
// Confirm and Prompt need to go before Execute to make sure there's a
// confirmation prompt prior to execution.
CommandWithConfirmDecorator{},
CommandWithPromptDecorator{},
CommandWithExecuteDecorator{},
}
// -- LOGGER -------------------------------------------------------------------
// CommandWithLogger can be implemented by a command to get a logger.
type CommandWithLogger interface {
Command
// Logger provides the logger to the command.
Logger(*slog.Logger)
}
// CommandWithLoggerDecorator is a decorator that provides a logger to the command.
// If the Logger field is not set, the default slog logger will be provided.
type CommandWithLoggerDecorator struct {
Logger *slog.Logger
}
// Decorate provides the logger to the command.
func (d CommandWithLoggerDecorator) Decorate(_ *Ecdysis, _ *cobra.Command, c Command) error {
v, ok := c.(CommandWithLogger)
if !ok {
return nil
}
if d.Logger == nil {
v.Logger(slog.Default())
} else {
v.Logger(d.Logger)
}
return nil
}
// -- ALIASES ------------------------------------------------------------------
// CommandWithAliases can be implemented by a command to provide aliases.
type CommandWithAliases interface {
Command
// Aliases is a slice of aliases that can be used instead of the first word
// in Usage.
Aliases() []string
}
// CommandWithAliasesDecorator is a decorator that sets the command aliases.
type CommandWithAliasesDecorator struct{}
// Decorate sets the command aliases.
func (CommandWithAliasesDecorator) Decorate(_ *Ecdysis, cmd *cobra.Command, c Command) error {
v, ok := c.(CommandWithAliases)
if !ok {
return nil
}
cmd.Aliases = v.Aliases()
return nil
}
// -- FLAGS --------------------------------------------------------------------
// CommandWithFlags can be implemented by a command to provide flags.
type CommandWithFlags interface {
Command
// Flags returns the set of flags on this command.
Flags() []Flag
}
// CommandWithFlagsDecorator is a decorator that sets the command flags.
type CommandWithFlagsDecorator struct{}
// Decorate sets the command flags.
//
//nolint:funlen,gocyclo,gocognit,forcetypeassert // this function has a big switch statement, can't get around that
func (CommandWithFlagsDecorator) Decorate(_ *Ecdysis, cmd *cobra.Command, c Command) error {
v, ok := c.(CommandWithFlags)
if !ok {
return nil
}
for _, f := range v.Flags() {
var flags *pflag.FlagSet
if f.Persistent {
flags = cmd.PersistentFlags()
} else {
flags = cmd.Flags()
}
if f.Required {
f.Usage += " (required)"
}
switch val := f.Ptr.(type) {
case *string:
if f.Default == nil {
f.Default = ""
}
flags.StringVarP(val, f.Long, f.Short, f.Default.(string), f.Usage)
case *int:
if f.Default == nil {
f.Default = 0
}
flags.IntVarP(val, f.Long, f.Short, f.Default.(int), f.Usage)
case *int8:
if f.Default == nil {
f.Default = int8(0)
}
flags.Int8VarP(val, f.Long, f.Short, f.Default.(int8), f.Usage)
case *int16:
if f.Default == nil {
f.Default = int16(0)
}
flags.Int16VarP(val, f.Long, f.Short, f.Default.(int16), f.Usage)
case *int32:
if f.Default == nil {
f.Default = int32(0)
}
flags.Int32VarP(val, f.Long, f.Short, f.Default.(int32), f.Usage)
case *int64:
if f.Default == nil {
f.Default = int64(0)
}
flags.Int64VarP(val, f.Long, f.Short, f.Default.(int64), f.Usage)
case *float32:
if f.Default == nil {
f.Default = float32(0)
}
flags.Float32VarP(val, f.Long, f.Short, f.Default.(float32), f.Usage)
case *float64:
if f.Default == nil {
f.Default = float64(0)
}
flags.Float64VarP(val, f.Long, f.Short, f.Default.(float64), f.Usage)
case *bool:
if f.Default == nil {
f.Default = false
}
flags.BoolVarP(val, f.Long, f.Short, f.Default.(bool), f.Usage)
case *time.Duration:
if f.Default == nil {
f.Default = time.Duration(0)
}
flags.DurationVarP(val, f.Long, f.Short, f.Default.(time.Duration), f.Usage)
case *[]bool:
if f.Default == nil {
f.Default = []bool(nil)
}
flags.BoolSliceVarP(val, f.Long, f.Short, f.Default.([]bool), f.Usage)
case *[]float32:
if f.Default == nil {
f.Default = []float32(nil)
}
flags.Float32SliceVarP(val, f.Long, f.Short, f.Default.([]float32), f.Usage)
case *[]float64:
if f.Default == nil {
f.Default = []float64(nil)
}
flags.Float64SliceVarP(val, f.Long, f.Short, f.Default.([]float64), f.Usage)
case *[]int32:
if f.Default == nil {
f.Default = []int32(nil)
}
flags.Int32SliceVarP(val, f.Long, f.Short, f.Default.([]int32), f.Usage)
case *[]int64:
if f.Default == nil {
f.Default = []int64(nil)
}
flags.Int64SliceVarP(val, f.Long, f.Short, f.Default.([]int64), f.Usage)
case *[]int:
if f.Default == nil {
f.Default = []int(nil)
}
flags.IntSliceVarP(val, f.Long, f.Short, f.Default.([]int), f.Usage)
case *[]string:
if f.Default == nil {
f.Default = []string(nil)
}
flags.StringSliceVarP(val, f.Long, f.Short, f.Default.([]string), f.Usage)
default:
return fmt.Errorf("unexpected flag value type: %T", val)
}
if f.Required {
err := cobra.MarkFlagRequired(flags, f.Long)
if err != nil {
return fmt.Errorf("could not mark flag required: %w", err)
}
}
if f.Hidden {
err := flags.MarkHidden(f.Long)
if err != nil {
return fmt.Errorf("could not mark flag hidden: %w", err)
}
}
}
return nil
}
// -- PARSING CONFIGURATION --------------------------------------------------------------------
// CommandWithConfig can be implemented by a command to parsing configuration.
type CommandWithConfig interface {
Command
Config() Config
}
// CommandWithConfigDecorator is a decorator that sets the command flags.
type CommandWithConfigDecorator struct{}
// Decorate parses the configuration based on flags.
func (CommandWithConfigDecorator) Decorate(_ *Ecdysis, cmd *cobra.Command, c Command) error {
v, ok := c.(CommandWithConfig)
if !ok {
return nil
}
old := cmd.PreRunE
cmd.PreRunE = func(cmd *cobra.Command, args []string) error {
if old != nil {
err := old(cmd, args)
if err != nil {
return err
}
}
cfg := v.Config()
return ParseConfig(cfg, cmd)
}
return nil
}
// -- DOCS ---------------------------------------------------------------------
// CommandWithDocs can be implemented by a command to provide documentation.
type CommandWithDocs interface {
Command
// Docs returns the documentation for the command.
Docs() Docs
}
// Docs will be shown to the user when typing 'help' as well as in generated docs.
type Docs struct {
// Short is the short description shown in the 'help' output.
Short string
// Long is the long message shown in the 'help <this-command>' output.
Long string
// Example is examples of how to use the command.
Example string
}
// CommandWithDocsDecorator is a decorator that sets the command documentation.
type CommandWithDocsDecorator struct{}
// Decorate sets the command documentation.
func (CommandWithDocsDecorator) Decorate(_ *Ecdysis, cmd *cobra.Command, c Command) error {
v, ok := c.(CommandWithDocs)
if !ok {
return nil
}
docs := v.Docs()
cmd.Long = docs.Long
cmd.Short = docs.Short
cmd.Example = docs.Example
return nil
}
// -- HIDDEN -------------------------------------------------------------------
// CommandWithHidden can be implemented by a command to hide it from the help.
type CommandWithHidden interface {
Command
// Hidden returns the desired hidden value for the command.
Hidden() bool
}
// CommandWithHiddenDecorator is a decorator that sets the command hidden value.
type CommandWithHiddenDecorator struct{}
// Decorate sets the command hidden value.
func (CommandWithHiddenDecorator) Decorate(_ *Ecdysis, cmd *cobra.Command, c Command) error {
v, ok := c.(CommandWithHidden)
if !ok {
return nil
}
cmd.Hidden = v.Hidden()
return nil
}
// -- SUB COMMANDS -------------------------------------------------------------
// CommandWithSubCommands can be implemented by a command to provide subcommands.
type CommandWithSubCommands interface {
Command
// SubCommands defines subcommands of a command.
SubCommands() []Command
}
// CommandWithSubCommandsDecorator is a decorator that sets the command subcommands.
type CommandWithSubCommandsDecorator struct{}
// Decorate sets the command subcommands.
func (CommandWithSubCommandsDecorator) Decorate(e *Ecdysis, cmd *cobra.Command, c Command) error {
v, ok := c.(CommandWithSubCommands)
if !ok {
return nil
}
for _, sub := range v.SubCommands() {
subCmd, err := e.BuildCobraCommand(sub)
if err != nil {
return fmt.Errorf("failed to build subcommand %q: %w", sub.Usage(), err)
}
cmd.AddCommand(subCmd)
}
return nil
}
// -- DEPRECATED ---------------------------------------------------------------
// CommandWithDeprecated can be implemented by a command to mark it as deprecated
// and print a message when it is used.
type CommandWithDeprecated interface {
Command
// Deprecated returns a message that will be printed when the command is used.
Deprecated() string
}
// CommandWithDeprecatedDecorator is a decorator that deprecates the command.
type CommandWithDeprecatedDecorator struct{}
// Decorate deprecates the command.
func (CommandWithDeprecatedDecorator) Decorate(_ *Ecdysis, cmd *cobra.Command, c Command) error {
v, ok := c.(CommandWithDeprecated)
if !ok {
return nil
}
cmd.Hidden = true
old := cmd.PreRunE
cmd.PreRunE = func(cmd *cobra.Command, args []string) error {
if old != nil {
err := old(cmd, args)
if err != nil {
return err
}
if cmd.Flags().Changed("json") {
return nil
}
c := cmd.Name()
if cmd.HasParent() {
c = fmt.Sprintf("%s %s", cmd.Parent().Name(), c)
}
fmt.Printf("Command %q is deprecated, %s\n", c, v.Deprecated())
}
return nil
}
return nil
}
// -- ARGS ---------------------------------------------------------------------
// CommandWithArgs can be implemented by a command to parse arguments.
type CommandWithArgs interface {
Command
// Args is meant to parse arguments after the command name.
Args([]string) error
}
// CommandWithArgsDecorator is a decorator that provides the command arguments.
type CommandWithArgsDecorator struct{}
// Decorate provides the command arguments.
func (CommandWithArgsDecorator) Decorate(_ *Ecdysis, cmd *cobra.Command, c Command) error {
v, ok := c.(CommandWithArgs)
if !ok {
return nil
}
old := cmd.PreRunE
cmd.PreRunE = func(cmd *cobra.Command, args []string) error {
if old != nil {
err := old(cmd, args)
if err != nil {
return err
}
}
return v.Args(args)
}
return nil
}
// -- CONFIRM ------------------------------------------------------------------
// CommandWithConfirm can be implemented by a command to require confirmation
// before execution. The user will be prompted to enter a specific value.
// If the value matches, the command will be executed, otherwise it will be
// aborted.
type CommandWithConfirm interface {
Command
// ValueToConfirm adds a prompt before the command is executed where the
// user is asked to write the exact value as wantInput. If the user input
// matches the command will be executed, otherwise processing will be
// aborted.
ValueToConfirm(context.Context) (wantInput string)
}
// CommandWithConfirmDecorator is a decorator that sets up a confirmation prompt
// before executing the command.
type CommandWithConfirmDecorator struct{}
// Decorate sets up a confirmation prompt before executing the command.
func (CommandWithConfirmDecorator) Decorate(_ *Ecdysis, cmd *cobra.Command, c Command) error {
v, ok := c.(CommandWithConfirm)
if !ok {
return nil
}
var (
force bool
yolo bool
)
cmd.Flags().BoolVarP(&force, "force", "f", false, "skip confirmation prompt")
cmd.Flags().BoolVarP(&yolo, "yolo", "", false, "skip confirmation prompt")
err := cmd.Flags().MarkHidden("yolo")
if err != nil {
return fmt.Errorf("could not mark flag hidden: %w", err)
}
old := cmd.RunE
cmd.RunE = func(cmd *cobra.Command, args []string) error {
if old != nil {
err := old(cmd, args)
if err != nil {
return err
}
}
// do not prompt for confirmation when --force (or --yolo 😜) is set
if force || yolo {
return nil
}
wantInput := v.ValueToConfirm(cmd.Context())
reader := bufio.NewReader(os.Stdin)
fmt.Printf("To proceed, type %q or re-run this command with --force\n▸ ", wantInput)
input, err := reader.ReadString('\n')
if err != nil {
return fmt.Errorf("failed to read user input: %w", err)
}
if wantInput != strings.TrimRight(input, "\r\n") {
return errors.New("action aborted")
}
return nil
}
return nil
}
// -- PROMPT -------------------------------------------------------------------
// CommandWithPrompt can be implemented by a command to require confirmation
// before execution. The user will be prompted to answer Y/N to proceed.
type CommandWithPrompt interface {
Command
// Prompt adds a prompt before the command is executed where the user is
// asked to answer Y/N to proceed. It returns the message to be printed and
// a boolean indicating if the prompt was successfully processed.
Prompt() (message string, ok bool)
// SkipPrompt will return logic around when to skip prompt (e.g.: when all
// flags and arguments are specified).
SkipPrompt() bool
}
// CommandWithPromptDecorator is a decorator that sets up a confirmation prompt
// before executing the command.
type CommandWithPromptDecorator struct{}
// Decorate sets up a confirmation prompt before executing the command.
func (CommandWithPromptDecorator) Decorate(_ *Ecdysis, cmd *cobra.Command, c Command) error {
v, ok := c.(CommandWithPrompt)
if !ok {
return nil
}
var (
force bool
yolo bool
)
cmd.Flags().BoolVarP(&force, "force", "f", false, "skip confirmation prompt")
cmd.Flags().BoolVarP(&yolo, "yolo", "", false, "skip confirmation prompt")
err := cmd.Flags().MarkHidden("yolo")
if err != nil {
return fmt.Errorf("could not mark flag hidden: %w", err)
}
old := cmd.RunE
cmd.RunE = func(cmd *cobra.Command, args []string) error {
if old != nil {
err := old(cmd, args)
if err != nil {
return err
}
}
// do not prompt for confirmation when --force (or --yolo 😜) is set
if force || yolo || v.SkipPrompt() {
return nil
}
msg, ok := v.Prompt()
if !ok {
fmt.Println(msg)
os.Exit(1)
}
return nil
}
return nil
}
// -- EXECUTE ------------------------------------------------------------------
// CommandWithExecute can be implemented by a command to provide an execution
// function.
type CommandWithExecute interface {
Command
// Execute is the actual work function. Most commands will implement this.
Execute(ctx context.Context) error
}
// CommandWithExecuteDecorator is a decorator that sets the command execution.
type CommandWithExecuteDecorator struct{}
// Decorate sets the command execution.
func (CommandWithExecuteDecorator) Decorate(_ *Ecdysis, cmd *cobra.Command, c Command) error {
v, ok := c.(CommandWithExecute)
if !ok {
return nil
}
old := cmd.RunE
cmd.RunE = func(cmd *cobra.Command, args []string) error {
if old != nil {
err := old(cmd, args)
if err != nil {
return err
}
}
ctx := ContextWithCobraCommand(cmd.Context(), cmd)
return v.Execute(ctx)
}
return nil
}