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 _, entry := range strings.Split(tag, ",") { 27 if entry == value { 28 return true 29 } 30 } 31 32 return false 33} 34 35// PropertyIndexesWithTag returns the indexes of all properties (in the form used by reflect.Value.FieldByIndex) that 36// are tagged with the given key and value, including ones found in embedded structs or pointers to structs. 37func PropertyIndexesWithTag(ps interface{}, key, value string) [][]int { 38 t := reflect.TypeOf(ps) 39 if !isStructPtr(t) { 40 panic(fmt.Errorf("type %s is not a pointer to a struct", t)) 41 } 42 t = t.Elem() 43 44 return propertyIndexesWithTag(t, key, value) 45} 46func propertyIndexesWithTag(t reflect.Type, key, value string) [][]int { 47 var indexes [][]int 48 49 for i := 0; i < t.NumField(); i++ { 50 field := t.Field(i) 51 ft := field.Type 52 if isStruct(ft) || isStructPtr(ft) { 53 if ft.Kind() == reflect.Ptr { 54 ft = ft.Elem() 55 } 56 subIndexes := propertyIndexesWithTag(ft, key, value) 57 for _, sub := range subIndexes { 58 sub = append([]int{i}, sub...) 59 indexes = append(indexes, sub) 60 } 61 } else if HasTag(field, key, value) { 62 indexes = append(indexes, field.Index) 63 } 64 } 65 66 return indexes 67} 68