k8s.io/kube-openapi@v0.0.0-20240228011516-70dd3763d340/pkg/builder3/util/util.go (about)

     1  /*
     2  Copyright 2022 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 util
    18  
    19  import (
    20  	"reflect"
    21  
    22  	"k8s.io/kube-openapi/pkg/schemamutation"
    23  	"k8s.io/kube-openapi/pkg/validation/spec"
    24  )
    25  
    26  // wrapRefs wraps OpenAPI V3 Schema refs that contain sibling elements.
    27  // AllOf is used to wrap the Ref to prevent references from having sibling elements
    28  // Please see https://github.com/kubernetes/kubernetes/issues/106387#issuecomment-967640388
    29  func WrapRefs(schema *spec.Schema) *spec.Schema {
    30  	walker := schemamutation.Walker{
    31  		SchemaCallback: func(schema *spec.Schema) *spec.Schema {
    32  			orig := schema
    33  			clone := func() {
    34  				if orig == schema {
    35  					schema = new(spec.Schema)
    36  					*schema = *orig
    37  				}
    38  			}
    39  			if schema.Ref.String() != "" && !reflect.DeepEqual(*schema, spec.Schema{SchemaProps: spec.SchemaProps{Ref: schema.Ref}}) {
    40  				clone()
    41  				refSchema := new(spec.Schema)
    42  				refSchema.Ref = schema.Ref
    43  				schema.Ref = spec.Ref{}
    44  				schema.AllOf = []spec.Schema{*refSchema}
    45  			}
    46  			return schema
    47  		},
    48  		RefCallback: schemamutation.RefCallbackNoop,
    49  	}
    50  	return walker.WalkSchema(schema)
    51  }