register.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. Copyright 2019 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 markers
  14. import (
  15. "reflect"
  16. "sigs.k8s.io/controller-tools/pkg/markers"
  17. )
  18. type definitionWithHelp struct {
  19. *markers.Definition
  20. Help *markers.DefinitionHelp
  21. }
  22. func (d *definitionWithHelp) WithHelp(help *markers.DefinitionHelp) *definitionWithHelp {
  23. d.Help = help
  24. return d
  25. }
  26. func (d *definitionWithHelp) Register(reg *markers.Registry) error {
  27. if err := reg.Register(d.Definition); err != nil {
  28. return err
  29. }
  30. if d.Help != nil {
  31. reg.AddHelp(d.Definition, d.Help)
  32. }
  33. return nil
  34. }
  35. func must(def *markers.Definition, err error) *definitionWithHelp {
  36. return &definitionWithHelp{
  37. Definition: markers.Must(def, err),
  38. }
  39. }
  40. // AllDefinitions contains all marker definitions for this package.
  41. var AllDefinitions []*definitionWithHelp
  42. type hasHelp interface {
  43. Help() *markers.DefinitionHelp
  44. }
  45. // mustMakeAllWithPrefix converts each object into a marker definition using
  46. // the object's type's with the prefix to form the marker name.
  47. func mustMakeAllWithPrefix(prefix string, target markers.TargetType, objs ...interface{}) []*definitionWithHelp {
  48. defs := make([]*definitionWithHelp, len(objs))
  49. for i, obj := range objs {
  50. name := prefix + ":" + reflect.TypeOf(obj).Name()
  51. def, err := markers.MakeDefinition(name, target, obj)
  52. if err != nil {
  53. panic(err)
  54. }
  55. defs[i] = &definitionWithHelp{Definition: def, Help: obj.(hasHelp).Help()}
  56. }
  57. return defs
  58. }
  59. // Register registers all definitions for CRD generation to the given registry.
  60. func Register(reg *markers.Registry) error {
  61. for _, def := range AllDefinitions {
  62. if err := def.Register(reg); err != nil {
  63. return err
  64. }
  65. }
  66. return nil
  67. }