...

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

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

     1  /*
     2  Copyright 2020 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 structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema"
    20  
    21  func isNonNullableNonDefaultableNull(x interface{}, s *structuralschema.Structural) bool {
    22  	return x == nil && s != nil && s.Generic.Nullable == false && s.Default.Object == nil
    23  }
    24  
    25  func getSchemaForField(field string, s *structuralschema.Structural) *structuralschema.Structural {
    26  	if s == nil {
    27  		return nil
    28  	}
    29  	schema, ok := s.Properties[field]
    30  	if ok {
    31  		return &schema
    32  	}
    33  	if s.AdditionalProperties != nil {
    34  		return s.AdditionalProperties.Structural
    35  	}
    36  	return nil
    37  }
    38  
    39  // PruneNonNullableNullsWithoutDefaults removes non-nullable
    40  // non-defaultable null values from object.
    41  //
    42  // Non-nullable nulls that have a default are left alone here and will
    43  // be defaulted later.
    44  func PruneNonNullableNullsWithoutDefaults(x interface{}, s *structuralschema.Structural) {
    45  	switch x := x.(type) {
    46  	case map[string]interface{}:
    47  		for k, v := range x {
    48  			schema := getSchemaForField(k, s)
    49  			if isNonNullableNonDefaultableNull(v, schema) {
    50  				delete(x, k)
    51  			} else {
    52  				PruneNonNullableNullsWithoutDefaults(v, schema)
    53  			}
    54  		}
    55  	case []interface{}:
    56  		var schema *structuralschema.Structural
    57  		if s != nil {
    58  			schema = s.Items
    59  		}
    60  		for i := range x {
    61  			PruneNonNullableNullsWithoutDefaults(x[i], schema)
    62  		}
    63  	default:
    64  		// scalars, do nothing
    65  	}
    66  }
    67  

View as plain text