group.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2012 Jesse van den Kieboom. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package flags
  5. import (
  6. "errors"
  7. "strings"
  8. )
  9. // ErrNotPointerToStruct indicates that a provided data container is not
  10. // a pointer to a struct. Only pointers to structs are valid data containers
  11. // for options.
  12. var ErrNotPointerToStruct = errors.New("provided data is not a pointer to struct")
  13. // Group represents an option group. Option groups can be used to logically
  14. // group options together under a description. Groups are only used to provide
  15. // more structure to options both for the user (as displayed in the help message)
  16. // and for you, since groups can be nested.
  17. type Group struct {
  18. // A short description of the group. The
  19. // short description is primarily used in the builtin generated help
  20. // message
  21. ShortDescription string
  22. // A long description of the group. The long
  23. // description is primarily used to present information on commands
  24. // (Command embeds Group) in the builtin generated help and man pages.
  25. LongDescription string
  26. // All the options in the group
  27. options []*Option
  28. // All the subgroups
  29. groups []*Group
  30. data interface{}
  31. }
  32. // AddGroup adds a new group to the command with the given name and data. The
  33. // data needs to be a pointer to a struct from which the fields indicate which
  34. // options are in the group.
  35. func (g *Group) AddGroup(shortDescription string, longDescription string, data interface{}) (*Group, error) {
  36. group := newGroup(shortDescription, longDescription, data)
  37. if err := group.scan(); err != nil {
  38. return nil, err
  39. }
  40. g.groups = append(g.groups, group)
  41. return group, nil
  42. }
  43. // Groups returns the list of groups embedded in this group.
  44. func (g *Group) Groups() []*Group {
  45. return g.groups
  46. }
  47. // Options returns the list of options in this group.
  48. func (g *Group) Options() []*Option {
  49. return g.options
  50. }
  51. // Find locates the subgroup with the given short description and returns it.
  52. // If no such group can be found Find will return nil. Note that the description
  53. // is matched case insensitively.
  54. func (g *Group) Find(shortDescription string) *Group {
  55. lshortDescription := strings.ToLower(shortDescription)
  56. var ret *Group
  57. g.eachGroup(func(gg *Group) {
  58. if gg != g && strings.ToLower(gg.ShortDescription) == lshortDescription {
  59. ret = gg
  60. }
  61. })
  62. return ret
  63. }