From 1eaa18d60adeebd7488551f0ecaf72aa7d7368ab Mon Sep 17 00:00:00 2001 From: Martin Atkins Date: Tue, 5 Mar 2024 18:08:45 -0800 Subject: [PATCH] backendbase: IntValue With legacy helper/schema it's common to just type-assert whatever ResourceData.Get returns and trust that it'll always be valid. We can't achieve something quite that lazy with cty, but we can at least factor out the work of turning a value we already know is a number into an int64 value. --- internal/backend/backendbase/helper.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/internal/backend/backendbase/helper.go b/internal/backend/backendbase/helper.go index bd03c67d73..3e84c0b91d 100644 --- a/internal/backend/backendbase/helper.go +++ b/internal/backend/backendbase/helper.go @@ -5,6 +5,7 @@ package backendbase import ( "fmt" + "math/big" "os" "github.com/hashicorp/terraform/internal/tfdiags" @@ -93,6 +94,23 @@ func GetAttrEnvDefaultFallback(v cty.Value, attrName string, defEnv string, fall return ret } +// IntValue converts a cty value of type cty.Number into a Go int64, or returns +// an error if that's not possible. +func IntValue(v cty.Value) (int64, error) { + if v.Type() != cty.Number { + return 0, fmt.Errorf("a number is required") + } + if v.IsNull() { + return 0, fmt.Errorf("must not be null") + } + bf := v.AsBigFloat() + ret, acc := bf.Int64() + if acc != big.Exact { + return 0, fmt.Errorf("must not be a whole number") + } + return ret, nil +} + // ErrorAsDiagnostics wraps a non-nil error as a tfdiags.Diagnostics. // // Panics if the given error is nil, since the caller should only be using