Debian Codegraph @

validate/validate.go

raw symbols SCIP
1 // Copyright 2019 Red Hat, Inc
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 validate
16
17 import (
18 "reflect"
19 "strings"
20
21 "github.com/coreos/vcontext/path"
22 "github.com/coreos/vcontext/report"
23 )
24
25 type CustomValidator func(v reflect.Value, c path.ContextPath) report.Report
26
27 // validator is the interface the DefaultValidator function uses when validating types.
28 // Most users should implement this interface on types they want to validate.
29 type validator interface {
30 Validate(path.ContextPath) report.Report
31 }
32
33 // DefaultValidator checks if the type implements the validator interface and calls the
34 // validate function if it does, returning the report.
35 func DefaultValidator(v reflect.Value, c path.ContextPath) report.Report {
36 // first check if this object has Validate(context) defined, but only on value
37 // recievers. Both pointer and value receivers satisfy a value receiver interface
38 // so ensure we're not a pointer too.
39 if obj, ok := v.Interface().(validator); ok && v.Kind() != reflect.Ptr {
40 return obj.Validate(c)
41 }
42 return report.Report{}
43 }
44
45 // ValidateCustom validates thing using the custom validation function supplied. Most users will not need this
46 // and should use Validate() instead.
47 func ValidateCustom(thing interface{}, tag string, customValidator CustomValidator) report.Report {
48 if thing == nil {
49 return report.Report{}
50 }
51 v := reflect.ValueOf(thing)
52 ctx := path.ContextPath{Tag: tag}
53 return validate(ctx, v, customValidator)
54 }
55
56 // Validate walks the structs, slices, and pointers in thing and calls any Validate(path.ContextPath) report.Report
57 // functions defined on the types, aggregating the results.
58 func Validate(thing interface{}, tag string) report.Report {
59 return ValidateCustom(thing, tag, DefaultValidator)
60 }
61
62 func validate(context path.ContextPath, v reflect.Value, validateFunc CustomValidator) (r report.Report) {
63 if !v.IsValid() {
64 return
65 }
66 if v.Kind() == reflect.Interface {
67 if v.IsNil() {
68 return
69 } else {
70 v = makeConcrete(v)
71 }
72 }
73
74 r.Merge(validateFunc(v, context))
75
76 switch v.Kind() {
77 case reflect.Struct:
78 r.Merge(validateStruct(context, v, validateFunc))
79 case reflect.Slice:
80 r.Merge(validateSlice(context, v, validateFunc))
81 case reflect.Ptr:
82 if !v.IsNil() {
83 r.Merge(validate(context, v.Elem(), validateFunc))
84 }
85 }
86
87 return
88 }
89
90 // StructField is an extension of go's reflect.StructField that also includes the value.
91 type StructField struct {
92 reflect.StructField
93 Value reflect.Value
94 }
95
96 // makeConcrete takes a value and if it is a value of an interface returns the
97 // value of the actual underlying type implementing that interface. If the value
98 // is already concrete, it returns the same value.
99 func makeConcrete(v reflect.Value) reflect.Value {
100 return reflect.ValueOf(v.Interface())
101 }
102
103 // GetFields takes a value of a struct and flattens all embedded structs in it.
104 // If any fields are interfaces, it "dereferences" the interface to its underlying type.
105 func GetFields(v reflect.Value) []StructField {
106 ret := []StructField{}
107 if v.Kind() != reflect.Struct {
108 return ret
109 }
110
111 for i := 0; i < v.NumField(); i++ {
112 field := v.Type().Field(i)
113 if !field.Anonymous {
114 ret = append(ret, StructField{
115 StructField: field,
116 Value: v.Field(i),
117 })
118 } else {
119 concrete := makeConcrete(v.Field(i))
120 ret = append(ret, GetFields(concrete)...)
121 }
122 }
123 return ret
124 }
125
126 func FieldName(s StructField, tag string) string {
127 if tag == "" {
128 return s.Name
129 }
130 tag = s.Tag.Get(tag)
131 return strings.Split(tag, ",")[0]
132 }
133
134 func validateStruct(context path.ContextPath, v reflect.Value, f CustomValidator) (r report.Report) {
135 fields := GetFields(v)
136 for _, field := range fields {
137 fieldContext := context.Append(FieldName(field, context.Tag))
138 r.Merge(validate(fieldContext, field.Value, f))
139 }
140 return
141 }
142
143 func validateSlice(context path.ContextPath, v reflect.Value, f CustomValidator) (r report.Report) {
144 for i := 0; i < v.Len(); i++ {
145 childContext := context.Append(i)
146 r.Merge(validate(childContext, v.Index(i), f))
147 }
148 return
149 }