Skip to content

Commit

Permalink
Take care about commonInitialisms in ToCamel
Browse files Browse the repository at this point in the history
  • Loading branch information
vvakame committed Mar 5, 2019
1 parent 1968a7b commit 6ea48ff
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 6 deletions.
33 changes: 28 additions & 5 deletions codegen/templates/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,29 +232,52 @@ func ToCamel(s string) string {
if s == "_" {
return "_"
}
buffer := make([]rune, 0, len(s))
buf := bytes.NewBuffer(make([]byte, 0, len(s)))
upper := true
lastWasUpper := false
var maxCommonInitialismsLen int
for word := range commonInitialisms {
if l := len(word); maxCommonInitialismsLen < l {
maxCommonInitialismsLen = l
}
}

for _, c := range s {
outer:
for i, rs := 0, []rune(s); i < len(rs); i++ {
c := rs[i]
if isDelimiter(c) {
upper = true
continue
}
if !lastWasUpper && unicode.IsUpper(c) {
tail := len(rs) - i
if maxCommonInitialismsLen < tail {
tail = maxCommonInitialismsLen
}
for j := tail; j != 0; j-- {
word := string(rs[i : i+j])
if commonInitialisms[word] {
buf.WriteString(word)
i += j - 1
upper = false
lastWasUpper = false // IDFoo will be IDFoo, not IDfoo
continue outer
}
}

upper = true
}

if upper {
buffer = append(buffer, unicode.ToUpper(c))
buf.WriteRune(unicode.ToUpper(c))
} else {
buffer = append(buffer, unicode.ToLower(c))
buf.WriteRune(unicode.ToLower(c))
}
upper = false
lastWasUpper = unicode.IsUpper(c)
}

return string(buffer)
return buf.String()
}

func ToGo(name string) string {
Expand Down
15 changes: 14 additions & 1 deletion codegen/templates/templates_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,25 @@ import (
"github.com/stretchr/testify/require"
)

func TestToUpper(t *testing.T) {
func TestToCamel(t *testing.T) {
require.Equal(t, "ToCamel", ToCamel("TO_CAMEL"))
require.Equal(t, "ToCamel", ToCamel("to_camel"))
require.Equal(t, "ToCamel", ToCamel("toCamel"))
require.Equal(t, "ToCamel", ToCamel("ToCamel"))
require.Equal(t, "ToCamel", ToCamel("to-camel"))

require.Equal(t, "RelatedURLs", ToCamel("RelatedURLs"))
require.Equal(t, "ImageIDs", ToCamel("ImageIDs"))
require.Equal(t, "FooID", ToCamel("FooID"))
require.Equal(t, "IDFoo", ToCamel("IDFoo"))
require.Equal(t, "FooASCII", ToCamel("FooASCII"))
require.Equal(t, "ASCIIFoo", ToCamel("ASCIIFoo"))
require.Equal(t, "FooUTF8", ToCamel("FooUTF8"))
require.Equal(t, "UTF8Foo", ToCamel("UTF8Foo"))

require.Equal(t, "A", ToCamel("A"))
require.Equal(t, "ID", ToCamel("ID"))
require.Equal(t, "", ToCamel(""))
}

func TestCenter(t *testing.T) {
Expand Down

0 comments on commit 6ea48ff

Please sign in to comment.