snake_case_converter.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. )
  18. // GetSnakeName calls toSnakeName on the passed in string. It produces
  19. // a snake-cased name from the provided camel-cased name.
  20. // It memoizes the transformation and returns the stored result if available.
  21. func GetSnakeName(name string) string {
  22. return toSnakeCase(name)
  23. }
  24. // toSnakeCase produces a monitoring compliant name from the original.
  25. // For systems (like Prometheus) that ask for snake-case names.
  26. // It converts CamelCase to camel_case, and CAMEL_CASE to camel_case.
  27. // For numbers, it converts 0.5 to v0_5.
  28. func toSnakeCase(name string) (hyphenated string) {
  29. snakeMemoizer.Lock()
  30. defer snakeMemoizer.Unlock()
  31. if hyphenated = snakeMemoizer.memo[name]; hyphenated != "" {
  32. return hyphenated
  33. }
  34. hyphenated = name
  35. for _, converter := range snakeConverters {
  36. hyphenated = converter.re.ReplaceAllString(hyphenated, converter.repl)
  37. }
  38. hyphenated = strings.ToLower(hyphenated)
  39. snakeMemoizer.memo[name] = hyphenated
  40. return
  41. }
  42. var snakeConverters = []struct {
  43. re *regexp.Regexp
  44. repl string
  45. }{
  46. // example: LC -> L_C (e.g. CamelCase -> Camel_Case).
  47. {regexp.MustCompile("([a-z])([A-Z])"), "${1}_${2}"},
  48. // example: CCa -> C_Ca (e.g. CCamel -> C_Camel).
  49. {regexp.MustCompile("([A-Z])([A-Z][a-z])"), "${1}_${2}"},
  50. {regexp.MustCompile(`\.`), "_"},
  51. {regexp.MustCompile("-"), "_"},
  52. }
  53. var snakeMemoizer = memoizerType{
  54. memo: make(map[string]string),
  55. }