/
size_between.go
62 lines (51 loc) · 1.7 KB
/
size_between.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
60
61
62
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package setvalidator
import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-framework-validators/helpers/validatordiag"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
)
var _ validator.Set = sizeBetweenValidator{}
// sizeBetweenValidator validates that set contains at least min elements
// and at most max elements.
type sizeBetweenValidator struct {
min int
max int
}
// Description describes the validation in plain text formatting.
func (v sizeBetweenValidator) Description(_ context.Context) string {
return fmt.Sprintf("set must contain at least %d elements and at most %d elements", v.min, v.max)
}
// MarkdownDescription describes the validation in Markdown formatting.
func (v sizeBetweenValidator) MarkdownDescription(ctx context.Context) string {
return v.Description(ctx)
}
// ValidateSet performs the validation.
func (v sizeBetweenValidator) ValidateSet(ctx context.Context, req validator.SetRequest, resp *validator.SetResponse) {
if req.ConfigValue.IsNull() || req.ConfigValue.IsUnknown() {
return
}
elems := req.ConfigValue.Elements()
if len(elems) < v.min || len(elems) > v.max {
resp.Diagnostics.Append(validatordiag.InvalidAttributeValueDiagnostic(
req.Path,
v.Description(ctx),
fmt.Sprintf("%d", len(elems)),
))
}
}
// SizeBetween returns an AttributeValidator which ensures that any configured
// attribute value:
//
// - Is a Set.
// - Contains at least min elements and at most max elements.
//
// Null (unconfigured) and unknown (known after apply) values are skipped.
func SizeBetween(min, max int) validator.Set {
return sizeBetweenValidator{
min: min,
max: max,
}
}