-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
util.go
62 lines (55 loc) · 1.17 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package log
import (
"bytes"
"strings"
)
func uniqueString(s []string) []string {
unique := make(map[string]bool, len(s))
us := make([]string, 0, len(s))
for _, elem := range s {
if len(elem) != 0 {
if !unique[elem] {
us = append(us, elem)
unique[elem] = true
}
}
}
return us
}
func sanitizeLabelKey(key string, isPrefix bool) string {
if len(key) == 0 {
return key
}
key = strings.TrimSpace(key)
if len(key) == 0 {
return key
}
if isPrefix && key[0] >= '0' && key[0] <= '9' {
key = "_" + key
}
return strings.Map(func(r rune) rune {
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || r == '_' || (r >= '0' && r <= '9') {
return r
}
return '_'
}, key)
}
// appendSanitize appends the sanitized key to the slice.
func appendSanitized(to, key []byte) []byte {
if len(key) == 0 {
return to
}
key = bytes.TrimSpace(key)
if len(to) == 0 && key[0] >= '0' && key[0] <= '9' {
to = append(to, '_')
}
// range over rune
for _, r := range string(key) {
if !((r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || r == '_' || (r >= '0' && r <= '9')) {
to = append(to, '_')
continue
}
to = append(to, byte(r))
}
return to
}