-
Notifications
You must be signed in to change notification settings - Fork 233
/
Copy pathvalidate.go
43 lines (36 loc) · 1.71 KB
/
validate.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package customdiff
import (
"context"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
// ValueChangeValidationFunc is a function type that validates the difference
// (or lack thereof) between two values, returning an error if the change
// is invalid.
type ValueChangeValidationFunc func(ctx context.Context, oldValue, newValue, meta interface{}) error
// ValueValidationFunc is a function type that validates a particular value,
// returning an error if the value is invalid.
type ValueValidationFunc func(ctx context.Context, value, meta interface{}) error
// ValidateChange returns a CustomizeDiffFunc that applies the given validation
// function to the change for the given key, returning any error produced.
func ValidateChange(key string, f ValueChangeValidationFunc) schema.CustomizeDiffFunc {
return func(ctx context.Context, d *schema.ResourceDiff, meta interface{}) error {
oldValue, newValue := d.GetChange(key)
return f(ctx, oldValue, newValue, meta)
}
}
// ValidateValue returns a CustomizeDiffFunc that applies the given validation
// function to value of the given key, returning any error produced.
//
// This should generally not be used since it is functionally equivalent to
// a validation function applied directly to the schema attribute in question,
// but is provided for situations where composing multiple CustomizeDiffFuncs
// together makes intent clearer than spreading that validation across the
// schema.
func ValidateValue(key string, f ValueValidationFunc) schema.CustomizeDiffFunc {
return func(ctx context.Context, d *schema.ResourceDiff, meta interface{}) error {
val := d.Get(key)
return f(ctx, val, meta)
}
}