github.com/kubeshop/testkube@v1.17.23/pkg/utils/text/slug.go (about) 1 package text 2 3 import ( 4 "regexp" 5 "strings" 6 "unicode" 7 8 "golang.org/x/text/unicode/norm" 9 ) 10 11 var lat = []*unicode.RangeTable{unicode.Letter, unicode.Number} 12 var nop = []*unicode.RangeTable{unicode.Mark, unicode.Sk, unicode.Lm} 13 14 // Slug replaces each run of characters which are not unicode letters or 15 // numbers with a single hyphen, except for leading or trailing runs. Letters 16 // will be stripped of diacritical marks and lowercased. Letter or number 17 // codepoints that do not have combining marks or a lower-cased variant will 18 // be passed through unaltered. 19 func Slug(s string) string { 20 buf := make([]rune, 0, len(s)) 21 dash := false 22 for _, r := range norm.NFKD.String(s) { 23 switch { 24 // unicode 'letters' like mandarin characters pass through 25 case unicode.IsOneOf(lat, r): 26 buf = append(buf, unicode.ToLower(r)) 27 dash = true 28 case unicode.IsOneOf(nop, r): 29 // skip 30 case dash: 31 buf = append(buf, '-') 32 dash = false 33 } 34 } 35 if i := len(buf) - 1; i >= 0 && buf[i] == '-' { 36 buf = buf[:i] 37 } 38 39 return strings.Replace(string(buf), "ł", "l", -1) 40 } 41 42 var eventNameFilter = regexp.MustCompile("[^a-zA-Z0-9]+") 43 44 func GAEventName(in string) string { 45 filtered := eventNameFilter.ReplaceAllString(in, "_") 46 filtered = strings.TrimLeft(filtered, "_") 47 if len(filtered) > 40 { 48 return filtered[:40] 49 } 50 return filtered 51 }