Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow using ValueAs into attr.Value. #232

Merged
merged 2 commits into from
Dec 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .changelog/232.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:enhancement
Added the ability to get an attribute as a generic `attr.Value` when using `GetAttribute`.
```
12 changes: 12 additions & 0 deletions internal/reflect/generic_attr_value.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package reflect

import (
"context"
"reflect"

"github.com/hashicorp/terraform-plugin-framework/attr"
)

func IsGenericAttrValue(ctx context.Context, target interface{}) bool {
return reflect.TypeOf((*attr.Value)(nil)) == reflect.TypeOf(target)
}
4 changes: 4 additions & 0 deletions tfsdk/value_as.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ import (
// the contents of `val`, using the reflection rules
// defined for `Get` and `GetAttribute`.
func ValueAs(ctx context.Context, val attr.Value, target interface{}) diag.Diagnostics {
if reflect.IsGenericAttrValue(ctx, target) {
*(target.(*attr.Value)) = val
return nil
}
raw, err := val.ToTerraformValue(ctx)
if err != nil {
return diag.Diagnostics{diag.NewErrorDiagnostic("Error converting value",
Expand Down
14 changes: 14 additions & 0 deletions tfsdk/value_as_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,17 @@ func TestValueAs(t *testing.T) {
})
}
}

func TestValueAs_generic(t *testing.T) {
t.Parallel()

var target attr.Value
val := types.String{Value: "hello"}
diags := ValueAs(context.Background(), val, &target)
if len(diags) > 0 {
t.Fatalf("Unexpected diagnostics: %s", diags)
}
if !val.Equal(target.(attr.Value)) {
t.Errorf("Expected target to be %v, got %v", val, target)
}
}