github.com/erda-project/erda-infra@v1.0.9/providers/component-protocol/utils/cputil/obj.go (about) 1 // Copyright (c) 2021 Terminus, Inc. 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 cputil 16 17 import ( 18 "fmt" 19 20 jsi "github.com/json-iterator/go" 21 22 "github.com/erda-project/erda-infra/providers/component-protocol/cptype" 23 ) 24 25 var json = jsi.ConfigFastest 26 27 // ObjJSONTransfer transfer from src to dst using json. 28 func ObjJSONTransfer(src interface{}, dst interface{}) error { 29 b, err := json.Marshal(src) 30 if err != nil { 31 return err 32 } 33 return json.Unmarshal(b, dst) 34 } 35 36 // MustObjJSONTransfer . 37 func MustObjJSONTransfer(src interface{}, dst interface{}) interface{} { 38 err := ObjJSONTransfer(src, dst) 39 if err != nil { 40 panic(fmt.Errorf("err: %v, src: %+v, dst: %+v", err, src, dst)) 41 } 42 return dst 43 } 44 45 // MustConvertProps . 46 func MustConvertProps(props interface{}) cptype.ComponentProps { 47 return *MustObjJSONTransfer(props, &cptype.ComponentProps{}).(*cptype.ComponentProps) 48 } 49 50 const ( 51 mapKeyMeta = "meta" 52 ) 53 54 // MustFlatMapMeta . 55 func MustFlatMapMeta(input interface{}, removeMetaAfterFlat bool) { 56 switch in := input.(type) { 57 case map[string]interface{}: 58 m := &in 59 flatMapMeta(m, removeMetaAfterFlat) 60 case *map[string]interface{}: 61 m := in 62 flatMapMeta(m, removeMetaAfterFlat) 63 case []interface{}: 64 for _, v := range in { 65 v := v 66 MustFlatMapMeta(v, removeMetaAfterFlat) 67 } 68 default: 69 return 70 } 71 } 72 73 func flatMapMeta(m *map[string]interface{}, removeMetaAfterFlat bool) { 74 for k, v := range *m { 75 v := v 76 if k != mapKeyMeta { 77 MustFlatMapMeta(v, removeMetaAfterFlat) 78 (*m)[k] = v 79 continue 80 } 81 // meta 82 metaMap, ok := v.(map[string]interface{}) 83 if !ok { 84 (*m)[k] = v 85 continue 86 } 87 // flat map 88 for k, v := range metaMap { 89 v := v 90 MustFlatMapMeta(v, removeMetaAfterFlat) 91 (*m)[k] = v 92 } 93 if removeMetaAfterFlat { 94 delete(*m, mapKeyMeta) 95 } 96 } 97 }