github.com/alex123012/deckhouse-controller-tools@v0.0.0-20230510090815-d594daf1af8c/pkg/crd/markers/register.go (about)

     1  /*
     2  Copyright 2019 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package markers
    18  
    19  import (
    20  	"reflect"
    21  
    22  	"sigs.k8s.io/controller-tools/pkg/markers"
    23  )
    24  
    25  type definitionWithHelp struct {
    26  	*markers.Definition
    27  	Help *markers.DefinitionHelp
    28  }
    29  
    30  func (d *definitionWithHelp) WithHelp(help *markers.DefinitionHelp) *definitionWithHelp {
    31  	d.Help = help
    32  	return d
    33  }
    34  
    35  func (d *definitionWithHelp) Register(reg *markers.Registry) error {
    36  	if err := reg.Register(d.Definition); err != nil {
    37  		return err
    38  	}
    39  	if d.Help != nil {
    40  		reg.AddHelp(d.Definition, d.Help)
    41  	}
    42  	return nil
    43  }
    44  
    45  func must(def *markers.Definition, err error) *definitionWithHelp {
    46  	return &definitionWithHelp{
    47  		Definition: markers.Must(def, err),
    48  	}
    49  }
    50  
    51  // AllDefinitions contains all marker definitions for this package.
    52  var AllDefinitions []*definitionWithHelp
    53  
    54  type hasHelp interface {
    55  	Help() *markers.DefinitionHelp
    56  }
    57  
    58  // mustMakeAllWithPrefix converts each object into a marker definition using
    59  // the object's type's with the prefix to form the marker name.
    60  func mustMakeAllWithPrefix(prefix string, target markers.TargetType, objs ...interface{}) []*definitionWithHelp {
    61  	defs := make([]*definitionWithHelp, len(objs))
    62  	for i, obj := range objs {
    63  		name := prefix + ":" + reflect.TypeOf(obj).Name()
    64  		def, err := markers.MakeDefinition(name, target, obj)
    65  		if err != nil {
    66  			panic(err)
    67  		}
    68  		defs[i] = &definitionWithHelp{Definition: def, Help: obj.(hasHelp).Help()}
    69  	}
    70  
    71  	return defs
    72  }
    73  
    74  // Register registers all definitions for CRD generation to the given registry.
    75  func Register(reg *markers.Registry) error {
    76  	for _, def := range AllDefinitions {
    77  		if err := def.Register(reg); err != nil {
    78  			return err
    79  		}
    80  	}
    81  
    82  	return nil
    83  }