terraform-provider-stackitp.../stackit/internal/utils/attributes.go
Marcel S. Henselin e5e8569bc1
Some checks failed
CI Workflow / Check GoReleaser config (pull_request) Successful in 4s
CI Workflow / Test readiness for publishing provider (pull_request) Successful in 11m7s
CI Workflow / CI (pull_request) Failing after 13m27s
CI Workflow / Code coverage report (pull_request) Has been skipped
chore: refactor import urls after repo move
2026-02-02 10:55:24 +01:00

48 lines
1.5 KiB
Go

// Copyright (c) STACKIT
package utils
import (
"context"
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/types"
"tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/core"
)
type attributeGetter interface {
GetAttribute(ctx context.Context, attributePath path.Path, target interface{}) diag.Diagnostics
}
func ToTime(ctx context.Context, format string, val types.String, target *time.Time) (diags diag.Diagnostics) {
var err error
text := val.ValueString()
*target, err = time.Parse(format, text)
if err != nil {
core.LogAndAddError(ctx, &diags, "cannot parse date", fmt.Sprintf("cannot parse date %q with format %q: %v", text, format, err))
return diags
}
return diags
}
// GetTimeFromStringAttribute retrieves a string attribute from e.g. a [plan.Plan], [tfsdk.Config] or a [tfsdk.State] and
// converts it to a [time.Time] object with a given format, if possible.
func GetTimeFromStringAttribute(ctx context.Context, attributePath path.Path, source attributeGetter, dateFormat string, target *time.Time) (diags diag.Diagnostics) {
var date types.String
diags.Append(source.GetAttribute(ctx, attributePath, &date)...)
if diags.HasError() {
return diags
}
if date.IsNull() || date.IsUnknown() {
return diags
}
diags.Append(ToTime(ctx, dateFormat, date, target)...)
if diags.HasError() {
return diags
}
return diags
}