## Description
<!-- **Please link some issue here describing what you are trying to achieve.**
In case there is no issue present for your PR, please consider creating one.
At least please give us some description what you are trying to achieve and why your change is needed. -->
relates to #1234
## Checklist
- [ ] Issue was linked above
- [ ] Code format was applied: `make fmt`
- [ ] Examples were added / adjusted (see `examples/` directory)
- [x] Docs are up-to-date: `make generate-docs` (will be checked by CI)
- [ ] Unit tests got implemented or updated
- [ ] Acceptance tests got implemented or updated (see e.g. [here](f5f99d1709/stackit/internal/services/dns/dns_acc_test.go))
- [x] Unit tests are passing: `make test` (will be checked by CI)
- [x] No linter issues: `make lint` (will be checked by CI)
Reviewed-on: #58
Co-authored-by: Marcel S. Henselin <marcel.henselin@stackit.cloud>
Co-committed-by: Marcel S. Henselin <marcel.henselin@stackit.cloud>
49 lines
1.5 KiB
Go
49 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
|
|
}
|