github.com/galaxyobe/gen@v0.0.0-20220910125335-392fa8f0990f/pkg/util/tag.go (about) 1 /* 2 Copyright 2022 Galaxyobe. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package util 18 19 import ( 20 "reflect" 21 "strings" 22 23 "k8s.io/gengo/types" 24 ) 25 26 const ( 27 Package = "package" 28 True = "true" 29 False = "false" 30 ) 31 32 func CheckTag(tag string, comments []string, require ...string) bool { 33 values := types.ExtractCommentTags("+", comments)[tag] 34 if len(require) == 0 { 35 return len(values) == 1 && values[0] == "" 36 } 37 if values == nil { 38 return false 39 } 40 return reflect.DeepEqual(values, require) 41 } 42 43 func GetTagBoolStatus(tag string, comments []string) (set bool, enabled bool) { 44 values := types.ExtractCommentTags("+", comments)[tag] 45 switch len(values) { 46 case 0: 47 enabled = true 48 return 49 default: 50 set = true 51 enabled = strings.Split(values[0], ",")[0] == True 52 return 53 } 54 } 55 56 func GetTagValues(tag string, comments []string) []string { 57 values := types.ExtractCommentTags("+", comments)[tag] 58 if len(values) == 0 { 59 return nil 60 } 61 var result []string 62 for _, item := range values { 63 result = append(result, strings.Split(item, ",")...) 64 } 65 return result 66 } 67 68 func GetTagValuesStatus(tag string, comments []string) (bool, []string) { 69 values := types.ExtractCommentTags("+", comments)[tag] 70 if len(values) == 0 { 71 return false, nil 72 } 73 var result []string 74 for _, item := range values { 75 result = append(result, strings.Split(item, ",")...) 76 } 77 return true, result 78 } 79 80 func GetTagValueStatus(tag string, comments []string) (bool, string) { 81 set, values := GetTagValuesStatus(tag, comments) 82 if len(values) > 0 { 83 return set, values[0] 84 } 85 return false, "" 86 }