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.
pull/34814/head
Martin Atkins 2 years ago
parent 70537aab08
commit 1eaa18d60a

@ -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

Loading…
Cancel
Save