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