Skip to content

Commit 2f1f83b

Browse files
authored
Merge pull request #503 from abdusco/502-enum-dashes
fix(gen): Improve enum value generation
2 parents 5552e5d + aaaa55d commit 2f1f83b

File tree

2 files changed

+45
-13
lines changed

2 files changed

+45
-13
lines changed

gen/templates.go

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -105,19 +105,7 @@ var templateFunctions = template.FuncMap{
105105
"generateTags": strmangle.GenerateTags,
106106
"generateIgnoreTags": strmangle.GenerateIgnoreTags,
107107
"normalizeType": NormalizeType,
108-
"enumVal": func(val string) string {
109-
var newval strings.Builder
110-
for _, r := range val {
111-
if r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r) {
112-
newval.WriteRune(r)
113-
continue
114-
}
115-
newval.WriteString(fmt.Sprintf("U%x", r))
116-
}
117-
118-
// Title case after doing unicode replacements or they will be stripped
119-
return strmangle.TitleCase(newval.String())
120-
},
108+
"enumVal": enumValToIdentifier,
121109
"columnTagName": func(casing, name, alias string) string {
122110
switch casing {
123111
case "camel":
@@ -149,6 +137,24 @@ var templateFunctions = template.FuncMap{
149137
"relQueryMethodName": relQueryMethodName,
150138
}
151139

140+
func enumValToIdentifier(val string) string {
141+
val = strings.ToLower(val)
142+
val = strings.ReplaceAll(val, "-", "_")
143+
val = strings.ReplaceAll(val, " ", "_")
144+
145+
var newval strings.Builder
146+
for _, r := range val {
147+
if r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r) {
148+
newval.WriteRune(r)
149+
continue
150+
}
151+
newval.WriteString(fmt.Sprintf("U%x", r))
152+
}
153+
154+
// Title case after doing unicode replacements or they will be stripped
155+
return strmangle.TitleCase(newval.String())
156+
}
157+
152158
func relQueryMethodName(tAlias drivers.TableAlias, relAlias string) string {
153159
for _, colAlias := range tAlias.Columns {
154160
// clash with field name

gen/templates_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package gen
2+
3+
import "testing"
4+
5+
func Test_enumValToIdentifier(t *testing.T) {
6+
tests := []struct {
7+
val string
8+
expected string
9+
}{
10+
{"in_progress", "InProgress"},
11+
{"in-progress", "InProgress"},
12+
{"in progress", "InProgress"},
13+
{"IN_PROGRESS", "InProgress"},
14+
{"in___-__progress", "InProgress"},
15+
{" in progress ", "InProgress"},
16+
// This is OK, because enum values are prefixed with the type name, e.g. TaskStatus1InProgress
17+
{"1-in-progress", "1InProgress"},
18+
}
19+
for _, tt := range tests {
20+
t.Run(tt.val, func(t *testing.T) {
21+
if actual := enumValToIdentifier(tt.val); actual != tt.expected {
22+
t.Errorf("enumValToIdentifier(%q) = %q; want %q", tt.val, actual, tt.expected)
23+
}
24+
})
25+
}
26+
}

0 commit comments

Comments
 (0)