yunion.io/x/cloudmux@v0.3.10-0-alpha.1/pkg/cloudprovider/generic/generic.go (about) 1 // Copyright 2019 Yunion 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 generic 16 17 import ( 18 "yunion.io/x/pkg/errors" 19 20 "yunion.io/x/cloudmux/pkg/cloudprovider" 21 ) 22 23 func GetResourceByFuncs[T cloudprovider.ICloudResource](objs []T, idFs []func(T) string, id string) (T, error) { 24 for i := range objs { 25 obj := objs[i] 26 for _, f := range idFs { 27 if f(obj) == id { 28 return obj, nil 29 } 30 } 31 } 32 return *new(T), cloudprovider.ErrNotFound 33 } 34 35 func GetResourceId[T cloudprovider.ICloudResource](obj T) string { 36 return obj.GetId() 37 } 38 39 func GetResourceName[T cloudprovider.ICloudResource](obj T) string { 40 return obj.GetName() 41 } 42 43 func GetResourceGlobalId[T cloudprovider.ICloudResource](obj T) string { 44 return obj.GetGlobalId() 45 } 46 47 func GetResourceById[T cloudprovider.ICloudResource](objs []T, id string) (T, error) { 48 return GetResourceByFuncs(objs, [](func(T) string){GetResourceId[T]}, id) 49 } 50 51 func GetResourceByName[T cloudprovider.ICloudResource](objs []T, id string) (T, error) { 52 return GetResourceByFuncs(objs, [](func(T) string){GetResourceName[T]}, id) 53 } 54 55 func GetResourceByGlobalId[T cloudprovider.ICloudResource](objs []T, id string) (T, error) { 56 return GetResourceByFuncs(objs, [](func(T) string){GetResourceGlobalId[T]}, id) 57 } 58 59 func GetResourceByIdOrName[T cloudprovider.ICloudResource](objs []T, idOrName string) (T, error) { 60 return GetResourceByFuncs(objs, [](func(T) string){ 61 GetResourceId[T], 62 GetResourceName[T], 63 GetResourceGlobalId[T], 64 }, idOrName) 65 } 66 67 func Iter[T cloudprovider.ICloudResource](objs []T, f func(T) error, continueOnErr bool) error { 68 var errs []error 69 for _, obj := range objs { 70 if err := f(obj); err != nil { 71 if !continueOnErr { 72 return errors.Wrapf(err, "resource %q", obj.GetGlobalId()) 73 } else { 74 errs = append(errs, err) 75 } 76 } 77 } 78 return errors.NewAggregate(errs) 79 }