Debian Codegraph @

vendor/github.com/urfave/cli/v2/command.go

raw
1 package cli
2
3 import (
4 "flag"
5 "fmt"
6 "reflect"
7 "sort"
8 "strings"
9 )
10
11 // Command is a subcommand for a cli.App.
12 type Command struct {
13 // The name of the command
14 Name string
15 // A list of aliases for the command
16 Aliases []string
17 // A short description of the usage of this command
18 Usage string
19 // Custom text to show on USAGE section of help
20 UsageText string
21 // A longer explanation of how the command works
22 Description string
23 // Whether this command supports arguments
24 Args bool
25 // A short description of the arguments of this command
26 ArgsUsage string
27 // The category the command is part of
28 Category string
29 // The function to call when checking for bash command completions
30 BashComplete BashCompleteFunc
31 // An action to execute before any sub-subcommands are run, but after the context is ready
32 // If a non-nil error is returned, no sub-subcommands are run
33 Before BeforeFunc
34 // An action to execute after any subcommands are run, but after the subcommand has finished
35 // It is run even if Action() panics
36 After AfterFunc
37 // The function to call when this command is invoked
38 Action ActionFunc
39 // Execute this function if a usage error occurs.
40 OnUsageError OnUsageErrorFunc
41 // List of child commands
42 Subcommands []*Command
43 // List of flags to parse
44 Flags []Flag
45 flagCategories FlagCategories
46 // Treat all flags as normal arguments if true
47 SkipFlagParsing bool
48 // Boolean to hide built-in help command and help flag
49 HideHelp bool
50 // Boolean to hide built-in help command but keep help flag
51 // Ignored if HideHelp is true.
52 HideHelpCommand bool
53 // Boolean to hide this command from help or completion
54 Hidden bool
55 // Boolean to enable short-option handling so user can combine several
56 // single-character bool arguments into one
57 // i.e. foobar -o -v -> foobar -ov
58 UseShortOptionHandling bool
59
60 // Full name of command for help, defaults to full command name, including parent commands.
61 HelpName string
62 commandNamePath []string
63
64 // CustomHelpTemplate the text template for the command help topic.
65 // cli.go uses text/template to render templates. You can
66 // render custom help text by setting this variable.
67 CustomHelpTemplate string
68
69 // categories contains the categorized commands and is populated on app startup
70 categories CommandCategories
71
72 // if this is a root "special" command
73 isRoot bool
74
75 separator separatorSpec
76 }
77
78 type Commands []*Command
79
80 type CommandsByName []*Command
81
82 func (c CommandsByName) Len() int {
83 return len(c)
84 }
85
86 func (c CommandsByName) Less(i, j int) bool {
87 return lexicographicLess(c[i].Name, c[j].Name)
88 }
89
90 func (c CommandsByName) Swap(i, j int) {
91 c[i], c[j] = c[j], c[i]
92 }
93
94 // FullName returns the full name of the command.
95 // For subcommands this ensures that parent commands are part of the command path
96 func (c *Command) FullName() string {
97 if c.commandNamePath == nil {
98 return c.Name
99 }
100 return strings.Join(c.commandNamePath, " ")
101 }
102
103 func (cmd *Command) Command(name string) *Command {
104 for _, c := range cmd.Subcommands {
105 if c.HasName(name) {
106 return c
107 }
108 }
109
110 return nil
111 }
112
113 func (c *Command) setup(ctx *Context) {
114 if c.Command(helpCommand.Name) == nil && !c.HideHelp {
115 if !c.HideHelpCommand {
116 c.Subcommands = append(c.Subcommands, helpCommand)
117 }
118 }
119
120 if !c.HideHelp && HelpFlag != nil {
121 // append help to flags
122 c.appendFlag(HelpFlag)
123 }
124
125 if ctx.App.UseShortOptionHandling {
126 c.UseShortOptionHandling = true
127 }
128
129 c.categories = newCommandCategories()
130 for _, command := range c.Subcommands {
131 c.categories.AddCommand(command.Category, command)
132 }
133 sort.Sort(c.categories.(*commandCategories))
134
135 for _, scmd := range c.Subcommands {
136 if scmd.HelpName == "" {
137 scmd.HelpName = fmt.Sprintf("%s %s", c.HelpName, scmd.Name)
138 }
139 scmd.separator = c.separator
140 }
141
142 if c.BashComplete == nil {
143 c.BashComplete = DefaultCompleteWithFlags(c)
144 }
145 }
146
147 func (c *Command) Run(cCtx *Context, arguments ...string) (err error) {
148
149 if !c.isRoot {
150 c.setup(cCtx)
151 if err := checkDuplicatedCmds(c); err != nil {
152 return err
153 }
154 }
155
156 a := args(arguments)
157 set, err := c.parseFlags(&a, cCtx.shellComplete)
158 cCtx.flagSet = set
159
160 if checkCompletions(cCtx) {
161 return nil
162 }
163
164 if err != nil {
165 if c.OnUsageError != nil {
166 err = c.OnUsageError(cCtx, err, !c.isRoot)
167 cCtx.App.handleExitCoder(cCtx, err)
168 return err
169 }
170 _, _ = fmt.Fprintf(cCtx.App.Writer, "%s %s\n\n", "Incorrect Usage:", err.Error())
171 if cCtx.App.Suggest {
172 if suggestion, err := c.suggestFlagFromError(err, ""); err == nil {
173 fmt.Fprintf(cCtx.App.Writer, "%s", suggestion)
174 }
175 }
176 if !c.HideHelp {
177 if c.isRoot {
178 _ = ShowAppHelp(cCtx)
179 } else {
180 _ = ShowCommandHelp(cCtx.parentContext, c.Name)
181 }
182 }
183 return err
184 }
185
186 if checkHelp(cCtx) {
187 return helpCommand.Action(cCtx)
188 }
189
190 if c.isRoot && !cCtx.App.HideVersion && checkVersion(cCtx) {
191 ShowVersion(cCtx)
192 return nil
193 }
194
195 if c.After != nil && !cCtx.shellComplete {
196 defer func() {
197 afterErr := c.After(cCtx)
198 if afterErr != nil {
199 cCtx.App.handleExitCoder(cCtx, err)
200 if err != nil {
201 err = newMultiError(err, afterErr)
202 } else {
203 err = afterErr
204 }
205 }
206 }()
207 }
208
209 cerr := cCtx.checkRequiredFlags(c.Flags)
210 if cerr != nil {
211 _ = helpCommand.Action(cCtx)
212 return cerr
213 }
214
215 if c.Before != nil && !cCtx.shellComplete {
216 beforeErr := c.Before(cCtx)
217 if beforeErr != nil {
218 cCtx.App.handleExitCoder(cCtx, beforeErr)
219 err = beforeErr
220 return err
221 }
222 }
223
224 if err = runFlagActions(cCtx, c.Flags); err != nil {
225 return err
226 }
227
228 var cmd *Command
229 args := cCtx.Args()
230 if args.Present() {
231 name := args.First()
232 cmd = c.Command(name)
233 if cmd == nil {
234 hasDefault := cCtx.App.DefaultCommand != ""
235 isFlagName := checkStringSliceIncludes(name, cCtx.FlagNames())
236
237 var (
238 isDefaultSubcommand = false
239 defaultHasSubcommands = false
240 )
241
242 if hasDefault {
243 dc := cCtx.App.Command(cCtx.App.DefaultCommand)
244 defaultHasSubcommands = len(dc.Subcommands) > 0
245 for _, dcSub := range dc.Subcommands {
246 if checkStringSliceIncludes(name, dcSub.Names()) {
247 isDefaultSubcommand = true
248 break
249 }
250 }
251 }
252
253 if isFlagName || (hasDefault && (defaultHasSubcommands && isDefaultSubcommand)) {
254 argsWithDefault := cCtx.App.argsWithDefaultCommand(args)
255 if !reflect.DeepEqual(args, argsWithDefault) {
256 cmd = cCtx.App.rootCommand.Command(argsWithDefault.First())
257 }
258 }
259 }
260 } else if c.isRoot && cCtx.App.DefaultCommand != "" {
261 if dc := cCtx.App.Command(cCtx.App.DefaultCommand); dc != c {
262 cmd = dc
263 }
264 }
265
266 if cmd != nil {
267 newcCtx := NewContext(cCtx.App, nil, cCtx)
268 newcCtx.Command = cmd
269 return cmd.Run(newcCtx, cCtx.Args().Slice()...)
270 }
271
272 if c.Action == nil {
273 c.Action = helpCommand.Action
274 }
275
276 err = c.Action(cCtx)
277
278 cCtx.App.handleExitCoder(cCtx, err)
279 return err
280 }
281
282 func (c *Command) newFlagSet() (*flag.FlagSet, error) {
283 return flagSet(c.Name, c.Flags, c.separator)
284 }
285
286 func (c *Command) useShortOptionHandling() bool {
287 return c.UseShortOptionHandling
288 }
289
290 func (c *Command) suggestFlagFromError(err error, command string) (string, error) {
291 flag, parseErr := flagFromError(err)
292 if parseErr != nil {
293 return "", err
294 }
295
296 flags := c.Flags
297 hideHelp := c.HideHelp
298 if command != "" {
299 cmd := c.Command(command)
300 if cmd == nil {
301 return "", err
302 }
303 flags = cmd.Flags
304 hideHelp = hideHelp || cmd.HideHelp
305 }
306
307 suggestion := SuggestFlag(flags, flag, hideHelp)
308 if len(suggestion) == 0 {
309 return "", err
310 }
311
312 return fmt.Sprintf(SuggestDidYouMeanTemplate, suggestion) + "\n\n", nil
313 }
314
315 func (c *Command) parseFlags(args Args, shellComplete bool) (*flag.FlagSet, error) {
316 set, err := c.newFlagSet()
317 if err != nil {
318 return nil, err
319 }
320
321 if c.SkipFlagParsing {
322 return set, set.Parse(append([]string{"--"}, args.Tail()...))
323 }
324
325 err = parseIter(set, c, args.Tail(), shellComplete)
326 if err != nil {
327 return nil, err
328 }
329
330 err = normalizeFlags(c.Flags, set)
331 if err != nil {
332 return nil, err
333 }
334
335 return set, nil
336 }
337
338 // Names returns the names including short names and aliases.
339 func (c *Command) Names() []string {
340 return append([]string{c.Name}, c.Aliases...)
341 }
342
343 // HasName returns true if Command.Name matches given name
344 func (c *Command) HasName(name string) bool {
345 for _, n := range c.Names() {
346 if n == name {
347 return true
348 }
349 }
350 return false
351 }
352
353 // VisibleCategories returns a slice of categories and commands that are
354 // Hidden=false
355 func (c *Command) VisibleCategories() []CommandCategory {
356 ret := []CommandCategory{}
357 for _, category := range c.categories.Categories() {
358 if visible := func() CommandCategory {
359 if len(category.VisibleCommands()) > 0 {
360 return category
361 }
362 return nil
363 }(); visible != nil {
364 ret = append(ret, visible)
365 }
366 }
367 return ret
368 }
369
370 // VisibleCommands returns a slice of the Commands with Hidden=false
371 func (c *Command) VisibleCommands() []*Command {
372 var ret []*Command
373 for _, command := range c.Subcommands {
374 if !command.Hidden {
375 ret = append(ret, command)
376 }
377 }
378 return ret
379 }
380
381 // VisibleFlagCategories returns a slice containing all the visible flag categories with the flags they contain
382 func (c *Command) VisibleFlagCategories() []VisibleFlagCategory {
383 if c.flagCategories == nil {
384 c.flagCategories = newFlagCategoriesFromFlags(c.Flags)
385 }
386 return c.flagCategories.VisibleCategories()
387 }
388
389 // VisibleFlags returns a slice of the Flags with Hidden=false
390 func (c *Command) VisibleFlags() []Flag {
391 return visibleFlags(c.Flags)
392 }
393
394 func (c *Command) appendFlag(fl Flag) {
395 if !hasFlag(c.Flags, fl) {
396 c.Flags = append(c.Flags, fl)
397 }
398 }
399
400 func hasCommand(commands []*Command, command *Command) bool {
401 for _, existing := range commands {
402 if command == existing {
403 return true
404 }
405 }
406
407 return false
408 }
409
410 func checkDuplicatedCmds(parent *Command) error {
411 seen := make(map[string]struct{})
412 for _, c := range parent.Subcommands {
413 for _, name := range c.Names() {
414 if _, exists := seen[name]; exists {
415 return fmt.Errorf("parent command [%s] has duplicated subcommand name or alias: %s", parent.Name, name)
416 }
417 seen[name] = struct{}{}
418 }
419 }
420 return nil
421 }