Skip to content

Commit

Permalink
feat: Implementation of string formatting as funcs.
Browse files Browse the repository at this point in the history
  • Loading branch information
skyzyx committed Mar 11, 2024
1 parent 8110aea commit 6de9499
Show file tree
Hide file tree
Showing 38 changed files with 1,238 additions and 66 deletions.
Binary file modified acc-coverage.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
162 changes: 107 additions & 55 deletions acc-coverage.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions corefuncprovider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,10 @@ func (p *coreFuncProvider) Functions(ctx context.Context) []func() function.Func
RuntimeGorootFunction,
RuntimeNumcpusFunction,
RuntimeOsFunction,
StrCamelFunction,
StrConstantFunction,
StrKebabFunction,
StrPascalFunction,
StrSnakeFunction,
}
}
Expand Down
103 changes: 103 additions & 0 deletions corefuncprovider/str_camel_function.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// 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-log/tflog"
"github.com/lithammer/dedent"
"github.com/northwood-labs/terraform-provider-corefunc/corefunc"
)

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

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

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

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

resp.Name = "str_camel"

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

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

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

resp.Definition = function.Definition{
Summary: "Converts a string to `camelCase`, removing any non-alphanumeric characters.",
MarkdownDescription: strings.TrimSpace(dedent.Dedent(`
Converts a string to ` + "`" + `camelCase` + "`" + `, removing any non-alphanumeric characters.
-> Some acronyms are maintained as uppercase. See
[caps: pkg-variables](https://pkg.go.dev/github.com/chanced/caps#pkg-variables) for a complete list.
Maps to the ` + linkPackage("StrCamel") + ` Go method, which can be used in ` + Terratest + `.
`)),
Parameters: []function.Parameter{
function.StringParameter{
Name: "str",
MarkdownDescription: "The string to convert to `camelCase`.",
},
},
Return: function.StringReturn{},
}

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

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

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

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

value := corefunc.StrCamel(str)
resp.Error = function.ConcatFuncErrors(resp.Result.Set(ctx, value))

tflog.Debug(ctx, "Ending StrCamel Function Run method.")
}
4 changes: 4 additions & 0 deletions corefuncprovider/str_camel_function_fixture.tftpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
output "camel" {
value = provider::corefunc::str_camel("{{ .Input }}")
}
#=> {{ .Expected }}
77 changes: 77 additions & 0 deletions corefuncprovider/str_camel_function_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// 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 TestAccStrCamelFunction(t *testing.T) {
t.Parallel()

funcName := traceFuncName()

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

buf := &bytes.Buffer{}
tmpl := template.Must(
template.ParseFiles("str_camel_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("camel", tc.Expected),
),
},
},
})
}
}
101 changes: 101 additions & 0 deletions corefuncprovider/str_constant_function.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// 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-log/tflog"
"github.com/lithammer/dedent"
"github.com/northwood-labs/terraform-provider-corefunc/corefunc"
)

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

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

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

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

resp.Name = "str_constant"

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

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

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

resp.Definition = function.Definition{
Summary: "Converts a string to `CONSTANT_CASE`, removing any non-alphanumeric characters.",
MarkdownDescription: strings.TrimSpace(dedent.Dedent(`
Converts a string to ` + "`" + `CONSTANT_CASE` + "`" + `, removing any non-alphanumeric characters.
Also known as ` + "`" + `SCREAMING_SNAKE_CASE` + "`" + `.
Maps to the ` + linkPackage("StrConstant") + ` Go method, which can be used in ` + Terratest + `.
`)),
Parameters: []function.Parameter{
function.StringParameter{
Name: "str",
MarkdownDescription: "The string to convert to `CONSTANT_CASE`.",
},
},
Return: function.StringReturn{},
}

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

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

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

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

value := corefunc.StrConstant(str)
resp.Error = function.ConcatFuncErrors(resp.Result.Set(ctx, value))

tflog.Debug(ctx, "Ending StrConstant Function Run method.")
}
4 changes: 4 additions & 0 deletions corefuncprovider/str_constant_function_fixture.tftpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
output "constant" {
value = provider::corefunc::str_constant("{{ .Input }}")
}
#=> {{ .Expected }}
77 changes: 77 additions & 0 deletions corefuncprovider/str_constant_function_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// 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 TestAccStrConstantFunction(t *testing.T) {
t.Parallel()

funcName := traceFuncName()

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

buf := &bytes.Buffer{}
tmpl := template.Must(
template.ParseFiles("str_constant_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("constant", tc.Expected),
),
},
},
})
}
}
Loading

0 comments on commit 6de9499

Please sign in to comment.