-
Notifications
You must be signed in to change notification settings - Fork 151
/
command.go
418 lines (345 loc) · 11.4 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
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
package core
import (
"context"
"fmt"
"reflect"
"sort"
"strings"
"github.com/scaleway/scaleway-cli/v2/internal/alias"
"github.com/scaleway/scaleway-cli/v2/internal/human"
)
// Command represent a CLI command. From this higher level type we create Cobra command objects.
type Command struct {
// Namespace is the top level entry point of a command. (e.g scw instance)
Namespace string
// Resource is the 2nd command level. Resources are nested in a namespace. (e.g scw instance server)
Resource string
// Verb is the 3rd command level. Verbs are nested in a resource. (e.g scw instance server list)
Verb string
// Short documentation.
Short string
// Long documentation.
Long string
// AllowAnonymousClient defines whether the SDK client can run the command without be authenticated.
AllowAnonymousClient bool
// DisableTelemetry disable telemetry for the command.
DisableTelemetry bool
// DisableAfterChecks disable checks that run after the command to avoid superfluous message
DisableAfterChecks bool
// Hidden hides the command form usage and auto-complete.
Hidden bool
// ArgsType defines the type of argument for this command.
ArgsType reflect.Type
// ArgSpecs defines specifications for arguments.
ArgSpecs ArgSpecs
// AcceptMultiplePositionalArgs defines whether the command can accept multiple positional arguments.
// If enabled, positional argument is expected to be a list.
AcceptMultiplePositionalArgs bool
// View defines the View for this command.
// It is used to create the different options for the different Marshalers.
View *View
// Examples defines Examples for this command.
Examples []*Example
// SeeAlsos presents commands related to this command.
SeeAlsos []*SeeAlso
// PreValidateFunc allows to manipulate args before validation
PreValidateFunc CommandPreValidateFunc
// ValidateFunc validates a command.
// If nil, core.DefaultCommandValidateFunc is used by default.
ValidateFunc CommandValidateFunc
// Interceptor are middleware func that can intercept context and args before they are sent to Run
// You can combine multiple CommandInterceptor using AddInterceptors method.
Interceptor CommandInterceptor
// Run will be called to execute a command. It will receive a context and parsed argument.
// Non-nil values returned by this method will be printed out.
Run CommandRunner
// WaitFunc will be called if non-nil when the -w (--wait) flag is passed.
WaitFunc WaitFunc
// WebURL will be used as url to open when the --web flag is passed
// Can contain template of values in request, ex: "url/{{ .Zone }}/{{ .ResourceID }}"
WebURL string
// WaitUsage override the usage for the -w (--wait) flag
WaitUsage string
// Aliases contains a list of aliases for a command
Aliases []string
// cache command path
path string
// Groups contains a list of groups IDs
Groups []string
//
Deprecated bool
}
// CommandPreValidateFunc allows to manipulate args before validation.
type CommandPreValidateFunc func(ctx context.Context, argsI interface{}) error
// CommandInterceptor allow to intercept and manipulate a runner arguments and return value.
// It can for example be used to change arguments type or catch runner errors.
type CommandInterceptor func(ctx context.Context, argsI interface{}, runner CommandRunner) (interface{}, error)
// CommandRunner returns the command response or an error.
type CommandRunner func(ctx context.Context, argsI interface{}) (interface{}, error)
// WaitFunc returns the updated response (respI if unchanged) or an error.
type WaitFunc func(ctx context.Context, argsI, respI interface{}) (interface{}, error)
const indexCommandSeparator = "."
// Override replaces or mutates the Command via a builder function.
func (c *Command) Override(builder func(command *Command) *Command) {
// Assign the value in case the builder creates a new Command object.
*c = *builder(c)
}
func (c *Command) getPath() string {
if c.path != "" {
return c.path
}
path := []string(nil)
if c.Namespace != "" {
path = append(path, c.Namespace)
}
if c.Resource != "" {
path = append(path, c.Resource)
}
if c.Verb != "" {
path = append(path, c.Verb)
}
c.path = strings.Join(path, indexCommandSeparator)
return c.path
}
func (c *Command) GetCommandLine(binaryName string) string {
return strings.Trim(binaryName+" "+strings.ReplaceAll(c.getPath(), indexCommandSeparator, " "), " ")
}
func (c *Command) GetUsage(binaryName string, commands *Commands) string {
parts := []string{
c.GetCommandLine(binaryName),
}
if commands.HasSubCommands(c) {
parts = append(parts, "<command>")
}
if positionalArg := c.ArgSpecs.GetPositionalArg(); positionalArg != nil {
parts = append(parts, "<"+positionalArg.Name+" ...>")
}
if len(c.ArgSpecs) > 0 {
parts = append(parts, "[arg=value ...]")
}
return strings.Join(parts, " ")
}
// seeAlsosAsStr returns all See Alsos as a single string
func (c *Command) seeAlsosAsStr() string {
seeAlsos := make([]string, 0, len(c.SeeAlsos))
for _, cmdSeeAlso := range c.SeeAlsos {
short := fmt.Sprintf(" # %s", cmdSeeAlso.Short)
commandStr := fmt.Sprintf(" %s", cmdSeeAlso.Command)
seeAlsoLines := []string{
short,
commandStr,
}
seeAlsos = append(seeAlsos, strings.Join(seeAlsoLines, "\n"))
}
return strings.Join(seeAlsos, "\n\n")
}
// AddInterceptors add one or multiple interceptors to a command.
// These new interceptors will be added after the already present interceptors (if any).
func (c *Command) AddInterceptors(interceptors ...CommandInterceptor) {
interceptors = append([]CommandInterceptor{c.Interceptor}, interceptors...)
c.Interceptor = CombineCommandInterceptor(interceptors...)
}
// MatchAlias returns true if the alias can be used for this command
func (c *Command) MatchAlias(alias alias.Alias) bool {
if len(c.ArgSpecs) == 0 {
// command should be either a namespace or a resource
// We need to check if child commands match this alias
return true
}
for _, aliasArg := range alias.Args() {
if c.ArgSpecs.GetByName(aliasArg) == nil {
return false
}
}
return true
}
// Commands represent a list of CLI commands, with a index to allow searching.
type Commands struct {
commands []*Command
commandIndex map[string]*Command
}
func NewCommands(cmds ...*Command) *Commands {
c := &Commands{
commands: make([]*Command, 0, len(cmds)),
commandIndex: make(map[string]*Command, len(cmds)),
}
for _, cmd := range cmds {
c.Add(cmd)
}
return c
}
func NewCommandsMerge(cmdsList ...*Commands) *Commands {
cmdCount := 0
for _, cmds := range cmdsList {
cmdCount += len(cmds.commands)
}
c := &Commands{
commands: make([]*Command, 0, cmdCount),
commandIndex: make(map[string]*Command, cmdCount),
}
for _, cmds := range cmdsList {
for _, cmd := range cmds.commands {
c.Add(cmd)
}
}
return c
}
func (c *Commands) MustFind(path ...string) *Command {
cmd, exist := c.find(path...)
if exist {
return cmd
}
panic(fmt.Errorf("command %v not found", strings.Join(path, " ")))
}
func (c *Commands) Find(path ...string) *Command {
cmd, exist := c.find(path...)
if exist {
return cmd
}
return nil
}
func (c *Commands) Remove(namespace, verb string) {
for i := range c.commands {
if c.commands[i].Namespace == namespace && c.commands[i].Verb == verb {
c.commands = append(c.commands[:i], c.commands[i+1:]...)
return
}
}
}
func (c *Commands) Add(cmd *Command) {
c.commands = append(c.commands, cmd)
c.commandIndex[cmd.getPath()] = cmd
}
func (c *Commands) Merge(cmds *Commands) {
for _, cmd := range cmds.commands {
c.Add(cmd)
}
}
func (c *Commands) GetAll() []*Command {
return c.commands
}
// find must take the command path, eg. find("instance","get","server")
func (c *Commands) find(path ...string) (*Command, bool) {
cmd, exist := c.commandIndex[strings.Join(path, indexCommandSeparator)]
if exist {
return cmd, true
}
return nil, false
}
// GetSortedCommand returns a slice of commands sorted alphabetically
func (c *Commands) GetSortedCommand() []*Command {
commands := make([]*Command, len(c.commands))
copy(commands, c.commands)
sort.Slice(commands, func(i, j int) bool {
return commands[i].signature() < commands[j].signature()
})
return commands
}
func (c *Commands) HasSubCommands(cmd *Command) bool {
if cmd.Namespace != "" && cmd.Resource != "" && cmd.Verb != "" {
return false
}
if cmd.Namespace == "" && cmd.Resource == "" && cmd.Verb == "" {
return true
}
for _, command := range c.commands {
if command == cmd {
continue
}
if cmd.Resource == "" && cmd.Namespace == command.Namespace {
return true
}
if cmd.Verb == "" && cmd.Namespace == command.Namespace && cmd.Resource == command.Resource {
return true
}
}
return false
}
func (c *Command) getHumanMarshalerOpt() *human.MarshalOpt {
if c.View != nil {
return c.View.getHumanMarshalerOpt()
}
return nil
}
// get a signature to sort commands
func (c *Command) signature() string {
return c.Namespace + " " + c.Resource + " " + c.Verb + " " + c.Short
}
// AliasIsValidCommandChild returns true is alias is a valid child command of given command
// Useful for this case:
// isl => instance server list
// valid child of "instance"
// invalid child of "rdb instance"
func (c *Commands) AliasIsValidCommandChild(command *Command, alias alias.Alias) bool {
// if alias is of size one, it means it cannot be a child
if len(alias.Command) == 1 {
return true
}
// if command is verb, it cannot have children
if command.Verb != "" {
return true
}
// if command is a resource, check command with alias' verb
if command.Resource != "" {
return c.Find(command.Namespace, command.Resource, alias.Command[1]) != nil
}
// if command is a namespace, check for alias' verb or resource
if command.Namespace != "" {
if len(alias.Command) > 2 {
return c.Find(command.Namespace, alias.Command[1], alias.Command[2]) != nil
}
return c.Find(command.Namespace, alias.Command[1]) != nil
}
return false
}
// addAliases add valid aliases to a command
func (c *Commands) addAliases(command *Command, aliases []alias.Alias) {
names := make([]string, 0, len(aliases))
for i := range aliases {
if c.AliasIsValidCommandChild(command, aliases[i]) && command.MatchAlias(aliases[i]) {
names = append(names, aliases[i].Name)
}
}
command.Aliases = append(command.Aliases, names...)
}
// applyAliases add resource aliases to each commands
func (c *Commands) applyAliases(config *alias.Config) {
for _, command := range c.commands {
aliases := []alias.Alias(nil)
exists := false
if command.Verb != "" {
aliases, exists = config.ResolveAliasesByFirstWord(command.Verb)
} else if command.Resource != "" {
aliases, exists = config.ResolveAliasesByFirstWord(command.Resource)
} else if command.Namespace != "" {
aliases, exists = config.ResolveAliasesByFirstWord(command.Namespace)
}
if exists {
c.addAliases(command, aliases)
}
}
}
// Copy returns a copy of a command
func (c *Command) Copy() *Command {
newCommand := *c
newCommand.Aliases = append([]string(nil), c.Aliases...)
newCommand.Examples = make([]*Example, len(c.Examples))
for i := range c.Examples {
e := *c.Examples[i]
newCommand.Examples[i] = &e
}
newCommand.SeeAlsos = make([]*SeeAlso, len(c.SeeAlsos))
for i := range c.SeeAlsos {
sa := *c.SeeAlsos[i]
newCommand.SeeAlsos[i] = &sa
}
return &newCommand
}
// Copy return a copy of all commands
func (c *Commands) Copy() *Commands {
newCommands := make([]*Command, len(c.commands))
for i := range c.commands {
newCommands[i] = c.commands[i].Copy()
}
return NewCommands(newCommands...)
}