...

Source file src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm.go

Documentation: k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting

     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 defaulting
    18  
    19  import (
    20  	structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema"
    21  	"k8s.io/apimachinery/pkg/runtime"
    22  )
    23  
    24  // isNonNullalbeNull returns true if the item is nil AND it's nullable
    25  func isNonNullableNull(x interface{}, s *structuralschema.Structural) bool {
    26  	return x == nil && s != nil && s.Generic.Nullable == false
    27  }
    28  
    29  // Default does defaulting of x depending on default values in s.
    30  // Default values from s are deep-copied.
    31  //
    32  // PruneNonNullableNullsWithoutDefaults has left the non-nullable nulls
    33  // that have a default here.
    34  func Default(x interface{}, s *structuralschema.Structural) {
    35  	if s == nil {
    36  		return
    37  	}
    38  
    39  	switch x := x.(type) {
    40  	case map[string]interface{}:
    41  		for k, prop := range s.Properties {
    42  			if prop.Default.Object == nil {
    43  				continue
    44  			}
    45  			if _, found := x[k]; !found || isNonNullableNull(x[k], &prop) {
    46  				x[k] = runtime.DeepCopyJSONValue(prop.Default.Object)
    47  			}
    48  		}
    49  		for k := range x {
    50  			if prop, found := s.Properties[k]; found {
    51  				Default(x[k], &prop)
    52  			} else if s.AdditionalProperties != nil {
    53  				if isNonNullableNull(x[k], s.AdditionalProperties.Structural) {
    54  					x[k] = runtime.DeepCopyJSONValue(s.AdditionalProperties.Structural.Default.Object)
    55  				}
    56  				Default(x[k], s.AdditionalProperties.Structural)
    57  			}
    58  		}
    59  	case []interface{}:
    60  		for i := range x {
    61  			if isNonNullableNull(x[i], s.Items) {
    62  				x[i] = runtime.DeepCopyJSONValue(s.Items.Default.Object)
    63  			}
    64  			Default(x[i], s.Items)
    65  		}
    66  	default:
    67  		// scalars, do nothing
    68  	}
    69  }
    70  

View as plain text