diff --git a/codegen/templates/templates.go b/codegen/templates/templates.go index 8522824e5c..74085e0fd3 100644 --- a/codegen/templates/templates.go +++ b/codegen/templates/templates.go @@ -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 { diff --git a/codegen/templates/templates_test.go b/codegen/templates/templates_test.go index 31f518b4bc..5debc545ab 100644 --- a/codegen/templates/templates_test.go +++ b/codegen/templates/templates_test.go @@ -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) {