github.com/googleapis/api-linter@v1.65.2/rules/internal/utils/casing.go (about)

     1  // Copyright 2023 Google LLC
     2  //
     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  //
     7  //     https://www.apache.org/licenses/LICENSE-2.0
     8  //
     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.
    14  
    15  package utils
    16  
    17  // ToUpperCamelCase returns the UpperCamelCase of a string, including removing
    18  // delimiters (_,-,., ) and using them to denote a new word.
    19  func ToUpperCamelCase(s string) string {
    20  	return toCamelCase(s, true, false)
    21  }
    22  
    23  // ToLowerCamelCase returns the lowerCamelCase of a string, including removing
    24  // delimiters (_,-,., ) and using them to denote a new word.
    25  func ToLowerCamelCase(s string) string {
    26  	return toCamelCase(s, false, true)
    27  }
    28  
    29  func toCamelCase(s string, makeNextUpper bool, makeNextLower bool) string {
    30  	asLower := make([]rune, 0, len(s))
    31  	for _, r := range s {
    32  		if isLower(r) {
    33  			if makeNextUpper {
    34  				r = r & '_' // make uppercase
    35  			}
    36  			asLower = append(asLower, r)
    37  		} else if isUpper(r) {
    38  			if makeNextLower {
    39  				r = r | ' ' // make lowercase
    40  				makeNextLower = false
    41  			}
    42  			asLower = append(asLower, r)
    43  		} else if isNumber(r) {
    44  			asLower = append(asLower, r)
    45  		}
    46  		makeNextUpper = false
    47  		makeNextLower = false
    48  
    49  		if r == '-' || r == '_' || r == ' ' || r == '.' {
    50  			// handle snake case scenarios, which generally indicates
    51  			// a delimited word.
    52  			makeNextUpper = true
    53  		}
    54  	}
    55  	return string(asLower)
    56  }
    57  
    58  func isUpper(r rune) bool {
    59  	return ('A' <= r && r <= 'Z')
    60  }
    61  
    62  func isNumber(r rune) bool {
    63  	return ('0' <= r && r <= '9')
    64  }
    65  
    66  func isLower(r rune) bool {
    67  	return ('a' <= r && r <= 'z')
    68  }