Debian Codegraph @

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

raw
1 package cli
2
3 import (
4 "context"
5 "flag"
6 "fmt"
7 "io"
8 "os"
9 "path/filepath"
10 "sort"
11 "strings"
12 "time"
13 )
14
15 const suggestDidYouMeanTemplate = "Did you mean %q?"
16
17 var (
18 changeLogURL = "https://github.com/urfave/cli/blob/main/docs/CHANGELOG.md"
19 appActionDeprecationURL = fmt.Sprintf("%s#deprecated-cli-app-action-signature", changeLogURL)
20 contactSysadmin = "This is an error in the application. Please contact the distributor of this application if this is not you."
21 errInvalidActionType = NewExitError("ERROR invalid Action type. "+
22 fmt.Sprintf("Must be `func(*Context`)` or `func(*Context) error). %s", contactSysadmin)+
23 fmt.Sprintf("See %s", appActionDeprecationURL), 2)
24 ignoreFlagPrefix = "test." // this is to ignore test flags when adding flags from other packages
25
26 SuggestFlag SuggestFlagFunc = nil // initialized in suggestions.go unless built with urfave_cli_no_suggest
27 SuggestCommand SuggestCommandFunc = nil // initialized in suggestions.go unless built with urfave_cli_no_suggest
28 SuggestDidYouMeanTemplate string = suggestDidYouMeanTemplate
29 )
30
31 // App is the main structure of a cli application. It is recommended that
32 // an app be created with the cli.NewApp() function
33 type App struct {
34 // The name of the program. Defaults to path.Base(os.Args[0])
35 Name string
36 // Full name of command for help, defaults to Name
37 HelpName string
38 // Description of the program.
39 Usage string
40 // Text to override the USAGE section of help
41 UsageText string
42 // Whether this command supports arguments
43 Args bool
44 // Description of the program argument format.
45 ArgsUsage string
46 // Version of the program
47 Version string
48 // Description of the program
49 Description string
50 // DefaultCommand is the (optional) name of a command
51 // to run if no command names are passed as CLI arguments.
52 DefaultCommand string
53 // List of commands to execute
54 Commands []*Command
55 // List of flags to parse
56 Flags []Flag
57 // Boolean to enable bash completion commands
58 EnableBashCompletion bool
59 // Boolean to hide built-in help command and help flag
60 HideHelp bool
61 // Boolean to hide built-in help command but keep help flag.
62 // Ignored if HideHelp is true.
63 HideHelpCommand bool
64 // Boolean to hide built-in version flag and the VERSION section of help
65 HideVersion bool
66 // categories contains the categorized commands and is populated on app startup
67 categories CommandCategories
68 // flagCategories contains the categorized flags and is populated on app startup
69 flagCategories FlagCategories
70 // An action to execute when the shell completion flag is set
71 BashComplete BashCompleteFunc
72 // An action to execute before any subcommands are run, but after the context is ready
73 // If a non-nil error is returned, no subcommands are run
74 Before BeforeFunc
75 // An action to execute after any subcommands are run, but after the subcommand has finished
76 // It is run even if Action() panics
77 After AfterFunc
78 // The action to execute when no subcommands are specified
79 Action ActionFunc
80 // Execute this function if the proper command cannot be found
81 CommandNotFound CommandNotFoundFunc
82 // Execute this function if a usage error occurs
83 OnUsageError OnUsageErrorFunc
84 // Execute this function when an invalid flag is accessed from the context
85 InvalidFlagAccessHandler InvalidFlagAccessFunc
86 // Compilation date
87 Compiled time.Time
88 // List of all authors who contributed
89 Authors []*Author
90 // Copyright of the binary if any
91 Copyright string
92 // Reader reader to write input to (useful for tests)
93 Reader io.Reader
94 // Writer writer to write output to
95 Writer io.Writer
96 // ErrWriter writes error output
97 ErrWriter io.Writer
98 // ExitErrHandler processes any error encountered while running an App before
99 // it is returned to the caller. If no function is provided, HandleExitCoder
100 // is used as the default behavior.
101 ExitErrHandler ExitErrHandlerFunc
102 // Other custom info
103 Metadata map[string]interface{}
104 // Carries a function which returns app specific info.
105 ExtraInfo func() map[string]string
106 // CustomAppHelpTemplate the text template for app help topic.
107 // cli.go uses text/template to render templates. You can
108 // render custom help text by setting this variable.
109 CustomAppHelpTemplate string
110 // SliceFlagSeparator is used to customize the separator for SliceFlag, the default is ","
111 SliceFlagSeparator string
112 // DisableSliceFlagSeparator is used to disable SliceFlagSeparator, the default is false
113 DisableSliceFlagSeparator bool
114 // Boolean to enable short-option handling so user can combine several
115 // single-character bool arguments into one
116 // i.e. foobar -o -v -> foobar -ov
117 UseShortOptionHandling bool
118 // Enable suggestions for commands and flags
119 Suggest bool
120 // Allows global flags set by libraries which use flag.XXXVar(...) directly
121 // to be parsed through this library
122 AllowExtFlags bool
123 // Treat all flags as normal arguments if true
124 SkipFlagParsing bool
125
126 didSetup bool
127 separator separatorSpec
128
129 rootCommand *Command
130 }
131
132 type SuggestFlagFunc func(flags []Flag, provided string, hideHelp bool) string
133
134 type SuggestCommandFunc func(commands []*Command, provided string) string
135
136 // Tries to find out when this binary was compiled.
137 // Returns the current time if it fails to find it.
138 func compileTime() time.Time {
139 info, err := os.Stat(os.Args[0])
140 if err != nil {
141 return time.Now()
142 }
143 return info.ModTime()
144 }
145
146 // NewApp creates a new cli Application with some reasonable defaults for Name,
147 // Usage, Version and Action.
148 func NewApp() *App {
149 return &App{
150 Name: filepath.Base(os.Args[0]),
151 Usage: "A new cli application",
152 UsageText: "",
153 BashComplete: DefaultAppComplete,
154 Action: helpCommand.Action,
155 Compiled: compileTime(),
156 Reader: os.Stdin,
157 Writer: os.Stdout,
158 ErrWriter: os.Stderr,
159 }
160 }
161
162 // Setup runs initialization code to ensure all data structures are ready for
163 // `Run` or inspection prior to `Run`. It is internally called by `Run`, but
164 // will return early if setup has already happened.
165 func (a *App) Setup() {
166 if a.didSetup {
167 return
168 }
169
170 a.didSetup = true
171
172 if a.Name == "" {
173 a.Name = filepath.Base(os.Args[0])
174 }
175
176 if a.HelpName == "" {
177 a.HelpName = a.Name
178 }
179
180 if a.Usage == "" {
181 a.Usage = "A new cli application"
182 }
183
184 if a.Version == "" {
185 a.HideVersion = true
186 }
187
188 if a.BashComplete == nil {
189 a.BashComplete = DefaultAppComplete
190 }
191
192 if a.Action == nil {
193 a.Action = helpCommand.Action
194 }
195
196 if a.Compiled == (time.Time{}) {
197 a.Compiled = compileTime()
198 }
199
200 if a.Reader == nil {
201 a.Reader = os.Stdin
202 }
203
204 if a.Writer == nil {
205 a.Writer = os.Stdout
206 }
207
208 if a.ErrWriter == nil {
209 a.ErrWriter = os.Stderr
210 }
211
212 if a.AllowExtFlags {
213 // add global flags added by other packages
214 flag.VisitAll(func(f *flag.Flag) {
215 // skip test flags
216 if !strings.HasPrefix(f.Name, ignoreFlagPrefix) {
217 a.Flags = append(a.Flags, &extFlag{f})
218 }
219 })
220 }
221
222 if len(a.SliceFlagSeparator) != 0 {
223 a.separator.customized = true
224 a.separator.sep = a.SliceFlagSeparator
225 }
226
227 if a.DisableSliceFlagSeparator {
228 a.separator.customized = true
229 a.separator.disabled = true
230 }
231
232 for _, c := range a.Commands {
233 cname := c.Name
234 if c.HelpName != "" {
235 cname = c.HelpName
236 }
237 c.separator = a.separator
238 c.HelpName = fmt.Sprintf("%s %s", a.HelpName, cname)
239 c.flagCategories = newFlagCategoriesFromFlags(c.Flags)
240 }
241
242 if a.Command(helpCommand.Name) == nil && !a.HideHelp {
243 if !a.HideHelpCommand {
244 a.appendCommand(helpCommand)
245 }
246
247 if HelpFlag != nil {
248 a.appendFlag(HelpFlag)
249 }
250 }
251
252 if !a.HideVersion {
253 a.appendFlag(VersionFlag)
254 }
255
256 a.categories = newCommandCategories()
257 for _, command := range a.Commands {
258 a.categories.AddCommand(command.Category, command)
259 }
260 sort.Sort(a.categories.(*commandCategories))
261
262 a.flagCategories = newFlagCategoriesFromFlags(a.Flags)
263
264 if a.Metadata == nil {
265 a.Metadata = make(map[string]interface{})
266 }
267 }
268
269 func (a *App) newRootCommand() *Command {
270 return &Command{
271 Name: a.Name,
272 Usage: a.Usage,
273 UsageText: a.UsageText,
274 Description: a.Description,
275 ArgsUsage: a.ArgsUsage,
276 BashComplete: a.BashComplete,
277 Before: a.Before,
278 After: a.After,
279 Action: a.Action,
280 OnUsageError: a.OnUsageError,
281 Subcommands: a.Commands,
282 Flags: a.Flags,
283 flagCategories: a.flagCategories,
284 HideHelp: a.HideHelp,
285 HideHelpCommand: a.HideHelpCommand,
286 UseShortOptionHandling: a.UseShortOptionHandling,
287 HelpName: a.HelpName,
288 CustomHelpTemplate: a.CustomAppHelpTemplate,
289 categories: a.categories,
290 SkipFlagParsing: a.SkipFlagParsing,
291 isRoot: true,
292 separator: a.separator,
293 }
294 }
295
296 func (a *App) newFlagSet() (*flag.FlagSet, error) {
297 return flagSet(a.Name, a.Flags, a.separator)
298 }
299
300 func (a *App) useShortOptionHandling() bool {
301 return a.UseShortOptionHandling
302 }
303
304 // Run is the entry point to the cli app. Parses the arguments slice and routes
305 // to the proper flag/args combination
306 func (a *App) Run(arguments []string) (err error) {
307 return a.RunContext(context.Background(), arguments)
308 }
309
310 // RunContext is like Run except it takes a Context that will be
311 // passed to its commands and sub-commands. Through this, you can
312 // propagate timeouts and cancellation requests
313 func (a *App) RunContext(ctx context.Context, arguments []string) (err error) {
314 a.Setup()
315
316 // handle the completion flag separately from the flagset since
317 // completion could be attempted after a flag, but before its value was put
318 // on the command line. this causes the flagset to interpret the completion
319 // flag name as the value of the flag before it which is undesirable
320 // note that we can only do this because the shell autocomplete function
321 // always appends the completion flag at the end of the command
322 shellComplete, arguments := checkShellCompleteFlag(a, arguments)
323
324 cCtx := NewContext(a, nil, &Context{Context: ctx})
325 cCtx.shellComplete = shellComplete
326
327 a.rootCommand = a.newRootCommand()
328 cCtx.Command = a.rootCommand
329
330 if err := checkDuplicatedCmds(a.rootCommand); err != nil {
331 return err
332 }
333 return a.rootCommand.Run(cCtx, arguments...)
334 }
335
336 // RunAsSubcommand is for legacy/compatibility purposes only. New code should only
337 // use App.RunContext. This function is slated to be removed in v3.
338 func (a *App) RunAsSubcommand(ctx *Context) (err error) {
339 a.Setup()
340
341 cCtx := NewContext(a, nil, ctx)
342 cCtx.shellComplete = ctx.shellComplete
343
344 a.rootCommand = a.newRootCommand()
345 cCtx.Command = a.rootCommand
346
347 return a.rootCommand.Run(cCtx, ctx.Args().Slice()...)
348 }
349
350 func (a *App) suggestFlagFromError(err error, command string) (string, error) {
351 flag, parseErr := flagFromError(err)
352 if parseErr != nil {
353 return "", err
354 }
355
356 flags := a.Flags
357 hideHelp := a.HideHelp
358 if command != "" {
359 cmd := a.Command(command)
360 if cmd == nil {
361 return "", err
362 }
363 flags = cmd.Flags
364 hideHelp = hideHelp || cmd.HideHelp
365 }
366
367 if SuggestFlag == nil {
368 return "", err
369 }
370 suggestion := SuggestFlag(flags, flag, hideHelp)
371 if len(suggestion) == 0 {
372 return "", err
373 }
374
375 return fmt.Sprintf(SuggestDidYouMeanTemplate+"\n\n", suggestion), nil
376 }
377
378 // RunAndExitOnError calls .Run() and exits non-zero if an error was returned
379 //
380 // Deprecated: instead you should return an error that fulfills cli.ExitCoder
381 // to cli.App.Run. This will cause the application to exit with the given error
382 // code in the cli.ExitCoder
383 func (a *App) RunAndExitOnError() {
384 if err := a.Run(os.Args); err != nil {
385 _, _ = fmt.Fprintln(a.ErrWriter, err)
386 OsExiter(1)
387 }
388 }
389
390 // Command returns the named command on App. Returns nil if the command does not exist
391 func (a *App) Command(name string) *Command {
392 for _, c := range a.Commands {
393 if c.HasName(name) {
394 return c
395 }
396 }
397
398 return nil
399 }
400
401 // VisibleCategories returns a slice of categories and commands that are
402 // Hidden=false
403 func (a *App) VisibleCategories() []CommandCategory {
404 ret := []CommandCategory{}
405 for _, category := range a.categories.Categories() {
406 if visible := func() CommandCategory {
407 if len(category.VisibleCommands()) > 0 {
408 return category
409 }
410 return nil
411 }(); visible != nil {
412 ret = append(ret, visible)
413 }
414 }
415 return ret
416 }
417
418 // VisibleCommands returns a slice of the Commands with Hidden=false
419 func (a *App) VisibleCommands() []*Command {
420 var ret []*Command
421 for _, command := range a.Commands {
422 if !command.Hidden {
423 ret = append(ret, command)
424 }
425 }
426 return ret
427 }
428
429 // VisibleFlagCategories returns a slice containing all the categories with the flags they contain
430 func (a *App) VisibleFlagCategories() []VisibleFlagCategory {
431 if a.flagCategories == nil {
432 return []VisibleFlagCategory{}
433 }
434 return a.flagCategories.VisibleCategories()
435 }
436
437 // VisibleFlags returns a slice of the Flags with Hidden=false
438 func (a *App) VisibleFlags() []Flag {
439 return visibleFlags(a.Flags)
440 }
441
442 func (a *App) appendFlag(fl Flag) {
443 if !hasFlag(a.Flags, fl) {
444 a.Flags = append(a.Flags, fl)
445 }
446 }
447
448 func (a *App) appendCommand(c *Command) {
449 if !hasCommand(a.Commands, c) {
450 a.Commands = append(a.Commands, c)
451 }
452 }
453
454 func (a *App) handleExitCoder(cCtx *Context, err error) {
455 if a.ExitErrHandler != nil {
456 a.ExitErrHandler(cCtx, err)
457 } else {
458 HandleExitCoder(err)
459 }
460 }
461
462 func (a *App) argsWithDefaultCommand(oldArgs Args) Args {
463 if a.DefaultCommand != "" {
464 rawArgs := append([]string{a.DefaultCommand}, oldArgs.Slice()...)
465 newArgs := args(rawArgs)
466
467 return &newArgs
468 }
469
470 return oldArgs
471 }
472
473 func runFlagActions(c *Context, fs []Flag) error {
474 for _, f := range fs {
475 isSet := false
476 for _, name := range f.Names() {
477 if c.IsSet(name) {
478 isSet = true
479 break
480 }
481 }
482 if isSet {
483 if af, ok := f.(ActionableFlag); ok {
484 if err := af.RunAction(c); err != nil {
485 return err
486 }
487 }
488 }
489 }
490 return nil
491 }
492
493 // Author represents someone who has contributed to a cli project.
494 type Author struct {
495 Name string // The Authors name
496 Email string // The Authors email
497 }
498
499 // String makes Author comply to the Stringer interface, to allow an easy print in the templating process
500 func (a *Author) String() string {
501 e := ""
502 if a.Email != "" {
503 e = " <" + a.Email + ">"
504 }
505
506 return fmt.Sprintf("%v%v", a.Name, e)
507 }
508
509 // HandleAction attempts to figure out which Action signature was used. If
510 // it's an ActionFunc or a func with the legacy signature for Action, the func
511 // is run!
512 func HandleAction(action interface{}, cCtx *Context) (err error) {
513 switch a := action.(type) {
514 case ActionFunc:
515 return a(cCtx)
516 case func(*Context) error:
517 return a(cCtx)
518 case func(*Context): // deprecated function signature
519 a(cCtx)
520 return nil
521 }
522
523 return errInvalidActionType
524 }
525
526 func checkStringSliceIncludes(want string, sSlice []string) bool {
527 found := false
528 for _, s := range sSlice {
529 if want == s {
530 found = true
531 break
532 }
533 }
534
535 return found
536 }