|
| 1 | +package validate |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + |
| 7 | + "github.com/hashicorp/terraform-plugin-framework-validators/validatordiag" |
| 8 | + "github.com/hashicorp/terraform-plugin-framework/tfsdk" |
| 9 | + "github.com/hashicorp/terraform-plugin-framework/types" |
| 10 | +) |
| 11 | + |
| 12 | +var _ tfsdk.AttributeValidator = atMostValidator{} |
| 13 | + |
| 14 | +// atMostValidator validates that an integer Attribute's value is at most a certain value. |
| 15 | +type atMostValidator struct { |
| 16 | + max int64 |
| 17 | +} |
| 18 | + |
| 19 | +// Description describes the validation in plain text formatting. |
| 20 | +func (validator atMostValidator) Description(_ context.Context) string { |
| 21 | + return fmt.Sprintf("value must be at most %d", validator.max) |
| 22 | +} |
| 23 | + |
| 24 | +// MarkdownDescription describes the validation in Markdown formatting. |
| 25 | +func (validator atMostValidator) MarkdownDescription(ctx context.Context) string { |
| 26 | + return validator.Description(ctx) |
| 27 | +} |
| 28 | + |
| 29 | +// Validate performs the validation. |
| 30 | +func (validator atMostValidator) Validate(ctx context.Context, request tfsdk.ValidateAttributeRequest, response *tfsdk.ValidateAttributeResponse) { |
| 31 | + i, ok := validateInt(ctx, request, response) |
| 32 | + |
| 33 | + if !ok { |
| 34 | + return |
| 35 | + } |
| 36 | + |
| 37 | + if i > validator.max { |
| 38 | + response.Diagnostics.Append(validatordiag.AttributeValueDiagnostic( |
| 39 | + request.AttributePath, |
| 40 | + validator.Description(ctx), |
| 41 | + fmt.Sprintf("%d", i), |
| 42 | + )) |
| 43 | + |
| 44 | + return |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +// AtMost returns an AttributeValidator which ensures that any configured |
| 49 | +// attribute value: |
| 50 | +// |
| 51 | +// - Is a number, which can be represented by a 64-bit integer. |
| 52 | +// - Is exclusively less than the given maximum. |
| 53 | +// |
| 54 | +// Null (unconfigured) and unknown (known after apply) values are skipped. |
| 55 | +func AtMost(max int64) tfsdk.AttributeValidator { |
| 56 | + return atMostValidator{ |
| 57 | + max: max, |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +// validateInt ensures that the request contains an Int64 value. |
| 62 | +func validateInt(ctx context.Context, request tfsdk.ValidateAttributeRequest, response *tfsdk.ValidateAttributeResponse) (int64, bool) { |
| 63 | + var n types.Int64 |
| 64 | + |
| 65 | + diags := tfsdk.ValueAs(ctx, request.AttributeConfig, &n) |
| 66 | + |
| 67 | + if diags.HasError() { |
| 68 | + response.Diagnostics = append(response.Diagnostics, diags...) |
| 69 | + |
| 70 | + return 0, false |
| 71 | + } |
| 72 | + |
| 73 | + if n.Unknown || n.Null { |
| 74 | + return 0, false |
| 75 | + } |
| 76 | + |
| 77 | + return n.Value, true |
| 78 | +} |
0 commit comments