-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
76 lines (59 loc) · 1.33 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
package cli
import (
"fmt"
"github.com/awee-ai/structs"
)
type Command[T any] interface {
// BaseCommand[T]
Name(name string) string
Add(name string, cmd Command[any])
Options() any
Commands() []Command[any]
// Command[T]
Run(options GlobalOptions, unknowns Unknowns) error
Validate(options map[string]any) error
Help() string
}
type BaseCommand[T any] struct {
command string
commands []Command[any]
Inputs *T
}
func NewBaseCommand[T any]() BaseCommand[T] {
return BaseCommand[T]{
commands: make([]Command[any], 0),
}
}
func (c *BaseCommand[T]) Name(name string) string {
// getter
if name == "" {
return c.command
}
// setter
c.command = name
return name
}
func (c *BaseCommand[T]) Add(name string, cmd Command[any]) {
cmd.Name(name)
c.commands = append(c.commands, cmd)
}
func (c *BaseCommand[T]) Validate(options map[string]any) error {
manager := structs.New(c.Inputs, structs.DefaultRules, defaultTags...)
errors, err := manager.Validate(options)
if err != nil {
return fmt.Errorf("error validating cli args structure: %w", err)
}
if len(errors) > 0 {
return fmt.Errorf("validation failed: %v", errors)
}
return nil
}
func (c *BaseCommand[T]) Options() any {
if c.Inputs == nil {
c.Inputs = new(T)
}
return c.Inputs
}
func (c *BaseCommand[T]) Commands() []Command[any] {
return c.commands
}