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

Avoid GraphQL to Go Naming Collision with "ToGoModelName" func #2322

Merged
merged 9 commits into from
Aug 18, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
112 changes: 112 additions & 0 deletions codegen/templates/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ import (
"os"
"path/filepath"
"reflect"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"text/template"
"unicode"

Expand Down Expand Up @@ -202,6 +204,7 @@ func Funcs() template.FuncMap {
"lookupImport": CurrentImports.Lookup,
"go": ToGo,
"goPrivate": ToGoPrivate,
"goModelName": ToGoModelName,
"add": func(a, b int) int {
return a + b
},
Expand Down Expand Up @@ -291,6 +294,115 @@ func Call(p *types.Func) string {
return pkg + p.Name()
}

var (
modelNamesMu sync.Mutex
modelNames = make(map[string]string, 0)
)

func resetModelNames() {
modelNamesMu.Lock()
defer modelNamesMu.Unlock()
modelNames = make(map[string]string, 0)
}

func buildGoModelNameKey(parts []string) string {
const sep = ":"
return strings.Join(parts, sep)
}

func ToGoModelName(parts ...string) string {
modelNamesMu.Lock()
defer modelNamesMu.Unlock()

var (
goNameKey string
partLen int

nameExists = func(n string) bool {
for _, v := range modelNames {
if n == v {
return true
}
}
return false
}

applyToGo = func(parts []string) string {
var out string
for _, p := range parts {
out = fmt.Sprintf("%s%s", out, ToGo(p))
}
return out
}

applyValidGoName = func(parts []string) string {
var out string
for _, p := range parts {
out = fmt.Sprintf("%s%s", out, replaceInvalidCharacters(p))
}
return out
}
)

// build key for this entity
goNameKey = buildGoModelNameKey(parts)

// determine if we've seen this entity before, and reuse if so
if goName, ok := modelNames[goNameKey]; ok {
return goName
}

// attempt first pass

// test first pass
if goName := applyToGo(parts); !nameExists(goName) {
modelNames[goNameKey] = goName
return goName
}

// determine number of parts
partLen = len(parts)

// if there is only 1 part, append incrementing number until no conflict
if partLen == 1 {
base := applyToGo(parts)
for i := 0; ; i++ {
tmp := fmt.Sprintf("%s%d", base, i)
if !nameExists(tmp) {
modelNames[goNameKey] = tmp
return tmp
}
}
}

// best effort "pretty" name
for i := partLen - 1; i >= 1; i-- {
tmp := fmt.Sprintf("%s%s", applyToGo(parts[0:i]), applyValidGoName(parts[i:]))
if !nameExists(tmp) {
modelNames[goNameKey] = tmp
return tmp
}
}

// finally, fallback to just adding an incrementing number
base := applyToGo(parts)
for i := 0; ; i++ {
tmp := fmt.Sprintf("%s%d", base, i)
if !nameExists(tmp) {
modelNames[goNameKey] = tmp
return tmp
}
}
}

var (
goNameRe = regexp.MustCompile("[^a-zA-Z0-9_]")
)

func replaceInvalidCharacters(in string) string {
return goNameRe.ReplaceAllLiteralString(in, "_")
}

func ToGo(name string) string {
if name == "_" {
return "_"
Expand Down
65 changes: 63 additions & 2 deletions codegen/templates/templates_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package templates

import (
"embed"
"fmt"
"os"
"path/filepath"
"testing"
Expand Down Expand Up @@ -74,9 +75,69 @@ func TestToGoPrivate(t *testing.T) {
require.Equal(t, "_", ToGoPrivate("_"))
}

func TestToGoModelName(t *testing.T) {
type aTest struct {
input [][]string
expected []string
}

theTests := []aTest{
{
input: [][]string{{"MyValue"}},
expected: []string{"MyValue"},
},
{
input: [][]string{{"MyValue"}, {"myValue"}},
expected: []string{"MyValue", "MyValue0"},
},
{
input: [][]string{{"MyValue"}, {"YourValue"}},
expected: []string{"MyValue", "YourValue"},
},
{
input: [][]string{{"MyEnumName", "Value"}},
expected: []string{"MyEnumNameValue"},
},
{
input: [][]string{{"MyEnumName", "Value"}, {"MyEnumName", "value"}},
expected: []string{"MyEnumNameValue", "MyEnumNamevalue"},
},
{
input: [][]string{{"MyEnumName", "value"}, {"MyEnumName", "Value"}},
expected: []string{"MyEnumNameValue", "MyEnumNameValue0"},
},
{
input: [][]string{{"MyEnumName", "Value"}, {"MyEnumName", "value"}, {"MyEnumName", "vALue"}, {"MyEnumName", "VALue"}},
expected: []string{"MyEnumNameValue", "MyEnumNamevalue", "MyEnumNameVALue", "MyEnumNameVALue0"},
},
{
input: [][]string{{"MyEnumName", "TitleValue"}, {"MyEnumName", "title_value"}, {"MyEnumName", "title_Value"}, {"MyEnumName", "Title_Value"}},
expected: []string{"MyEnumNameTitleValue", "MyEnumNametitle_value", "MyEnumNametitle_Value", "MyEnumNameTitle_Value"},
},
{
input: [][]string{{"MyEnumName", "TitleValue", "OtherValue"}},
expected: []string{"MyEnumNameTitleValueOtherValue"},
},
{
input: [][]string{{"MyEnumName", "TitleValue", "OtherValue"}, {"MyEnumName", "title_value", "OtherValue"}},
expected: []string{"MyEnumNameTitleValueOtherValue", "MyEnumNametitle_valueOtherValue"},
},
}

for ti, at := range theTests {
resetModelNames()
t.Run(fmt.Sprintf("modelname-%d", ti), func(t *testing.T) {
at := at
for i, n := range at.input {
require.Equal(t, at.expected[i], ToGoModelName(n...))
}
})
}
}

func Test_wordWalker(t *testing.T) {
helper := func(str string) []*wordInfo {
resultList := []*wordInfo{}
resultList := make([]*wordInfo, 0)
wordWalker(str, func(info *wordInfo) {
resultList = append(resultList, info)
})
Expand All @@ -101,7 +162,7 @@ func Test_wordWalker(t *testing.T) {
require.Equal(t, []*wordInfo{{Word: "A"}}, helper("A"))
require.Equal(t, []*wordInfo{{Word: "ID", HasCommonInitial: true, MatchCommonInitial: true}}, helper("ID"))
require.Equal(t, []*wordInfo{{Word: "id", HasCommonInitial: true, MatchCommonInitial: true}}, helper("id"))
require.Equal(t, []*wordInfo{}, helper(""))
require.Equal(t, make([]*wordInfo, 0), helper(""))

require.Equal(t, []*wordInfo{{Word: "Related"}, {Word: "Urls"}}, helper("RelatedUrls"))
require.Equal(t, []*wordInfo{{Word: "ITicket"}}, helper("ITicket"))
Expand Down
Loading