...

Source file src/github.com/GoogleCloudPlatform/k8s-config-connector/pkg/dcl/fields.go

Documentation: github.com/GoogleCloudPlatform/k8s-config-connector/pkg/dcl

     1  // Copyright 2022 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package dcl
    16  
    17  import (
    18  	"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/util/pathslice"
    19  	"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/util/slice"
    20  )
    21  
    22  func IsContainerField(path []string) bool {
    23  	if len(path) > 1 {
    24  		return false
    25  	}
    26  	field := pathslice.Base(path)
    27  	return field == "organization" || field == "project" || field == "folder"
    28  }
    29  
    30  // TrimNilFields removes all nil fields in the input object, including
    31  // non-top-level nil fields (e.g. those found in nested objects and nested list
    32  // of objects).
    33  func TrimNilFields(m map[string]interface{}) {
    34  	for k, v := range m {
    35  		if IsNil(v) {
    36  			delete(m, k)
    37  			continue
    38  		}
    39  
    40  		switch v := v.(type) {
    41  		// If value is an object, trim nil fields in object.
    42  		case map[string]interface{}:
    43  			TrimNilFields(v)
    44  		// If value is a list of objects, trim nil fields in each object.
    45  		case []interface{}:
    46  			if !slice.IsListOfStringInterfaceMaps(v) {
    47  				// List is a list of primitives rather than of objects.
    48  				continue
    49  			}
    50  			for _, e := range v {
    51  				TrimNilFields(e.(map[string]interface{}))
    52  			}
    53  		}
    54  	}
    55  }
    56  
    57  // An interface value strictly equals to nil only if the V (actual value) and T (type) are both unset;
    58  // we want to treat interface values like (T=[]interface{}, V=nil) as nil too since the actual value is nil.
    59  func IsNil(v interface{}) bool {
    60  	if v == nil {
    61  		return true
    62  	}
    63  	switch v := v.(type) {
    64  	case []interface{}:
    65  		return v == nil
    66  	case map[string]interface{}:
    67  		return v == nil
    68  	}
    69  	return false
    70  }
    71  
    72  func AddToMap(key string, val interface{}, obj map[string]interface{}) {
    73  	if !IsNil(val) {
    74  		obj[key] = val
    75  	}
    76  }
    77  

View as plain text