Skip to content
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
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ require (
github.com/hashicorp/terraform-plugin-mux v0.21.0
github.com/hashicorp/terraform-plugin-sdk/v2 v2.38.1
github.com/hashicorp/terraform-plugin-testing v1.13.3
github.com/huandu/xstrings v1.5.0
github.com/jarcoal/httpmock v1.4.1
github.com/mongodb-forks/digest v1.1.0
github.com/mongodb/atlas-sdk-go v1.0.1-0.20251103084024-4a19449c6541
Expand Down
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -345,8 +345,6 @@ github.com/hashicorp/yamux v0.1.2 h1:XtB8kyFOyHXYVFnwT5C3+Bdo8gArse7j2AQ0DA0Uey8
github.com/hashicorp/yamux v0.1.2/go.mod h1:C+zze2n6e/7wshOZep2A70/aQU6QBRWJO/G6FT1wIns=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
github.com/huandu/xstrings v1.5.0 h1:2ag3IFq9ZDANvthTwTiqSSZLjDc+BedvHPAp5tJy2TI=
github.com/huandu/xstrings v1.5.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
Expand Down
75 changes: 32 additions & 43 deletions internal/common/autogen/stringcase/string_case.go
Original file line number Diff line number Diff line change
@@ -1,60 +1,49 @@
package stringcase

import (
"fmt"
"regexp"
"strings"
"unicode"
"unicode/utf8"

"github.com/huandu/xstrings"
)

var (
camelCase = regexp.MustCompile(`([a-z])[A-Z]`)
unsupportedCharacters = regexp.MustCompile(`[^a-zA-Z0-9_]+`)
)

type SnakeCaseString string

func (snake SnakeCaseString) SnakeCase() string {
return string(snake)
}

func (snake SnakeCaseString) PascalCase() string {
return xstrings.ToPascalCase(string(snake))
}

func (snake SnakeCaseString) CamelCase() string {
return xstrings.ToCamelCase(string(snake))
}

func (snake SnakeCaseString) LowerCaseNoUnderscore() string {
return strings.ReplaceAll(string(snake), "_", "")
}
var unsupportedCharacters = regexp.MustCompile(`[^a-zA-Z0-9_]+`)

func FromCamelCase(input string) SnakeCaseString {
if input == "" {
return SnakeCaseString(input)
// ToSnakeCase Multiple consecutive uppercase letters are treated as part of the same word except for the last one.
// Example: "MongoDBMajorVersion" -> "mongo_db_major_version"
func ToSnakeCase(str string) string {
if str == "" {
return str
}

removedUnsupported := unsupportedCharacters.ReplaceAllString(input, "")

insertedUnderscores := camelCase.ReplaceAllStringFunc(removedUnsupported, func(s string) string {
firstChar := s[0]
restOfString := s[1:]
return fmt.Sprintf("%c_%s", firstChar, strings.ToLower(restOfString))
})

return SnakeCaseString(strings.ToLower(insertedUnderscores))
}
str = unsupportedCharacters.ReplaceAllString(str, "")

func ToCamelCase(str string) string {
return xstrings.ToCamelCase(str)
}
builder := &strings.Builder{}
runes := []rune(str)
length := len(runes)

prevIsUpper := unicode.IsUpper(runes[0])
builder.WriteRune(unicode.ToLower(runes[0]))

for i := 1; i < length; i++ {
current := runes[i]
currentIsUpper := unicode.IsUpper(runes[i])

// Write an underscore before uppercase letter if:
// - Previous char was lowercase, so this is the first uppercase.
// - Next char is lowercase, so this is the last uppercase in a sequence.
if currentIsUpper {
if !prevIsUpper || (i+1 != length && unicode.IsLower(runes[i+1])) {
builder.WriteByte('_')
}
current = unicode.ToLower(current)
}

builder.WriteRune(current)
prevIsUpper = currentIsUpper
}

func ToSnakeCase(str string) string {
return xstrings.ToSnakeCase(str)
return builder.String()
}

func Capitalize(str string) string {
Expand Down
75 changes: 73 additions & 2 deletions internal/common/autogen/stringcase/string_case_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func TestCapitalize(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if actual := stringcase.Capitalize(tt.input); actual != tt.expected {
t.Errorf("Capitalize() returned %v, expected %v", actual, tt.expected)
t.Errorf("Capitalize(%q) returned %q, expected %q", tt.input, actual, tt.expected)
}
})
}
Expand Down Expand Up @@ -92,7 +92,78 @@ func TestUncapitalize(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if actual := stringcase.Uncapitalize(tt.input); actual != tt.expected {
t.Errorf("Uncapitalize() returned %v, expected %v", actual, tt.expected)
t.Errorf("Uncapitalize(%q) returned %q, expected %q", tt.input, actual, tt.expected)
}
})
}
}

