Debian Codegraph @

help.go

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