Debian Codegraph @

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

raw
1 package cli
2
3 import (
4 "fmt"
5 "io"
6 "os"
7 "strings"
8 "text/tabwriter"
9 "text/template"
10 "unicode/utf8"
11 )
12
13 const (
14 helpName = "help"
15 helpAlias = "h"
16 )
17
18 // this instance is to avoid recursion in the ShowCommandHelp which can
19 // add a help command again
20 var helpCommandDontUse = &Command{
21 Name: helpName,
22 Aliases: []string{helpAlias},
23 Usage: "Shows a list of commands or help for one command",
24 ArgsUsage: "[command]",
25 }
26
27 var helpCommand = &Command{
28 Name: helpName,
29 Aliases: []string{helpAlias},
30 Usage: "Shows a list of commands or help for one command",
31 ArgsUsage: "[command]",
32 Action: func(cCtx *Context) error {
33 args := cCtx.Args()
34 argsPresent := args.First() != ""
35 firstArg := args.First()
36
37 // This action can be triggered by a "default" action of a command
38 // or via cmd.Run when cmd == helpCmd. So we have following possibilities
39 //
40 // 1 $ app
41 // 2 $ app help
42 // 3 $ app foo
43 // 4 $ app help foo
44 // 5 $ app foo help
45 // 6 $ app foo -h (with no other sub-commands nor flags defined)
46
47 // Case 4. when executing a help command set the context to parent
48 // to allow resolution of subsequent args. This will transform
49 // $ app help foo
50 // to
51 // $ app foo
52 // which will then be handled as case 3
53 if cCtx.Command.Name == helpName || cCtx.Command.Name == helpAlias {
54 cCtx = cCtx.parentContext
55 }
56
57 // Case 4. $ app help foo
58 // foo is the command for which help needs to be shown
59 if argsPresent {
60 return ShowCommandHelp(cCtx, firstArg)
61 }
62
63 // Case 1 & 2
64 // Special case when running help on main app itself as opposed to individual
65 // commands/subcommands
66 if cCtx.parentContext.App == nil {
67 _ = ShowAppHelp(cCtx)
68 return nil
69 }
70
71 // Case 3, 5
72 if (len(cCtx.Command.Subcommands) == 1 && !cCtx.Command.HideHelp && !cCtx.Command.HideHelpCommand) ||
73 (len(cCtx.Command.Subcommands) == 0 && cCtx.Command.HideHelp) {
74 templ := cCtx.Command.CustomHelpTemplate
75 if templ == "" {
76 templ = CommandHelpTemplate
77 }
78 HelpPrinter(cCtx.App.Writer, templ, cCtx.Command)
79 return nil
80 }
81
82 // Case 6, handling incorporated in the callee itself
83 return ShowSubcommandHelp(cCtx)
84 },
85 }
86
87 // Prints help for the App or Command
88 type helpPrinter func(w io.Writer, templ string, data interface{})
89
90 // Prints help for the App or Command with custom template function.
91 type helpPrinterCustom func(w io.Writer, templ string, data interface{}, customFunc map[string]interface{})
92
93 // HelpPrinter is a function that writes the help output. If not set explicitly,
94 // this calls HelpPrinterCustom using only the default template functions.
95 //
96 // If custom logic for printing help is required, this function can be
97 // overridden. If the ExtraInfo field is defined on an App, this function
98 // should not be modified, as HelpPrinterCustom will be used directly in order
99 // to capture the extra information.
100 var HelpPrinter helpPrinter = printHelp
101
102 // HelpPrinterCustom is a function that writes the help output. It is used as
103 // the default implementation of HelpPrinter, and may be called directly if
104 // the ExtraInfo field is set on an App.
105 //
106 // In the default implementation, if the customFuncs argument contains a
107 // "wrapAt" key, which is a function which takes no arguments and returns
108 // an int, this int value will be used to produce a "wrap" function used
109 // by the default template to wrap long lines.
110 var HelpPrinterCustom helpPrinterCustom = printHelpCustom
111
112 // VersionPrinter prints the version for the App
113 var VersionPrinter = printVersion
114
115 // ShowAppHelpAndExit - Prints the list of subcommands for the app and exits with exit code.
116 func ShowAppHelpAndExit(c *Context, exitCode int) {
117 _ = ShowAppHelp(c)
118 os.Exit(exitCode)
119 }
120
121 // ShowAppHelp is an action that displays the help.
122 func ShowAppHelp(cCtx *Context) error {
123 tpl := cCtx.App.CustomAppHelpTemplate
124 if tpl == "" {
125 tpl = AppHelpTemplate
126 }
127
128 if cCtx.App.ExtraInfo == nil {
129 HelpPrinter(cCtx.App.Writer, tpl, cCtx.App)
130 return nil
131 }
132
133 customAppData := func() map[string]interface{} {
134 return map[string]interface{}{
135 "ExtraInfo": cCtx.App.ExtraInfo,
136 }
137 }
138 HelpPrinterCustom(cCtx.App.Writer, tpl, cCtx.App, customAppData())
139
140 return nil
141 }
142
143 // DefaultAppComplete prints the list of subcommands as the default app completion method
144 func DefaultAppComplete(cCtx *Context) {
145 DefaultCompleteWithFlags(nil)(cCtx)
146 }
147
148 func printCommandSuggestions(commands []*Command, writer io.Writer) {
149 for _, command := range commands {
150 if command.Hidden {
151 continue
152 }
153 if strings.HasSuffix(os.Getenv("0"), "zsh") {
154 for _, name := range command.Names() {
155 _, _ = fmt.Fprintf(writer, "%s:%s\n", name, command.Usage)
156 }
157 } else {
158 for _, name := range command.Names() {
159 _, _ = fmt.Fprintf(writer, "%s\n", name)
160 }
161 }
162 }
163 }
164
165 func cliArgContains(flagName string) bool {
166 for _, name := range strings.Split(flagName, ",") {
167 name = strings.TrimSpace(name)
168 count := utf8.RuneCountInString(name)
169 if count > 2 {
170 count = 2
171 }
172 flag := fmt.Sprintf("%s%s", strings.Repeat("-", count), name)
173 for _, a := range os.Args {
174 if a == flag {
175 return true
176 }
177 }
178 }
179 return false
180 }
181
182 func printFlagSuggestions(lastArg string, flags []Flag, writer io.Writer) {
183 cur := strings.TrimPrefix(lastArg, "-")
184 cur = strings.TrimPrefix(cur, "-")
185 for _, flag := range flags {
186 if bflag, ok := flag.(*BoolFlag); ok && bflag.Hidden {
187 continue
188 }
189 for _, name := range flag.Names() {
190 name = strings.TrimSpace(name)
191 // this will get total count utf8 letters in flag name
192 count := utf8.RuneCountInString(name)
193 if count > 2 {
194 count = 2 // reuse this count to generate single - or -- in flag completion
195 }
196 // if flag name has more than one utf8 letter and last argument in cli has -- prefix then
197 // skip flag completion for short flags example -v or -x
198 if strings.HasPrefix(lastArg, "--") && count == 1 {
199 continue
200 }
201 // match if last argument matches this flag and it is not repeated
202 if strings.HasPrefix(name, cur) && cur != name && !cliArgContains(name) {
203 flagCompletion := fmt.Sprintf("%s%s", strings.Repeat("-", count), name)
204 _, _ = fmt.Fprintln(writer, flagCompletion)
205 }
206 }
207 }
208 }
209
210 func DefaultCompleteWithFlags(cmd *Command) func(cCtx *Context) {
211 return func(cCtx *Context) {
212 var lastArg string
213
214 // TODO: This shouldnt depend on os.Args rather it should
215 // depend on root arguments passed to App
216 if len(os.Args) > 2 {
217 lastArg = os.Args[len(os.Args)-2]
218 }
219
220 if lastArg != "" {
221 if strings.HasPrefix(lastArg, "-") {
222 if cmd != nil {
223 printFlagSuggestions(lastArg, cmd.Flags, cCtx.App.Writer)
224
225 return
226 }
227
228 printFlagSuggestions(lastArg, cCtx.App.Flags, cCtx.App.Writer)
229
230 return
231 }
232 }
233
234 if cmd != nil {
235 printCommandSuggestions(cmd.Subcommands, cCtx.App.Writer)
236 return
237 }
238
239 printCommandSuggestions(cCtx.Command.Subcommands, cCtx.App.Writer)
240 }
241 }
242
243 // ShowCommandHelpAndExit - exits with code after showing help
244 func ShowCommandHelpAndExit(c *Context, command string, code int) {
245 _ = ShowCommandHelp(c, command)
246 os.Exit(code)
247 }
248
249 // ShowCommandHelp prints help for the given command
250 func ShowCommandHelp(ctx *Context, command string) error {
251 commands := ctx.App.Commands
252 if ctx.Command.Subcommands != nil {
253 commands = ctx.Command.Subcommands
254 }
255 for _, c := range commands {
256 if c.HasName(command) {
257 if !ctx.App.HideHelpCommand && !c.HasName(helpName) && len(c.Subcommands) != 0 && c.Command(helpName) == nil {
258 c.Subcommands = append(c.Subcommands, helpCommandDontUse)
259 }
260 if !ctx.App.HideHelp && HelpFlag != nil {
261 c.appendFlag(HelpFlag)
262 }
263 templ := c.CustomHelpTemplate
264 if templ == "" {
265 if len(c.Subcommands) == 0 {
266 templ = CommandHelpTemplate
267 } else {
268 templ = SubcommandHelpTemplate
269 }
270 }
271
272 HelpPrinter(ctx.App.Writer, templ, c)
273
274 return nil
275 }
276 }
277
278 if ctx.App.CommandNotFound == nil {
279 errMsg := fmt.Sprintf("No help topic for '%v'", command)
280 if ctx.App.Suggest && SuggestCommand != nil {
281 if suggestion := SuggestCommand(ctx.Command.Subcommands, command); suggestion != "" {
282 errMsg += ". " + suggestion
283 }
284 }
285 return Exit(errMsg, 3)
286 }
287
288 ctx.App.CommandNotFound(ctx, command)
289 return nil
290 }
291
292 // ShowSubcommandHelpAndExit - Prints help for the given subcommand and exits with exit code.
293 func ShowSubcommandHelpAndExit(c *Context, exitCode int) {
294 _ = ShowSubcommandHelp(c)
295 os.Exit(exitCode)
296 }
297
298 // ShowSubcommandHelp prints help for the given subcommand
299 func ShowSubcommandHelp(cCtx *Context) error {
300 if cCtx == nil {
301 return nil
302 }
303 // use custom template when provided (fixes #1703)
304 templ := SubcommandHelpTemplate
305 if cCtx.Command != nil && cCtx.Command.CustomHelpTemplate != "" {
306 templ = cCtx.Command.CustomHelpTemplate
307 }
308 HelpPrinter(cCtx.App.Writer, templ, cCtx.Command)
309 return nil
310 }
311
312 // ShowVersion prints the version number of the App
313 func ShowVersion(cCtx *Context) {
314 VersionPrinter(cCtx)
315 }
316
317 func printVersion(cCtx *Context) {
318 _, _ = fmt.Fprintf(cCtx.App.Writer, "%v version %v\n", cCtx.App.Name, cCtx.App.Version)
319 }
320
321 // ShowCompletions prints the lists of commands within a given context
322 func ShowCompletions(cCtx *Context) {
323 c := cCtx.Command
324 if c != nil && c.BashComplete != nil {
325 c.BashComplete(cCtx)
326 }
327 }
328
329 // ShowCommandCompletions prints the custom completions for a given command
330 func ShowCommandCompletions(ctx *Context, command string) {
331 c := ctx.Command.Command(command)
332 if c != nil {
333 if c.BashComplete != nil {
334 c.BashComplete(ctx)
335 } else {
336 DefaultCompleteWithFlags(c)(ctx)
337 }
338 }
339 }
340
341 // printHelpCustom is the default implementation of HelpPrinterCustom.
342 //
343 // The customFuncs map will be combined with a default template.FuncMap to
344 // allow using arbitrary functions in template rendering.
345 func printHelpCustom(out io.Writer, templ string, data interface{}, customFuncs map[string]interface{}) {
346 const maxLineLength = 10000
347
348 funcMap := template.FuncMap{
349 "join": strings.Join,
350 "subtract": subtract,
351 "indent": indent,
352 "nindent": nindent,
353 "trim": strings.TrimSpace,
354 "wrap": func(input string, offset int) string { return wrap(input, offset, maxLineLength) },
355 "offset": offset,
356 "offsetCommands": offsetCommands,
357 }
358
359 if customFuncs["wrapAt"] != nil {
360 if wa, ok := customFuncs["wrapAt"]; ok {
361 if waf, ok := wa.(func() int); ok {
362 wrapAt := waf()
363 customFuncs["wrap"] = func(input string, offset int) string {
364 return wrap(input, offset, wrapAt)
365 }
366 }
367 }
368 }
369
370 for key, value := range customFuncs {
371 funcMap[key] = value
372 }
373
374 w := tabwriter.NewWriter(out, 1, 8, 2, ' ', 0)
375 t := template.Must(template.New("help").Funcs(funcMap).Parse(templ))
376 templates := map[string]string{
377 "helpNameTemplate": helpNameTemplate,
378 "usageTemplate": usageTemplate,
379 "descriptionTemplate": descriptionTemplate,
380 "visibleCommandTemplate": visibleCommandTemplate,
381 "copyrightTemplate": copyrightTemplate,
382 "versionTemplate": versionTemplate,
383 "visibleFlagCategoryTemplate": visibleFlagCategoryTemplate,
384 "visibleFlagTemplate": visibleFlagTemplate,
385 "visibleGlobalFlagCategoryTemplate": strings.Replace(visibleFlagCategoryTemplate, "OPTIONS", "GLOBAL OPTIONS", -1),
386 "authorsTemplate": authorsTemplate,
387 "visibleCommandCategoryTemplate": visibleCommandCategoryTemplate,
388 }
389 for name, value := range templates {
390 if _, err := t.New(name).Parse(value); err != nil {
391 if os.Getenv("CLI_TEMPLATE_ERROR_DEBUG") != "" {
392 _, _ = fmt.Fprintf(ErrWriter, "CLI TEMPLATE ERROR: %#v\n", err)
393 }
394 }
395 }
396
397 err := t.Execute(w, data)
398 if err != nil {
399 // If the writer is closed, t.Execute will fail, and there's nothing
400 // we can do to recover.
401 if os.Getenv("CLI_TEMPLATE_ERROR_DEBUG") != "" {
402 _, _ = fmt.Fprintf(ErrWriter, "CLI TEMPLATE ERROR: %#v\n", err)
403 }
404 return
405 }
406 _ = w.Flush()
407 }
408
409 func printHelp(out io.Writer, templ string, data interface{}) {
410 HelpPrinterCustom(out, templ, data, nil)
411 }
412
413 func checkVersion(cCtx *Context) bool {
414 found := false
415 for _, name := range VersionFlag.Names() {
416 if cCtx.Bool(name) {
417 found = true
418 }
419 }
420 return found
421 }
422
423 func checkHelp(cCtx *Context) bool {
424 if HelpFlag == nil {
425 return false
426 }
427 found := false
428 for _, name := range HelpFlag.Names() {
429 if cCtx.Bool(name) {
430 found = true
431 break
432 }
433 }
434
435 return found
436 }
437
438 func checkShellCompleteFlag(a *App, arguments []string) (bool, []string) {
439 if !a.EnableBashCompletion {
440 return false, arguments
441 }
442
443 pos := len(arguments) - 1
444 lastArg := arguments[pos]
445
446 if lastArg != "--generate-bash-completion" {
447 return false, arguments
448 }
449
450 for _, arg := range arguments {
451 // If arguments include "--", shell completion is disabled
452 // because after "--" only positional arguments are accepted.
453 // https://unix.stackexchange.com/a/11382
454 if arg == "--" {
455 return false, arguments
456 }
457 }
458
459 return true, arguments[:pos]
460 }
461
462 func checkCompletions(cCtx *Context) bool {
463 if !cCtx.shellComplete {
464 return false
465 }
466
467 if args := cCtx.Args(); args.Present() {
468 name := args.First()
469 if cmd := cCtx.Command.Command(name); cmd != nil {
470 // let the command handle the completion
471 return false
472 }
473 }
474
475 ShowCompletions(cCtx)
476 return true
477 }
478
479 func subtract(a, b int) int {
480 return a - b
481 }
482
483 func indent(spaces int, v string) string {
484 pad := strings.Repeat(" ", spaces)
485 return pad + strings.Replace(v, "\n", "\n"+pad, -1)
486 }
487
488 func nindent(spaces int, v string) string {
489 return "\n" + indent(spaces, v)
490 }
491
492 func wrap(input string, offset int, wrapAt int) string {
493 var ss []string
494
495 lines := strings.Split(input, "\n")
496
497 padding := strings.Repeat(" ", offset)
498
499 for i, line := range lines {
500 if line == "" {
501 ss = append(ss, line)
502 } else {
503 wrapped := wrapLine(line, offset, wrapAt, padding)
504 if i == 0 {
505 ss = append(ss, wrapped)
506 } else {
507 ss = append(ss, padding+wrapped)
508 }
509
510 }
511 }
512
513 return strings.Join(ss, "\n")
514 }
515
516 func wrapLine(input string, offset int, wrapAt int, padding string) string {
517 if wrapAt <= offset || len(input) <= wrapAt-offset {
518 return input
519 }
520
521 lineWidth := wrapAt - offset
522 words := strings.Fields(input)
523 if len(words) == 0 {
524 return input
525 }
526
527 wrapped := words[0]
528 spaceLeft := lineWidth - len(wrapped)
529 for _, word := range words[1:] {
530 if len(word)+1 > spaceLeft {
531 wrapped += "\n" + padding + word
532 spaceLeft = lineWidth - len(word)
533 } else {
534 wrapped += " " + word
535 spaceLeft -= 1 + len(word)
536 }
537 }
538
539 return wrapped
540 }
541
542 func offset(input string, fixed int) int {
543 return len(input) + fixed
544 }
545
546 // this function tries to find the max width of the names column
547 // so say we have the following rows for help
548 //
549 // foo1, foo2, foo3 some string here
550 // bar1, b2 some other string here
551 //
552 // We want to offset the 2nd row usage by some amount so that everything
553 // is aligned
554 //
555 // foo1, foo2, foo3 some string here
556 // bar1, b2 some other string here
557 //
558 // to find that offset we find the length of all the rows and use the max
559 // to calculate the offset
560 func offsetCommands(cmds []*Command, fixed int) int {
561 var max int = 0
562 for _, cmd := range cmds {
563 s := strings.Join(cmd.Names(), ", ")
564 if len(s) > max {
565 max = len(s)
566 }
567 }
568 return max + fixed
569 }