1/* 2Copyright 2020 The Kubernetes Authors. 3 4Licensed under the Apache License, Version 2.0 (the "License"); 5you may not use this file except in compliance with the License. 6You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10Unless required by applicable law or agreed to in writing, software 11distributed under the License is distributed on an "AS IS" BASIS, 12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13See the License for the specific language governing permissions and 14limitations under the License. 15*/ 16 17package defaulting 18 19import structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema" 20 21func isNonNullableNonDefaultableNull(x interface{}, s *structuralschema.Structural) bool { 22 return x == nil && s != nil && s.Generic.Nullable == false && s.Default.Object == nil 23} 24 25func 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. 44func 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