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

Added commercetools_state as datasource #401

Merged
merged 1 commit into from
Aug 11, 2023
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 .changes/unreleased/Added-20230810-093613.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
kind: Added
body: '**New data source:** `commercetools_state`'
time: 2023-08-10T09:36:13.176619198+02:00
51 changes: 51 additions & 0 deletions docs/data-sources/state.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "commercetools_state Data Source - terraform-provider-commercetools"
subcategory: ""
description: |-
Fetches state information for the given key. This is an easy way to import the id of an existing state for a given key.
---

# commercetools_state (Data Source)

Fetches state information for the given key. This is an easy way to import the id of an existing state for a given key.

## Example Usage

```terraform
# The Initial state is a state that is provided in a new commercetools environment by default
data "commercetools_state" "initial_state" {
key = "Initial"
}

resource "commercetools_state_transitions" "from_created_to_allocated" {
from = data.commercetools_state.initial_state.id
to = [
commercetools_state.backorder.id,
]
}

resource "commercetools_state" "backorder" {
key = "backorder"
type = "LineItemState"
name = {
en = "Back Order",

}
description = {
en = "Not available - on back order"
}
initial = false
}
```

<!-- schema generated by tfplugindocs -->
## Schema

### Required

- `key` (String) Key of the state

### Read-Only

- `id` (String) ID of the state
19 changes: 18 additions & 1 deletion docs/data-sources/type.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,24 @@ description: |-

Fetches type information


## Example Usage

```terraform
data "commercetools_type" "existing_type" {
key = "test"
}

resource "commercetools_channel" "test" {
key = "test"
roles = ["ProductDistribution"]
custom {
type_id = data.commercetools_type.existing_type.id
fields = {
"my-field" = "foobar"
}
}
}
```

<!-- schema generated by tfplugindocs -->
## Schema
Expand Down
24 changes: 24 additions & 0 deletions examples/data-sources/commercetools_state/data-source.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# The Initial state is a state that is provided in a new commercetools environment by default
data "commercetools_state" "initial_state" {
key = "Initial"
}

resource "commercetools_state_transitions" "from_created_to_allocated" {
from = data.commercetools_state.initial_state.id
to = [
commercetools_state.backorder.id,
]
}

resource "commercetools_state" "backorder" {
key = "backorder"
type = "LineItemState"
name = {
en = "Back Order",

}
description = {
en = "Not available - on back order"
}
initial = false
}
14 changes: 14 additions & 0 deletions examples/data-sources/commercetools_type/data-source.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
data "commercetools_type" "existing_type" {
key = "test"
}

resource "commercetools_channel" "test" {
key = "test"
roles = ["ProductDistribution"]
custom {
type_id = data.commercetools_type.existing_type.id
fields = {
"my-field" = "foobar"
}
}
}
97 changes: 97 additions & 0 deletions internal/datasource/state/resource.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package custom_type

import (
"context"

"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/labd/commercetools-go-sdk/platform"

"github.com/labd/terraform-provider-commercetools/internal/utils"
)

// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &StateSource{}
_ datasource.DataSourceWithConfigure = &StateSource{}
)

// NewDataSource is a helper function to simplify the data source implementation.
func NewDataSource() datasource.DataSource {
return &StateSource{}
}

// StateSource is the data source implementation.
type StateSource struct {
client *platform.ByProjectKeyRequestBuilder
mutex *utils.MutexKV
demeyerthom marked this conversation as resolved.
Show resolved Hide resolved
}

// StateModel maps the data source schema data.
type StateModel struct {
ID types.String `tfsdk:"id"`
Key types.String `tfsdk:"key"`
}

// Metadata returns the data source type name.
func (d *StateSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_state"
}

// Schema defines the schema for the data source.
func (d *StateSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Fetches state information for the given key. " +
"This is an easy way to import the id of an existing state for a given key.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: "ID of the state",
Computed: true,
},
"key": schema.StringAttribute{
Description: "Key of the state",
Required: true,
},
},
}
}

// Configure adds the provider configured client to the data source.
func (d *StateSource) Configure(_ context.Context, req datasource.ConfigureRequest, _ *datasource.ConfigureResponse) {
if req.ProviderData == nil {
return
}

Check warning on line 64 in internal/datasource/state/resource.go

View check run for this annotation

Codecov / codecov/patch

internal/datasource/state/resource.go#L63-L64

Added lines #L63 - L64 were not covered by tests
data := req.ProviderData.(*utils.ProviderData)
d.client = data.Client
d.mutex = data.Mutex
}