func TestToSnakeCase(t *testing.T) {
tests := []struct {
name string
input string
expected string
}{
{
name: "Empty string",
input: "",
expected: "",
},
{
name: "Single letter",
input: "a",
expected: "a",
},
{
name: "Single uppercase letter",
input: "A",
expected: "a",
},
{
name: "Simple camelCase",
input: "camelCase",
expected: "camel_case",
},
{
name: "Simple PascalCase",
input: "PascalCase",
expected: "pascal_case",
},
{
name: "All lowercase",
input: "word",
expected: "word",
},
{
name: "All uppercase",
input: "WORD",
expected: "word",
},
{
name: "Consecutive uppercase at start, middle and end",
input: "THISIsANExampleWORD",
expected: "this_is_an_example_word",
},
{
name: "Numbers do not split words",
input: "Example123Word456WithNUMBERS789",
expected: "example123_word456_with_numbers789",
},
{
name: "Already snake_case",
input: "already_snake_case",
expected: "already_snake_case",
},
{
name: "Unsupported characters are removed",
input: "Example#!Unsup-.ported%&Chars",
expected: "example_unsupported_chars",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if actual := stringcase.ToSnakeCase(tt.input); actual != tt.expected {
t.Errorf("ToSnakeCase(%q) returned %q, expected %q", tt.input, actual, tt.expected)
}
})
}
Expand Down
12 changes: 6 additions & 6 deletions internal/serviceapi/clusterapi/resource_schema.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion internal/serviceapi/clusterapi/resource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func TestAccClusterAPI_basic(t *testing.T) {
ImportStateVerifyIdentifierAttribute: "name",
ImportStateVerifyIgnore: []string{
"retain_backups_enabled", // This field is TF specific and not returned by Atlas, so Import can't fill it in.
"mongo_dbmajor_version", // Risks plan change of 8 --> 8.0 (always normalized to `major.minor`)
"mongo_db_major_version", // Risks plan change of 8 --> 8.0 (always normalized to `major.minor`)
"state_name", // Cluster state can change from IDLE to UPDATING and risks making the test flaky
"delete_on_create_timeout", // This field is TF specific and not returned by Atlas, so Import can't fill it in.
},
Expand Down
8 changes: 4 additions & 4 deletions internal/serviceapi/databaseuserapi/resource_schema.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 8 additions & 8 deletions tools/codegen/codespec/api_to_provider_spec_mapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"log"
"strings"

"github.com/mongodb/terraform-provider-mongodbatlas/internal/common/autogen/stringcase"
high "github.com/pb33f/libopenapi/datamodel/high/v3"
low "github.com/pb33f/libopenapi/datamodel/low/v3"
"github.com/pb33f/libopenapi/orderedmap"
Expand Down Expand Up @@ -47,12 +46,12 @@ func ToCodeSpecModel(atlasAdminAPISpecFilePath, configPath string, resourceName
for name, resourceConfig := range resourceConfigsToIterate {
log.Printf("[INFO] Generating resource model: %s", name)
// find resource operations, schemas, etc from OAS
oasResource, err := getAPISpecResource(&apiSpec.Model, &resourceConfig, stringcase.SnakeCaseString(name))
oasResource, err := getAPISpecResource(&apiSpec.Model, &resourceConfig, name)
if err != nil {
return nil, fmt.Errorf("unable to get APISpecResource schema: %v", err)
}
// map OAS resource model to CodeSpecModel
resource, err := apiSpecResourceToCodeSpecModel(oasResource, &resourceConfig, stringcase.SnakeCaseString(name))
resource, err := apiSpecResourceToCodeSpecModel(oasResource, &resourceConfig, name)
if err != nil {
return nil, fmt.Errorf("unable to map to code spec model for %s: %w", name, err)
}
Expand Down Expand Up @@ -81,7 +80,7 @@ func validateRequiredOperations(resourceConfigs map[string]config.Resource) erro
return nil
}

func apiSpecResourceToCodeSpecModel(oasResource APISpecResource, resourceConfig *config.Resource, name stringcase.SnakeCaseString) (*Resource, error) {
func apiSpecResourceToCodeSpecModel(oasResource APISpecResource, resourceConfig *config.Resource, name string) (*Resource, error) {
createOp := oasResource.CreateOp
updateOp := oasResource.UpdateOp
readOp := oasResource.ReadOp
Expand Down Expand Up @@ -117,9 +116,10 @@ func apiSpecResourceToCodeSpecModel(oasResource APISpecResource, resourceConfig
operations.VersionHeader = getLatestVersionFromAPISpec(readOp)
}
resource := &Resource{
Name: name,
Schema: schema,
Operations: operations,
Name: name,
PackageName: strings.ReplaceAll(name, "_", ""),
Schema: schema,
Operations: operations,
}

applyTransformationsWithConfigOpts(resourceConfig, resource)
Expand Down Expand Up @@ -234,7 +234,7 @@ func opResponseToAttributes(op *high.Operation) Attributes {
return responseAttributes
}

func getAPISpecResource(spec *high.Document, resourceConfig *config.Resource, name stringcase.SnakeCaseString) (APISpecResource, error) {
func getAPISpecResource(spec *high.Document, resourceConfig *config.Resource, name string) (APISpecResource, error) {
var errResult error
var resourceDeprecationMsg *string

Expand Down
Loading