kebab_case_converter.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. Copyright 2019 The Vitess Authors.
  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
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package stats
  14. import (
  15. "regexp"
  16. "strings"
  17. "sync"
  18. )
  19. // toKebabCase produces a monitoring compliant name from the
  20. // original. It converts CamelCase to camel-case,
  21. // and CAMEL_CASE to camel-case. For numbers, it
  22. // converts 0.5 to v0_5.
  23. func toKebabCase(name string) (hyphenated string) {
  24. memoizer.Lock()
  25. defer memoizer.Unlock()
  26. if hyphenated = memoizer.memo[name]; hyphenated != "" {
  27. return hyphenated
  28. }
  29. hyphenated = name
  30. for _, converter := range kebabConverters {
  31. hyphenated = converter.re.ReplaceAllString(hyphenated, converter.repl)
  32. }
  33. hyphenated = strings.ToLower(hyphenated)
  34. memoizer.memo[name] = hyphenated
  35. return
  36. }
  37. var kebabConverters = []struct {
  38. re *regexp.Regexp
  39. repl string
  40. }{
  41. // example: LC -> L-C (e.g. CamelCase -> Camel-Case).
  42. {regexp.MustCompile("([a-z])([A-Z])"), "$1-$2"},
  43. // example: CCa -> C-Ca (e.g. CCamel -> C-Camel).
  44. {regexp.MustCompile("([A-Z])([A-Z][a-z])"), "$1-$2"},
  45. {regexp.MustCompile("_"), "-"},
  46. {regexp.MustCompile(`\.`), "_"},
  47. }
  48. var memoizer = memoizerType{
  49. memo: make(map[string]string),
  50. }
  51. type memoizerType struct {
  52. sync.Mutex
  53. memo map[string]string
  54. }