hashicorp / terraform-plugin-codegen-spec

Terraform Provider Code Generation Specification and Go Bindings
Mozilla Public License 2.0
7 stars 4 forks source link

Consider adding schema definition string method on types #23

Open bendbennett opened 1 year ago

bendbennett commented 1 year ago

In the terraform-plugin-codegen-framework code strings for the types for use in generated schema are produced along the following lines:

switch {
case v.Bool != nil:
    if v.Bool.CustomType != nil {
        aTypes.WriteString(v.Bool.CustomType.Type)
    } else {
        aTypes.WriteString("types.BoolType")
    }
    // ...
}

A method could be created for each of the types so that the logic for determining which string to return would be come the responsibility of the type itself rather than the caller.

For instance:

switch {
case v.Bool != nil:
    aTypes.WriteString(v.Bool.SchemaString)
    // ...
}
bflad commented 1 year ago

This feels like more of a framework code generation issue than something to solve within specification code as I don't think the specification should know or understand SDK-specific details (e.g. types.BoolType). Generating terraform-plugin-go code, for another example, would be concerned with understanding tftypes package implementation details.

One potential way to envision this on the framework side of things is having a wrapper type, similar to the schema wrapper types, that knows how to handle the framework-specific details:

// In terraform-plugin-codegen-framework/internal/schema package since
// it should theoretically be generic across any schema type.
package schema

type BoolType struct {
  CustomType *schemaspec.CustomType // or its own type, if there's shared framework-specific details worth abstracting
}

func (t BoolType) SchemaDefinition() string {
  if t.CustomType != nil {
    return t.CustomType.Type
  }

  return "types.BoolType"
}

func (t BoolType) SchemaImport() string {
  if t.CustomType != nil {
    if t.CustomType.HasImport() {
      return t.CustomType.Import
    }

    return ""
  }

  return "github.com/hashicorp/terraform-plugin-framework/types"
}