-
Notifications
You must be signed in to change notification settings - Fork 230
/
meta.go
59 lines (54 loc) · 2.07 KB
/
meta.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package validation
import (
"fmt"
"reflect"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
// NoZeroValues is a SchemaValidateFunc which tests if the provided value is
// not a zero value. It's useful in situations where you want to catch
// explicit zero values on things like required fields during validation.
func NoZeroValues(i interface{}, k string) (s []string, es []error) {
if reflect.ValueOf(i).Interface() == reflect.Zero(reflect.TypeOf(i)).Interface() {
switch reflect.TypeOf(i).Kind() {
case reflect.String:
es = append(es, fmt.Errorf("%s must not be empty, got %v", k, i))
case reflect.Int, reflect.Float64:
es = append(es, fmt.Errorf("%s must not be zero, got %v", k, i))
default:
// this validator should only ever be applied to TypeString, TypeInt and TypeFloat
panic(fmt.Errorf("can't use NoZeroValues with %T attribute %s", i, k))
}
}
return
}
// All returns a SchemaValidateFunc which tests if the provided value
// passes all provided SchemaValidateFunc
func All(validators ...schema.SchemaValidateFunc) schema.SchemaValidateFunc {
return func(i interface{}, k string) ([]string, []error) {
var allErrors []error
var allWarnings []string
for _, validator := range validators {
validatorWarnings, validatorErrors := validator(i, k)
allWarnings = append(allWarnings, validatorWarnings...)
allErrors = append(allErrors, validatorErrors...)
}
return allWarnings, allErrors
}
}
// Any returns a SchemaValidateFunc which tests if the provided value
// passes any of the provided SchemaValidateFunc
func Any(validators ...schema.SchemaValidateFunc) schema.SchemaValidateFunc {
return func(i interface{}, k string) ([]string, []error) {
var allErrors []error
var allWarnings []string
for _, validator := range validators {
validatorWarnings, validatorErrors := validator(i, k)
if len(validatorWarnings) == 0 && len(validatorErrors) == 0 {
return []string{}, []error{}
}
allWarnings = append(allWarnings, validatorWarnings...)
allErrors = append(allErrors, validatorErrors...)
}
return allWarnings, allErrors
}
}