github.com/hashicorp/terraform-plugin-sdk@v1.17.2/helper/validation/meta.go (about)

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