command_groups.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 templates
  14. import (
  15. "github.com/spf13/cobra"
  16. )
  17. type CommandGroup struct {
  18. Message string
  19. Commands []*cobra.Command
  20. }
  21. type CommandGroups []CommandGroup
  22. func (g CommandGroups) Add(c *cobra.Command) {
  23. for _, group := range g {
  24. c.AddCommand(group.Commands...)
  25. }
  26. }
  27. func (g CommandGroups) Has(c *cobra.Command) bool {
  28. for _, group := range g {
  29. for _, command := range group.Commands {
  30. if command == c {
  31. return true
  32. }
  33. }
  34. }
  35. return false
  36. }
  37. func AddAdditionalCommands(g CommandGroups, message string, cmds []*cobra.Command) CommandGroups {
  38. group := CommandGroup{Message: message}
  39. for _, c := range cmds {
  40. // Don't show commands that have no short description
  41. if !g.Has(c) && len(c.Short) != 0 {
  42. group.Commands = append(group.Commands, c)
  43. }
  44. }
  45. if len(group.Commands) == 0 {
  46. return g
  47. }
  48. return append(g, group)
  49. }