github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/pkg/normalizer/normalizer.go (about) 1 /* 2 * Copyright 2020 The Compass 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 normalizer 18 19 import ( 20 "regexp" 21 "strings" 22 ) 23 24 // defaultNormalizationPrefix is a fixed string used as prefix during default normalization 25 const defaultNormalizationPrefix = "mp-" 26 27 // DefaultNormalizator missing godoc 28 type DefaultNormalizator struct{} 29 30 // Normalize is the default normalization function used as normalization function; 31 // It attempts to validate if the input is already normalized so it doesn't apply normalization again. 32 func (dn *DefaultNormalizator) Normalize(name string) string { 33 if dn.isNormalized(name) { 34 return name 35 } 36 37 prefixedName := defaultNormalizationPrefix + name 38 return dn.normalize(prefixedName) 39 } 40 41 func (dn *DefaultNormalizator) normalize(name string) string { 42 normalizedName := strings.ToLower(name) 43 normalizedName = regexp.MustCompile("[^-a-z0-9]").ReplaceAllString(normalizedName, "-") 44 normalizedName = regexp.MustCompile("-{2,}").ReplaceAllString(normalizedName, "-") 45 normalizedName = regexp.MustCompile("-$").ReplaceAllString(normalizedName, "") 46 47 return normalizedName 48 } 49 50 func (dn *DefaultNormalizator) isNormalized(name string) bool { 51 if !strings.HasPrefix(name, defaultNormalizationPrefix) { 52 return false 53 } 54 normalizedName := dn.normalize(name) 55 return name == normalizedName 56 }