github.com/spotmaxtech/k8s-apimachinery-v0260@v0.0.1/pkg/runtime/codec_check.go (about) 1 /* 2 Copyright 2016 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 runtime 18 19 import ( 20 "fmt" 21 "reflect" 22 23 "github.com/spotmaxtech/k8s-apimachinery-v0260/pkg/runtime/schema" 24 "github.com/spotmaxtech/k8s-apimachinery-v0260/pkg/util/json" 25 ) 26 27 // CheckCodec makes sure that the codec can encode objects like internalType, 28 // decode all of the external types listed, and also decode them into the given 29 // object. (Will modify internalObject.) (Assumes JSON serialization.) 30 // TODO: verify that the correct external version is chosen on encode... 31 func CheckCodec(c Codec, internalType Object, externalTypes ...schema.GroupVersionKind) error { 32 if _, err := Encode(c, internalType); err != nil { 33 return fmt.Errorf("internal type not encodable: %v", err) 34 } 35 for _, et := range externalTypes { 36 typeMeta := TypeMeta{ 37 Kind: et.Kind, 38 APIVersion: et.GroupVersion().String(), 39 } 40 exBytes, err := json.Marshal(&typeMeta) 41 if err != nil { 42 return err 43 } 44 obj, err := Decode(c, exBytes) 45 if err != nil { 46 return fmt.Errorf("external type %s not interpretable: %v", et, err) 47 } 48 if reflect.TypeOf(obj) != reflect.TypeOf(internalType) { 49 return fmt.Errorf("decode of external type %s produced: %#v", et, obj) 50 } 51 if err = DecodeInto(c, exBytes, internalType); err != nil { 52 return fmt.Errorf("external type %s not convertible to internal type: %v", et, err) 53 } 54 } 55 return nil 56 }