Sets the help function of a command to one which respects the --json-output flag.
(command *cobra.Command)
| 8 | |
| 9 | // Sets the help function of a command to one which respects the --json-output flag. |
| 10 | func setHelpFunc(command *cobra.Command) { |
| 11 | originalHelpFunc := command.HelpFunc() |
| 12 | command.SetHelpFunc(func(command *cobra.Command, strings []string) { |
| 13 | if !output.JSONOutput { |
| 14 | // Use the default help function for plain text output |
| 15 | originalHelpFunc(command, strings) |
| 16 | } else { |
| 17 | // JSON representation of a subcommand |
| 18 | type jsonSubCommand struct { |
| 19 | Name string |
| 20 | Description string |
| 21 | } |
| 22 | |
| 23 | // JSON representation of a group of commands |
| 24 | type jsonCommandGroup struct { |
| 25 | Name string |
| 26 | Commands []*jsonSubCommand |
| 27 | } |
| 28 | |
| 29 | // JSON representation of a CLI flag |
| 30 | type jsonFlag struct { |
| 31 | Name string |
| 32 | Shorthand string |
| 33 | Usage string |
| 34 | Default string |
| 35 | Deprecated string |
| 36 | Hidden bool |
| 37 | ShorthandDeprecated string |
| 38 | } |
| 39 | |
| 40 | var jsonCommands []*jsonSubCommand |
| 41 | var jsonCommandGroups []*jsonCommandGroup |
| 42 | var jsonAdditionalCommands []*jsonSubCommand |
| 43 | var jsonAdditionalHelpCommands []*jsonSubCommand |
| 44 | var jsonFlags []*jsonFlag |
| 45 | var jsonGlobalFlags []*jsonFlag |
| 46 | |
| 47 | // Build list of subcommands. Logic reflects the default "usage" template from cobra |
| 48 | if len(command.Groups()) == 0 { |
| 49 | // Direct subcommands, if there are no groups |
| 50 | for _, subCmd := range command.Commands() { |
| 51 | if subCmd.IsAvailableCommand() || subCmd.Name() == "help" { |
| 52 | jsonCommands = append(jsonCommands, &jsonSubCommand{ |
| 53 | Name: subCmd.Name(), |
| 54 | Description: subCmd.Short, |
| 55 | }) |
| 56 | } |
| 57 | } |
| 58 | } else { |
| 59 | // Groups of subcommands |
| 60 | for _, group := range command.Groups() { |
| 61 | var jsonGroupCommands []*jsonSubCommand |
| 62 | for _, subCmd := range command.Commands() { |
| 63 | if subCmd.GroupID == group.ID || (subCmd.IsAvailableCommand() || subCmd.Name() == "help") { |
| 64 | jsonGroupCommands = append(jsonGroupCommands, &jsonSubCommand{ |
| 65 | Name: subCmd.Name(), |
| 66 | Description: subCmd.Short, |
| 67 | }) |