github.com/cs3org/reva/v2@v2.27.7/pkg/storage/utils/indexer/reflect.go (about) 1 // Copyright 2018-2022 CERN 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 // In applying this license, CERN does not waive the privileges and immunities 16 // granted to it by virtue of its status as an Intergovernmental Organization 17 // or submit itself to any jurisdiction. 18 19 package indexer 20 21 import ( 22 "errors" 23 "fmt" 24 "path" 25 "reflect" 26 "strconv" 27 "strings" 28 29 "github.com/cs3org/reva/v2/pkg/storage/utils/indexer/option" 30 ) 31 32 func getType(v interface{}) (reflect.Value, error) { 33 rv := reflect.ValueOf(v) 34 for rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Interface { 35 rv = rv.Elem() 36 } 37 if !rv.IsValid() { 38 return reflect.Value{}, errors.New("failed to read value via reflection") 39 } 40 41 return rv, nil 42 } 43 44 func getTypeFQN(t interface{}) string { 45 typ, _ := getType(t) 46 typeName := path.Join(typ.Type().PkgPath(), typ.Type().Name()) 47 typeName = strings.ReplaceAll(typeName, "/", ".") 48 return typeName 49 } 50 51 func valueOf(v interface{}, indexBy option.IndexBy) (string, error) { 52 switch idxBy := indexBy.(type) { 53 case option.IndexByField: 54 return valueOfField(v, string(idxBy)) 55 case option.IndexByFunc: 56 return idxBy.Func(v) 57 default: 58 return "", fmt.Errorf("unknown indexBy type") 59 } 60 } 61 62 func valueOfField(v interface{}, field string) (string, error) { 63 parts := strings.Split(field, ".") 64 for i, part := range parts { 65 r := reflect.ValueOf(v) 66 if r.Kind() == reflect.Ptr { 67 r = r.Elem() 68 } 69 f := reflect.Indirect(r).FieldByName(part) 70 if f.Kind() == reflect.Ptr { 71 f = f.Elem() 72 } 73 74 switch { 75 case f.Kind() == reflect.Struct && i != len(parts)-1: 76 v = f.Interface() 77 case f.Kind() == reflect.String: 78 return f.String(), nil 79 case f.IsZero(): 80 return "", nil 81 default: 82 return strconv.Itoa(int(f.Int())), nil 83 } 84 } 85 return "", nil 86 }