github.com/XiaoMi/Gaea@v1.2.5/stats/kebab_case_converter.go (about) 1 /* 2 Copyright 2018 The Vitess Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package stats 18 19 import ( 20 "regexp" 21 "strings" 22 "sync" 23 ) 24 25 // toKebabCase produces a monitoring compliant name from the 26 // original. It converts CamelCase to camel-case, 27 // and CAMEL_CASE to camel-case. For numbers, it 28 // converts 0.5 to v0_5. 29 func toKebabCase(name string) (hyphenated string) { 30 memoizer.Lock() 31 defer memoizer.Unlock() 32 if hyphenated = memoizer.memo[name]; hyphenated != "" { 33 return hyphenated 34 } 35 hyphenated = name 36 for _, converter := range kebabConverters { 37 hyphenated = converter.re.ReplaceAllString(hyphenated, converter.repl) 38 } 39 hyphenated = strings.ToLower(hyphenated) 40 memoizer.memo[name] = hyphenated 41 return 42 } 43 44 var kebabConverters = []struct { 45 re *regexp.Regexp 46 repl string 47 }{ 48 // example: LC -> L-C (e.g. CamelCase -> Camel-Case). 49 {regexp.MustCompile("([a-z])([A-Z])"), "$1-$2"}, 50 // example: CCa -> C-Ca (e.g. CCamel -> C-Camel). 51 {regexp.MustCompile("([A-Z])([A-Z][a-z])"), "$1-$2"}, 52 {regexp.MustCompile("_"), "-"}, 53 {regexp.MustCompile("\\."), "_"}, 54 } 55 56 var memoizer = memoizerType{ 57 memo: make(map[string]string), 58 } 59 60 type memoizerType struct { 61 sync.Mutex 62 memo map[string]string 63 }