Skip to content

Commit

Permalink
internal/fwschemadata: Migrate tfsdk GetAttribute and getAttributeVal…
Browse files Browse the repository at this point in the history
…ue logic (hashicorp#453)

Reference: hashicorp#366

This change continues the migration of `tfsdk.Config`/`tfsdk.Plan`/`tfsdk.State` type logic into the `internal/fwschemadata` package `Data` type, so the implementation is shared and to potentially introduce other implementations.
  • Loading branch information
bflad authored Aug 15, 2022
1 parent c0fe42b commit 655bd5d
Show file tree
Hide file tree
Showing 10 changed files with 7,483 additions and 4,830 deletions.
62 changes: 62 additions & 0 deletions internal/fwschemadata/data_get_at_path.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package fwschemadata

import (
"context"
"fmt"

"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/internal/logging"
"github.com/hashicorp/terraform-plugin-framework/internal/reflect"
"github.com/hashicorp/terraform-plugin-framework/path"
)

// GetAtPath retrieves the attribute found at `path` and populates the
// `target` with the value.
func (d Data) GetAtPath(ctx context.Context, schemaPath path.Path, target any) diag.Diagnostics {
ctx = logging.FrameworkWithAttributePath(ctx, schemaPath.String())

attrValue, diags := d.ValueAtPath(ctx, schemaPath)

if diags.HasError() {
return diags
}

if attrValue == nil {
diags.AddAttributeError(
schemaPath,
"Config Read Error",
"An unexpected error was encountered trying to read an attribute from the configuration. This is always an error in the provider. Please report the following to the provider developer:\n\n"+
"Missing attribute value, however no error was returned. Preventing the panic from this situation.",
)
return diags
}

if reflect.IsGenericAttrValue(ctx, target) {
*(target.(*attr.Value)) = attrValue
return nil
}

raw, err := attrValue.ToTerraformValue(ctx)

if err != nil {
diags.AddAttributeError(
schemaPath,
"Error converting value",
fmt.Sprintf("An unexpected error was encountered converting a %T to its equivalent Terraform representation. This is always a bug in the provider.\n\n"+
"Error: %s", attrValue, err),
)
return diags
}

reflectDiags := reflect.Into(ctx, attrValue.Type(ctx), raw, target, reflect.Options{})

// reflect.Into does not have path information for its Diagnostics.
for idx, valueAsDiag := range reflectDiags {
reflectDiags[idx] = diag.WithPath(schemaPath, valueAsDiag)
}

diags.Append(reflectDiags...)

return diags
}
Loading

0 comments on commit 655bd5d

Please sign in to comment.