...

Source file src/k8s.io/cli-runtime/pkg/resource/metadata_decoder.go

Documentation: k8s.io/cli-runtime/pkg/resource

     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 resource
    18  
    19  import (
    20  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    21  	"k8s.io/apimachinery/pkg/runtime"
    22  	"k8s.io/apimachinery/pkg/runtime/schema"
    23  	utiljson "k8s.io/apimachinery/pkg/util/json"
    24  )
    25  
    26  // metadataValidatingDecoder wraps a decoder and additionally ensures metadata schema fields decode before returning an unstructured object
    27  type metadataValidatingDecoder struct {
    28  	decoder runtime.Decoder
    29  }
    30  
    31  func (m *metadataValidatingDecoder) Decode(data []byte, defaults *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
    32  	obj, gvk, err := m.decoder.Decode(data, defaults, into)
    33  
    34  	// if we already errored, return
    35  	if err != nil {
    36  		return obj, gvk, err
    37  	}
    38  
    39  	// if we're not unstructured, return
    40  	if _, isUnstructured := obj.(runtime.Unstructured); !isUnstructured {
    41  		return obj, gvk, err
    42  	}
    43  
    44  	// make sure the data can decode into ObjectMeta before we return,
    45  	// so we don't silently truncate schema errors in metadata later with accesser get/set calls
    46  	v := &metadataOnlyObject{}
    47  	if typedErr := utiljson.Unmarshal(data, v); typedErr != nil {
    48  		return obj, gvk, typedErr
    49  	}
    50  	return obj, gvk, err
    51  }
    52  
    53  type metadataOnlyObject struct {
    54  	metav1.TypeMeta   `json:",inline"`
    55  	metav1.ObjectMeta `json:"metadata,omitempty"`
    56  }
    57  

View as plain text