-
Notifications
You must be signed in to change notification settings - Fork 0
/
stringargsdispatcher.go
211 lines (184 loc) · 5.98 KB
/
stringargsdispatcher.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
package command
import (
"context"
"fmt"
"io"
"sort"
"strings"
"unicode"
)
type constError string
func (e constError) Error() string {
return string(e)
}
const (
Default = ""
ErrNotFound = constError("command not found")
)
type stringArgsCommand struct {
command string
description string
args Args
commandFunc interface{}
stringArgsFunc StringArgsFunc
resultsHandlers []ResultsHandler
}
func checkCommandChars(command string) error {
if strings.IndexFunc(command, unicode.IsSpace) >= 0 {
return fmt.Errorf("command contains space characters: '%s'", command)
}
if strings.IndexFunc(command, unicode.IsGraphic) == -1 {
return fmt.Errorf("command contains non graphc characters: '%s'", command)
}
if strings.ContainsAny(command, "|&;()<>") {
return fmt.Errorf("command contains invalid characters: '%s'", command)
}
return nil
}
type StringArgsCommandLogger interface {
LogStringArgsCommand(command string, args []string)
}
type StringArgsCommandLoggerFunc func(command string, args []string)
func (f StringArgsCommandLoggerFunc) LogStringArgsCommand(command string, args []string) {
f(command, args)
}
type StringArgsDispatcher struct {
comm map[string]*stringArgsCommand
loggers []StringArgsCommandLogger
}
func NewStringArgsDispatcher(loggers ...StringArgsCommandLogger) *StringArgsDispatcher {
return &StringArgsDispatcher{
comm: make(map[string]*stringArgsCommand),
loggers: loggers,
}
}
func (disp *StringArgsDispatcher) AddCommand(command, description string, commandFunc interface{}, args Args, resultsHandlers ...ResultsHandler) error {
if _, exists := disp.comm[command]; exists {
return fmt.Errorf("Command '%s' already added", command)
}
if err := checkCommandChars(command); err != nil {
return fmt.Errorf("Command '%s' returned: %w", command, err)
}
stringArgsFunc, err := GetStringArgsFunc(commandFunc, args, resultsHandlers...)
if err != nil {
return fmt.Errorf("Command '%s' returned: %w", command, err)
}
disp.comm[command] = &stringArgsCommand{
command: command,
description: description,
args: args,
commandFunc: commandFunc,
stringArgsFunc: stringArgsFunc,
resultsHandlers: resultsHandlers,
}
return nil
}
func (disp *StringArgsDispatcher) MustAddCommand(command, description string, commandFunc interface{}, args Args, resultsHandlers ...ResultsHandler) {
err := disp.AddCommand(command, description, commandFunc, args, resultsHandlers...)
if err != nil {
panic(err)
}
}
func (disp *StringArgsDispatcher) AddDefaultCommand(description string, commandFunc interface{}, args Args, resultsHandlers ...ResultsHandler) error {
stringArgsFunc, err := GetStringArgsFunc(commandFunc, args, resultsHandlers...)
if err != nil {
return fmt.Errorf("Default command: %w", err)
}
disp.comm[Default] = &stringArgsCommand{
command: Default,
description: description,
args: args,
commandFunc: commandFunc,
stringArgsFunc: stringArgsFunc,
resultsHandlers: resultsHandlers,
}
return nil
}
func (disp *StringArgsDispatcher) MustAddDefaultCommand(description string, commandFunc interface{}, args Args, resultsHandlers ...ResultsHandler) {
err := disp.AddDefaultCommand(description, commandFunc, args, resultsHandlers...)
if err != nil {
panic(err)
}
}
func (disp *StringArgsDispatcher) HasCommnd(command string) bool {
_, found := disp.comm[command]
return found
}
func (disp *StringArgsDispatcher) HasDefaultCommnd() bool {
_, found := disp.comm[Default]
return found
}
func (disp *StringArgsDispatcher) Dispatch(ctx context.Context, command string, args ...string) error {
cmd, found := disp.comm[command]
if !found {
return ErrNotFound
}
for _, logger := range disp.loggers {
logger.LogStringArgsCommand(command, args)
}
return cmd.stringArgsFunc(ctx, args...)
}
func (disp *StringArgsDispatcher) MustDispatch(ctx context.Context, command string, args ...string) {
err := disp.Dispatch(ctx, command, args...)
if err != nil {
panic(fmt.Errorf("Command '%s' returned: %w", command, err))
}
}
func (disp *StringArgsDispatcher) DispatchDefaultCommand() error {
return disp.Dispatch(context.Background(), Default)
}
func (disp *StringArgsDispatcher) MustDispatchDefaultCommand() {
err := disp.DispatchDefaultCommand()
if err != nil {
panic(fmt.Errorf("Default command: %w", err))
}
}
func (disp *StringArgsDispatcher) DispatchCombinedCommandAndArgs(ctx context.Context, commandAndArgs []string) (command string, err error) {
if len(commandAndArgs) == 0 {
return Default, disp.DispatchDefaultCommand()
}
command = commandAndArgs[0]
args := commandAndArgs[1:]
return command, disp.Dispatch(ctx, command, args...)
}
func (disp *StringArgsDispatcher) MustDispatchCombinedCommandAndArgs(ctx context.Context, commandAndArgs []string) (command string) {
command, err := disp.DispatchCombinedCommandAndArgs(ctx, commandAndArgs)
if err != nil {
panic(fmt.Errorf("MustDispatchCombinedCommandAndArgs(%v): %w", commandAndArgs, err))
}
return command
}
func (disp *StringArgsDispatcher) PrintCommands(appName string) {
list := make([]*stringArgsCommand, 0, len(disp.comm))
for _, cmd := range disp.comm {
list = append(list, cmd)
}
sort.Slice(list, func(i, j int) bool {
return list[i].command < list[j].command
})
for _, cmd := range list {
CommandUsageColor.Printf(" %s %s %s\n", appName, cmd.command, cmd.args)
if cmd.description != "" {
CommandDescriptionColor.Printf(" %s\n", cmd.description)
}
hasAnyArgDesc := false
for _, arg := range cmd.args.Args() {
if arg.Description != "" {
hasAnyArgDesc = true
}
}
if hasAnyArgDesc {
for _, arg := range cmd.args.Args() {
CommandDescriptionColor.Printf(" <%s:%s> %s\n", arg.Name, arg.Type, arg.Description)
}
}
CommandDescriptionColor.Println()
}
}
func (disp *StringArgsDispatcher) PrintCommandsUsageIntro(appName string, output io.Writer) {
if len(disp.comm) > 0 {
fmt.Fprint(output, "Commands:\n")
disp.PrintCommands(appName)
fmt.Fprint(output, "Flags:\n")
}
}