Skip to content

Commit

Permalink
feat: Partial implementation of str_iterative_replace.
Browse files Browse the repository at this point in the history
  • Loading branch information
skyzyx committed Mar 11, 2024
1 parent a7f932f commit 098169b
Show file tree
Hide file tree
Showing 5 changed files with 255 additions and 0 deletions.
117 changes: 117 additions & 0 deletions corefuncprovider/str_iterative_replace_function.go.bak
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// Copyright 2023-2024, Northwood Labs
// Copyright 2023-2024, Ryan Parman <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package corefuncprovider // lint:no_dupe

import (
"context"
"fmt"
"strings"

"github.com/hashicorp/terraform-plugin-framework/function"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/lithammer/dedent"
"github.com/northwood-labs/terraform-provider-corefunc/corefunc"
)

// Ensure the implementation satisfies the expected interfaces.
var _ function.Function = &strIterativeReplaceFunction{}

type (
// strIterativeReplaceFunction is the function implementation.
strIterativeReplaceFunction struct{}
)

// StrIterativeReplaceFunction is a method that exposes its paired Go function as a
// Terraform Function.
// https://developer.hashicorp.com/terraform/plugin/framework/functions/implementation
func StrIterativeReplaceFunction() function.Function { // lint:allow_return_interface
return &strIterativeReplaceFunction{}
}

func (f *strIterativeReplaceFunction) Metadata(
ctx context.Context,
req function.MetadataRequest,
resp *function.MetadataResponse,
) {
tflog.Debug(ctx, "Starting StrIterativeReplace Function Metadata method.")

resp.Name = "str_iterative_replace"

tflog.Debug(ctx, fmt.Sprintf("resp.Name = %s", resp.Name))

tflog.Debug(ctx, "Ending StrIterativeReplace Function Metadata method.")
}

// Definition defines the parameters and return type for the function.
func (f *strIterativeReplaceFunction) Definition(
ctx context.Context,
req function.DefinitionRequest,
resp *function.DefinitionResponse,
) {
tflog.Debug(ctx, "Starting StrIterativeReplace Function Definition method.")

resp.Definition = function.Definition{
Summary: "Performs a series of replacements against a string.",
MarkdownDescription: strings.TrimSpace(dedent.Dedent(`
Performs a series of replacements against a string. Allows a Terraform
module to accept a set of replacements from a user.

Maps to the [` + "`" + `corefunc.StrIterativeReplace()` + "`" + `](URL)
Go method, which can be used in ` + Terratest + `.
`)),
Parameters: []function.Parameter{
function.StringParameter{
Name: "str",
MarkdownDescription: "The string upon which replacements should be applied.",
},
function.ListParameter{
Name: "replacements",
MarkdownDescription: strings.TrimSpace(dedent.Dedent(`
A list of maps. Each map has an ` + "`" + `old` + "`" + ` and ` + "`" + `new` + "`" +
` key. ` + "`" + `old` + "`" + ` represents the existing string to be replaced, and ` + "`" +
`new` + "`" + ` represents the replacement string.
`)),
ElementType: types.MapType{},
// https://discuss.hashicorp.com/t/provider-functions-equivalent-to-schema-listnestedattribute/63585
},
},
Return: function.StringReturn{},
}

tflog.Debug(ctx, "Ending StrIterativeReplace Function Definition method.")
}

func (f *strIterativeReplaceFunction) Run(ctx context.Context, req function.RunRequest, resp *function.RunResponse) {
tflog.Debug(ctx, "Starting StrIterativeReplace Function Run method.")

var str string
err := req.Arguments.Get(ctx, &str)

resp.Error = function.ConcatFuncErrors(err)
if resp.Error != nil {
return
}

value := corefunc.StrIterativeReplace(
str,
// opts,
)

resp.Error = function.ConcatFuncErrors(resp.Result.Set(ctx, value))

tflog.Debug(ctx, "Ending StrIterativeReplace Function Run method.")
}
14 changes: 14 additions & 0 deletions corefuncprovider/str_iterative_replace_function_fixture.tftpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
output "replacements" {
value = provider::corefunc::str_iterative_replace(
"{{ .Input }}",
[
{{- with .Replacements }}{{- range . }}
{
old = "{{- .Old -}}"
new = "{{- .New -}}"
},
{{- end }}{{- end }}
]
)
}
#=> {{ .Expected }}
78 changes: 78 additions & 0 deletions corefuncprovider/str_iterative_replace_function_test.go.bak
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Copyright 2023-2024, Northwood Labs
// Copyright 2023-2024, Ryan Parman <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package corefuncprovider // lint:no_dupe

import (
"bytes"
"fmt"
"log"
"os"
"strings"
"testing"
"text/template"

"github.com/northwood-labs/terraform-provider-corefunc/testfixtures"

"github.com/hashicorp/go-version"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/tfversion"
)

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

funcName := traceFuncName()

for name, tc := range testfixtures.StrIterativeReplaceTestTable { // lint:no_dupe
fmt.Printf(
"=== RUN %s/%s\n",
strings.TrimSpace(funcName),
strings.TrimSpace(name),
)

buf := &bytes.Buffer{}
tmpl := template.Must(
template.ParseFiles("str_iterative_replace_function_fixture.tftpl"),
)

err := tmpl.Execute(buf, tc)
if err != nil {
log.Fatalln(err)
}

if os.Getenv("PROVIDER_DEBUG") != "" {
fmt.Fprintln(os.Stderr, buf.String())
}

resource.UnitTest(t, resource.TestCase{
TerraformVersionChecks: []tfversion.TerraformVersionCheck{
tfversion.SkipBelow(
version.Must(version.NewVersion("1.7.999")),
),
},
ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
Steps: []resource.TestStep{
{
Config: providerConfig + buf.String(),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckOutput("@TODO", tc.Expected),
),
// ExpectError: tc.expectedError,
},
},
})
}
}
33 changes: 33 additions & 0 deletions examples/functions/corefunc_str_iterative_replace/function.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
output "replacements" {
value = provider::corefunc::str_iterative_replace(
"This is a string for testing replacements. New Relic. Set-up.",
[
{
old = "."
new = ""
},
{
old = " "
new = "_"
},
{
old = "-"
new = "_"
},
{
old = "New Relic"
new = "datadog"
},
{
old = "This"
new = "this"
},
{
old = "Set-up"
new = "setup"
},
],
)
}

#=> this_is_a_string_for_testing_replacements_datadog_setup
13 changes: 13 additions & 0 deletions examples/functions/corefunc_str_iterative_replace/versions.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
terraform {
required_version = "~> 1.8"

required_providers {
corefunc = {
source = "northwood-labs/corefunc"
version = "~> 1.4"
}
}
}

# There are no configuration options
provider "corefunc" {}

0 comments on commit 098169b

Please sign in to comment.