1// Copyright 2019 Google Inc. All rights reserved. 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 15package proptools 16 17import ( 18 "fmt" 19 "reflect" 20 "strings" 21) 22 23// HasTag returns true if a StructField has a tag in the form `name:"foo,value"`. 24func HasTag(field reflect.StructField, name, value string) bool { 25 tag := field.Tag.Get(name) 26 for len(tag) > 0 { 27 idx := strings.Index(tag, ",") 28 29 if idx < 0 { 30 return tag == value 31 } 32 if tag[:idx] == value { 33 return true 34 } 35 36 tag = tag[idx+1:] 37 } 38 39 return false 40} 41 42// PropertyIndexesWithTag returns the indexes of all properties (in the form used by reflect.Value.FieldByIndex) that 43// are tagged with the given key and value, including ones found in embedded structs or pointers to structs. 44func PropertyIndexesWithTag(ps interface{}, key, value string) [][]int { 45 t := reflect.TypeOf(ps) 46 if !isStructPtr(t) { 47 panic(fmt.Errorf("type %s is not a pointer to a struct", t)) 48 } 49 t = t.Elem() 50 51 return propertyIndexesWithTag(t, key, value) 52} 53func propertyIndexesWithTag(t reflect.Type, key, value string) [][]int { 54 var indexes [][]int 55 56 for i := 0; i < t.NumField(); i++ { 57 field := t.Field(i) 58 ft := field.Type 59 if isStruct(ft) || isStructPtr(ft) || isSliceOfStruct(ft) { 60 if ft.Kind() == reflect.Ptr || ft.Kind() == reflect.Slice { 61 ft = ft.Elem() 62 } 63 subIndexes := propertyIndexesWithTag(ft, key, value) 64 for _, sub := range subIndexes { 65 sub = append([]int{i}, sub...) 66 indexes = append(indexes, sub) 67 } 68 } else if HasTag(field, key, value) { 69 indexes = append(indexes, field.Index) 70 } 71 } 72 73 return indexes 74} 75