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

Implement State, State.Get, State.GetAttribute #43

Closed
wants to merge 2 commits into from
Closed
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
13 changes: 13 additions & 0 deletions attr/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,19 @@ type Type interface {
// Equal must return true if the Type is considered semantically equal
// to the Type passed as an argument.
Equal(Type) bool

tftypes.AttributePathStepper
}

// ObjectType extends the Type interface to include a method returning a copy
// of the type with its "attribute types" filled in. Attribute types are
// part of the definition of an object type.
type ObjectType interface {
Type

// Equal must return true if the Type is considered semantically equal
// to the Type passed as an argument.
Equal(Type) bool
}

// TypeWithValidate extends the Type interface to include a Validate method,
Expand Down
14 changes: 13 additions & 1 deletion schema/attribute.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package schema

import "github.com/hashicorp/terraform-plugin-framework/attr"
import (
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-go/tftypes"
)

// Attribute defines the constraints and behaviors of a single field in a
// schema. Attributes are the fields that show up in Terraform state files and
Expand Down Expand Up @@ -60,3 +63,12 @@ type Attribute struct {
// instructing them on what upgrade steps to take.
DeprecationMessage string
}

func (a Attribute) ApplyTerraform5AttributePathStep(step tftypes.AttributePathStep) (interface{}, error) {
if a.Type != nil {
return a.Type.ApplyTerraform5AttributePathStep(step)
}
if a.Attributes != nil {
return a.Attributes.ApplyTerraform5AttributePathStep(step)
}
}
9 changes: 9 additions & 0 deletions schema/nested_attributes.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ const (
type NestedAttributes interface {
getNestingMode() nestingMode
getAttributes() map[string]Attribute
tftypes.AttributePathStepper
}

type nestedAttributes map[string]Attribute
Expand Down Expand Up @@ -88,6 +89,14 @@ func (l listNestedAttributes) getNestingMode() nestingMode {
return nestingModeList
}

func (l listNestedAttributes) ApplyTerraform5AttributePathStep(step tftypes.AttributePathStep) (interface{}, error) {
if _, ok := step.(tftypes.ElementKeyInt); !ok {
return nil, fmt.Errorf("cannot apply step %T to ListNestedAttributes", step)
}

return l.nestedAttributes, nil
}

// SetNestedAttributes nests `attributes` under another attribute, allowing
// multiple instances of that group of attributes to appear in the
// configuration, while requiring each group of values be unique. Minimum and
Expand Down
18 changes: 18 additions & 0 deletions schema/schema.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
package schema

import (
"fmt"

"github.com/hashicorp/terraform-plugin-go/tftypes"
)

// Schema is used to define the shape of practitioner-provider information,
// like resources, data sources, and providers. Think of it as a type
// definition, but for Terraform.
Expand All @@ -17,3 +23,15 @@ type Schema struct {
// Versions should only be incremented by one each release.
Version int64
}

func (s Schema) ApplyTerraform5AttributePathStep(step tftypes.AttributePathStep) (interface{}, error) {
if v, ok := step.(tftypes.AttributeName); ok {
if attr, ok := s.Attributes[string(v)]; ok {
return attr, nil
} else {
return nil, fmt.Errorf("could not find attribute %q in schema", v)
}
} else {
return nil, fmt.Errorf("cannot apply AttributePathStep %T to schema", step)
}
}
43 changes: 43 additions & 0 deletions state.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package tfsdk

import (
"context"
"fmt"
"reflect"
"regexp"
"strings"

"github.com/hashicorp/terraform-plugin-framework/attr"
tfReflect "github.com/hashicorp/terraform-plugin-framework/internal/reflect"
"github.com/hashicorp/terraform-plugin-framework/schema"
"github.com/hashicorp/terraform-plugin-go/tftypes"
)

var attributeValueReflectType = reflect.TypeOf(new(attr.Value)).Elem()

type State struct {
Raw tftypes.Value
Schema schema.Schema
}

func isValidFieldName(name string) bool {
re := regexp.MustCompile("^[a-z][a-z0-9_]*$")
return re.MatchString(name)
}

// Get populates the struct passed as `target` with the entire state. No type assertion necessary.
func (s State) Get(ctx context.Context, target interface{}) error {
return tfReflect.Into(ctx, s.Raw, target, tfReflect.Options{}, tftypes.NewAttributePath())
}

// GetAttribute retrieves the attribute found at `path` and returns it as an attr.Value,
// which provider developers need to assert the type of
func (s State) GetAttribute(ctx context.Context, path tftypes.AttributePath) (attr.Value, error) {

}

// MustGetAttribute retrieves the attribute as GetAttribute does, but populates target using As,
// using the simplified representation without Unknown. Errors if Unknown present
func (s State) MustGetAttribute(ctx context.Context, path tftypes.AttributePath, target interface{}) error {
return nil
}
81 changes: 81 additions & 0 deletions state_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package tfsdk

import (
"context"
"testing"

"github.com/hashicorp/terraform-plugin-framework/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-go/tftypes"
)

func TestStateGet(t *testing.T) {
schema := schema.Schema{
Attributes: map[string]schema.Attribute{
"foo": {
Type: types.StringType,
Required: true,
},
"bar": {
Type: types.ListType{
ElemType: types.StringType,
},
Required: true,
},
},
}
state := State{
Raw: tftypes.NewValue(tftypes.Object{
AttributeTypes: map[string]tftypes.Type{
"foo": tftypes.String,
"bar": tftypes.List{ElementType: tftypes.String},
},
}, map[string]tftypes.Value{
"foo": tftypes.NewValue(tftypes.String, "hello, world"),
"bar": tftypes.NewValue(tftypes.List{
ElementType: tftypes.String,
}, []tftypes.Value{
tftypes.NewValue(tftypes.String, "red"),
tftypes.NewValue(tftypes.String, "blue"),
tftypes.NewValue(tftypes.String, "green"),
}),
}),
Schema: schema,
}
type myType struct {
Foo types.String `tfsdk:"foo"`
Bar types.List `tfsdk:"bar"`
}
var val myType
err := state.Get(context.Background(), &val)
if err != nil {
t.Errorf("Error running As: %s", err)
}
if val.Foo.Unknown {
t.Error("Expected Foo to be known")
}
if val.Foo.Null {
t.Error("Expected Foo to be non-null")
}
if val.Foo.Value != "hello, world" {
t.Errorf("Expected Foo to be %q, got %q", "hello, world", val.Foo.Value)
}
if val.Bar.Unknown {
t.Error("Expected Bar to be known")
}
if val.Bar.Null {
t.Errorf("Expected Bar to be non-null")
}
if len(val.Bar.Elems) != 3 {
t.Errorf("Expected Bar to have 3 elements, had %d", len(val.Bar.Elems))
}
if val.Bar.Elems[0].(types.String).Value != "red" {
t.Errorf("Expected Bar's first element to be %q, got %q", "red", val.Bar.Elems[0].(types.String).Value)
}
if val.Bar.Elems[1].(types.String).Value != "blue" {
t.Errorf("Expected Bar's second element to be %q, got %q", "blue", val.Bar.Elems[1].(types.String).Value)
}
if val.Bar.Elems[2].(types.String).Value != "green" {
t.Errorf("Expected Bar's third element to be %q, got %q", "green", val.Bar.Elems[2].(types.String).Value)
}
}
34 changes: 23 additions & 11 deletions types/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,17 +85,9 @@ type List struct {
func (l *List) ElementsAs(ctx context.Context, target interface{}, allowUnhandled bool) error {
// we need a tftypes.Value for this List to be able to use it with our
// reflection code
values := make([]tftypes.Value, 0, len(l.Elems))
for pos, elem := range l.Elems {
val, err := elem.ToTerraformValue(ctx)
if err != nil {
return fmt.Errorf("error getting Terraform value for element %d: %w", pos, err)
}
err = tftypes.ValidateValue(l.ElemType.TerraformType(ctx), val)
if err != nil {
return fmt.Errorf("error using created Terraform value for element %d: %w", pos, err)
}
values = append(values, tftypes.NewValue(l.ElemType.TerraformType(ctx), val))
values, err := l.ToTerraformValue(ctx)
if err != nil {
return err
}
return reflect.Into(ctx, tftypes.NewValue(tftypes.List{
ElementType: l.ElemType.TerraformType(ctx),
Expand Down Expand Up @@ -195,3 +187,23 @@ func (l *List) SetTerraformValue(ctx context.Context, in tftypes.Value) error {
l.Elems = elems
return nil
}

// ListOf returns a new list with an ElemType of tftypes.Object, whose elements
// are the values passed in. The struct type must have struct tags TODO
// func ListOf(values []interface{}) List {
// // make the list
// // populate the list with tftypes.Objects

// // to make the object type:
// // reflect to get the type of the passed in struct
// // need to get map[string]tftypes.Type

// l := List{
// ElemType: tftypes.Object,
// }

// for _, v := range values {
// objType :=
// l.Elems = append(l.Elems, )
// }
// }
4 changes: 4 additions & 0 deletions types/primitive.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,7 @@ func (p primitive) Equal(o attr.Type) bool {
return false
}
}

func (p primitive) ApplyTerraform5AttributePathStep(step tftypes.AttributePathStep) (interface{}, error) {
return nil, fmt.Errorf("cannot apply AttributePathStep %T to %s", step, p.String())
}