help.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 cmd
  14. import (
  15. "io"
  16. "strings"
  17. "github.com/spf13/cobra"
  18. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  19. )
  20. const help_long = `Help provides help for any command in the application.
  21. Simply type kubectl help [path to command] for full details.`
  22. func NewCmdHelp(f *cmdutil.Factory, out io.Writer) *cobra.Command {
  23. cmd := &cobra.Command{
  24. Use: "help [command] | STRING_TO_SEARCH",
  25. Short: "Help about any command",
  26. Long: help_long,
  27. Run: RunHelp,
  28. }
  29. return cmd
  30. }
  31. func RunHelp(cmd *cobra.Command, args []string) {
  32. foundCmd, _, err := cmd.Root().Find(args)
  33. // NOTE(andreykurilin): actually, I did not find any cases when foundCmd can be nil,
  34. // but let's make this check since it is included in original code of initHelpCmd
  35. // from github.com/spf13/cobra
  36. if foundCmd == nil {
  37. cmd.Printf("Unknown help topic %#q.\n", args)
  38. cmd.Root().Usage()
  39. } else if err != nil {
  40. // print error message at first, since it can contain suggestions
  41. cmd.Println(err)
  42. argsString := strings.Join(args, " ")
  43. var matchedMsgIsPrinted bool = false
  44. for _, foundCmd := range foundCmd.Commands() {
  45. if strings.Contains(foundCmd.Short, argsString) {
  46. if !matchedMsgIsPrinted {
  47. cmd.Printf("Matchers of string '%s' in short descriptions of commands: \n", argsString)
  48. matchedMsgIsPrinted = true
  49. }
  50. cmd.Printf(" %-14s %s\n", foundCmd.Name(), foundCmd.Short)
  51. }
  52. }
  53. if !matchedMsgIsPrinted {
  54. // if nothing is found, just print usage
  55. cmd.Root().Usage()
  56. }
  57. } else {
  58. if len(args) == 0 {
  59. // help message for help command :)
  60. foundCmd = cmd
  61. }
  62. helpFunc := foundCmd.HelpFunc()
  63. helpFunc(foundCmd, args)
  64. }
  65. }