help.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package help
  14. import (
  15. "strings"
  16. "github.com/spf13/cobra"
  17. "k8s.io/kubernetes/pkg/kubectl/util/i18n"
  18. "k8s.io/kubernetes/pkg/kubectl/util/templates"
  19. )
  20. var helpLong = templates.LongDesc(i18n.T(`
  21. Help provides help for any command in the application.
  22. Simply type kubectl help [path to command] for full details.`))
  23. // NewCmdHelp returns the help Cobra command
  24. func NewCmdHelp() *cobra.Command {
  25. cmd := &cobra.Command{
  26. Use: "help [command] | STRING_TO_SEARCH",
  27. DisableFlagsInUseLine: true,
  28. Short: i18n.T("Help about any command"),
  29. Long: helpLong,
  30. Run: RunHelp,
  31. }
  32. return cmd
  33. }
  34. // RunHelp checks given arguments and executes command
  35. func RunHelp(cmd *cobra.Command, args []string) {
  36. foundCmd, _, err := cmd.Root().Find(args)
  37. // NOTE(andreykurilin): actually, I did not find any cases when foundCmd can be nil,
  38. // but let's make this check since it is included in original code of initHelpCmd
  39. // from github.com/spf13/cobra
  40. if foundCmd == nil {
  41. cmd.Printf("Unknown help topic %#q.\n", args)
  42. cmd.Root().Usage()
  43. } else if err != nil {
  44. // print error message at first, since it can contain suggestions
  45. cmd.Println(err)
  46. argsString := strings.Join(args, " ")
  47. var matchedMsgIsPrinted = false
  48. for _, foundCmd := range foundCmd.Commands() {
  49. if strings.Contains(foundCmd.Short, argsString) {
  50. if !matchedMsgIsPrinted {
  51. cmd.Printf("Matchers of string '%s' in short descriptions of commands: \n", argsString)
  52. matchedMsgIsPrinted = true
  53. }
  54. cmd.Printf(" %-14s %s\n", foundCmd.Name(), foundCmd.Short)
  55. }
  56. }
  57. if !matchedMsgIsPrinted {
  58. // if nothing is found, just print usage
  59. cmd.Root().Usage()
  60. }
  61. } else {
  62. if len(args) == 0 {
  63. // help message for help command :)
  64. foundCmd = cmd
  65. }
  66. helpFunc := foundCmd.HelpFunc()
  67. helpFunc(foundCmd, args)
  68. }
  69. }