printDefaultHelp renders Cobra's built-in plain-text help by temporarily clearing the custom help function on the command and all its ancestors. Clearing only `cmd` is not enough: cobra's Help() walks up the parent chain to resolve a help func, which would re-enter wrapHelp on the still-wrapped root
(cmd *cobra.Command)
| 104 | // to resolve a help func, which would re-enter wrapHelp on the still-wrapped |
| 105 | // root and recurse forever in non-TTY mode. |
| 106 | func printDefaultHelp(cmd *cobra.Command) { |
| 107 | type saved struct { |
| 108 | cmd *cobra.Command |
| 109 | fn func(*cobra.Command, []string) |
| 110 | } |
| 111 | var stack []saved |
| 112 | for c := cmd; c != nil; c = c.Parent() { |
| 113 | stack = append(stack, saved{c, c.HelpFunc()}) |
| 114 | c.SetHelpFunc(nil) |
| 115 | } |
| 116 | cmd.Help() //nolint:errcheck // stdout write failure is non-recoverable |
| 117 | for _, s := range stack { |
| 118 | s.cmd.SetHelpFunc(s.fn) |
| 119 | } |
| 120 | } |