// Read refreshes the Terraform state with the latest data.
func (d *StateSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var state StateModel

diags := req.Config.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}

Check warning on line 78 in internal/datasource/state/resource.go

View check run for this annotation

Codecov / codecov/patch

internal/datasource/state/resource.go#L77-L78

Added lines #L77 - L78 were not covered by tests

resource, err := d.client.States().WithKey(state.Key.ValueString()).Get().Execute(ctx)
if err != nil {
resp.Diagnostics.AddError(
"Unable to read state",
err.Error(),
)
return
}

Check warning on line 87 in internal/datasource/state/resource.go

View check run for this annotation

Codecov / codecov/patch

internal/datasource/state/resource.go#L82-L87

Added lines #L82 - L87 were not covered by tests

state.ID = types.StringValue(resource.ID)

// Set state
diags = resp.State.Set(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}

Check warning on line 96 in internal/datasource/state/resource.go

View check run for this annotation

Codecov / codecov/patch

internal/datasource/state/resource.go#L95-L96

Added lines #L95 - L96 were not covered by tests
}
90 changes: 90 additions & 0 deletions internal/datasource/state/resource_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package custom_type_test

import (
"context"
"fmt"
"testing"

acctest "github.com/labd/terraform-provider-commercetools/internal/acctest"
"github.com/labd/terraform-provider-commercetools/internal/utils"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
"github.com/stretchr/testify/assert"
)

func TestAccState(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { acctest.TestAccPreCheck(t) },
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories,
CheckDestroy: testAccCheckDestroy,
Steps: []resource.TestStep{
{
Config: testAccConfigLoadState(),
Check: resource.ComposeTestCheckFunc(
func(s *terraform.State) error {
client, err := acctest.GetClient()
if err != nil {
return nil
}
result, err := client.States().WithKey("test").Get().Execute(context.Background())
if err != nil {
return nil
}
assert.NotNil(t, result)
assert.Equal(t, result.Key, "test")
return nil
},
),
},
},
})
}

func testAccCheckDestroy(s *terraform.State) error {
client, err := acctest.GetClient()
if err != nil {
return err
}

for _, rs := range s.RootModule().Resources {
if rs.Type != "commercetools_state" {
continue
}
response, err := client.States().WithId(rs.Primary.ID).Get().Execute(context.Background())
if err == nil {
if response != nil && response.ID == rs.Primary.ID {
return fmt.Errorf("state (%s) still exists", rs.Primary.ID)
}
return nil
}
if newErr := acctest.CheckApiResult(err); newErr != nil {
return newErr
}
}
return nil
}

func testAccConfigLoadState() string {
return utils.HCLTemplate(`
resource "commercetools_state" "test" {
key = "test"
type = "ReviewState"
name = {
en = "Unreviewed"
}
description = {
en = "Not reviewed yet"
}
initial = true
}

data "commercetools_state" "test" {
key = "test"

depends_on = [
commercetools_state.test
]
}
`, map[string]any{})
}
4 changes: 2 additions & 2 deletions internal/datasource/type/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ var (
_ datasource.DataSourceWithConfigure = &CustomTypeSource{}
)

// NewCustomTypeSource is a helper function to simplify the provider implementation.
func NewTypeDataSource() datasource.DataSource {
// NewDataSource is a helper function to simplify the provider implementation.
func NewDataSource() datasource.DataSource {
return &CustomTypeSource{}
}

Expand Down
6 changes: 4 additions & 2 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ import (
"github.com/labd/commercetools-go-sdk/platform"
"golang.org/x/oauth2/clientcredentials"

custom_type "github.com/labd/terraform-provider-commercetools/internal/datasource/type"
datasourcestate "github.com/labd/terraform-provider-commercetools/internal/datasource/state"
datasourcetype "github.com/labd/terraform-provider-commercetools/internal/datasource/type"
"github.com/labd/terraform-provider-commercetools/internal/resources/project"
"github.com/labd/terraform-provider-commercetools/internal/resources/state"
"github.com/labd/terraform-provider-commercetools/internal/resources/state_transition"
Expand Down Expand Up @@ -180,7 +181,8 @@ func (p *ctProvider) Configure(ctx context.Context, req provider.ConfigureReques
// DataSources defines the data sources implemented in the provider.
func (p *ctProvider) DataSources(_ context.Context) []func() datasource.DataSource {
return []func() datasource.DataSource{
custom_type.NewTypeDataSource,
datasourcetype.NewDataSource,
datasourcestate.NewDataSource,
}
}

Expand Down
Loading