-
Notifications
You must be signed in to change notification settings - Fork 1
/
names.go
53 lines (48 loc) · 1.08 KB
/
names.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
package kube
import (
"bytes"
"strings"
)
// ToValidName converts the given string into a valid Kubernetes resource name
func ToValidName(name string) string {
return toValidName(name, false)
}
// ToValidNameWithDots converts the given string into a valid Kubernetes resource name
func ToValidNameWithDots(name string) string {
return toValidName(name, true)
}
func toValidName(name string, allowDots bool) string {
var buffer bytes.Buffer
first := true
lastCharDash := false
lower := strings.ToLower(name)
for _, ch := range lower {
if first {
// strip non letters at start
if ch >= 'a' && ch <= 'z' {
buffer.WriteRune(ch)
first = false
}
} else {
if !allowDots && ch == '.' {
ch = '-'
}
if !(ch >= 'a' && ch <= 'z') && !(ch >= '0' && ch <= '9') && ch != '-' && ch != '.' {
ch = '-'
}
if ch != '-' || !lastCharDash {
buffer.WriteRune(ch)
}
lastCharDash = ch == '-'
}
}
answer := buffer.String()
for {
if strings.HasSuffix(answer, "-") {
answer = strings.TrimSuffix(answer, "-")
} else {
break
}
}
return answer
}