-
Notifications
You must be signed in to change notification settings - Fork 87
/
name.go
70 lines (58 loc) · 1.67 KB
/
name.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
63
64
65
66
67
68
69
70
package name
import (
"crypto/md5"
"crypto/sha256"
"encoding/hex"
"fmt"
"strings"
)
func GuessPluralName(name string) string {
if name == "" {
return name
}
if strings.EqualFold(name, "Endpoints") {
return name
}
if suffix(name, "s") || suffix(name, "ch") || suffix(name, "x") || suffix(name, "sh") {
return name + "es"
}
if suffix(name, "f") || suffix(name, "fe") {
return name + "ves"
}
if suffix(name, "y") && len(name) > 2 && !strings.ContainsAny(name[len(name)-2:len(name)-1], "[aeiou]") {
return name[0:len(name)-1] + "ies"
}
return name + "s"
}
func suffix(str, end string) bool {
return strings.HasSuffix(str, end)
}
// Limit the length of a string to count characters. If the string's length is
// greater or equal to count, it will be truncated and a hash will be appended
// to the end.
// Warning: runtime error for count <= 5: https://go.dev/play/p/UAbpZIOvIYo
func Limit(s string, count int) string {
if len(s) < count {
return s
}
return fmt.Sprintf("%s-%s", s[:count-6], Hex(s, 5))
}
func Hex(s string, length int) string {
h := md5.Sum([]byte(s))
d := hex.EncodeToString(h[:])
return d[:length]
}
func SafeConcatName(name ...string) string {
fullPath := strings.Join(name, "-")
if len(fullPath) < 64 {
return fullPath
}
digest := sha256.Sum256([]byte(fullPath))
// since we cut the string in the middle, the last char may not be compatible with what is expected in k8s
// we are checking and if necessary removing the last char
c := fullPath[56]
if 'a' <= c && c <= 'z' || '0' <= c && c <= '9' {
return fullPath[0:57] + "-" + hex.EncodeToString(digest[0:])[0:5]
}
return fullPath[0:56] + "-" + hex.EncodeToString(digest[0:])[0:6]
}