1 // Copyright (c) 2018 Cisco and/or its affiliates.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at:
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
22 // commonInitialisms is a set of common initialisms that need to stay in upper case.
23 var commonInitialisms = map[string]bool{
26 //"ASCII": true, // there are only two use cases for ASCII which already have initialism before and after
68 // specialInitialisms is a set of special initialisms that need part to stay in upper case.
69 var specialInitialisms = map[string]string{
75 func usesInitialism(s string) string {
76 if u := strings.ToUpper(s); commonInitialisms[u] {
78 } else if su, ok := specialInitialisms[u]; ok {
84 // camelCaseName returns correct name identifier (camelCase).
85 func camelCaseName(name string) (should string) {
86 name = strings.Title(name)
88 // Fast path for simple cases: "_" and all lowercase.
93 for _, r := range name {
94 if !unicode.IsLower(r) {
103 // Split camelCase at any lower->upper transition, and split on underscores.
104 // Check each word for common initialisms.
105 runes := []rune(name)
106 w, i := 0, 0 // index of start of word, scan
107 for i+1 <= len(runes) {
108 eow := false // whether we hit the end of a word
109 if i+1 == len(runes) {
111 } else if runes[i+1] == '_' {
112 // underscore; shift the remainder forward over any run of underscores
115 for i+n+1 < len(runes) && runes[i+n+1] == '_' {
119 // Leave at most one underscore if the underscore is between two digits
120 if i+n+1 < len(runes) && unicode.IsDigit(runes[i]) && unicode.IsDigit(runes[i+n+1]) {
124 copy(runes[i+1:], runes[i+n+1:])
125 runes = runes[:len(runes)-n]
126 } else if unicode.IsLower(runes[i]) && !unicode.IsLower(runes[i+1]) {
136 word := string(runes[w:i])
137 if u := usesInitialism(word); u != "" {
138 // Keep consistent case, which is lowercase only at the start.
139 if w == 0 && unicode.IsLower(runes[w]) {
140 u = strings.ToLower(u)
142 // All the common initialisms are ASCII,
143 // so we can replace the bytes exactly.
144 copy(runes[w:], []rune(u))
145 } else if w > 0 && strings.ToLower(word) == word {
146 // already all lowercase, and not the first word, so uppercase the first character.
147 runes[w] = unicode.ToUpper(runes[w])