Skip to content

Commit

Permalink
avoid joining dot and dash at generated fixed names (#2800)
Browse files Browse the repository at this point in the history
  • Loading branch information
Pablo Mercado authored Mar 25, 2020
1 parent 54e57b5 commit 93707e9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
21 changes: 13 additions & 8 deletions pkg/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,15 +116,20 @@ func ToDNS1123Subdomain(name string) string {
// The name's length will be short enough to be valid for K8s Services.
func GenerateFixedName(owner metav1.Object, prefix string) string {
uid := string(owner.GetUID())

pl := validation.DNS1123LabelMaxLength - len(uid)
if pl < len(prefix) {
prefix = prefix[:pl]
}

// Make sure the UID is separated from the prefix by a leading dash.
if !strings.HasPrefix(uid, "-") {
if !strings.HasSuffix(prefix, "-") && !strings.HasPrefix(uid, "-") {
uid = "-" + uid
if len(prefix) == pl {
prefix = prefix[:len(prefix)-1]
}
}
// Trim any trailing dash from the prefix as the UID is now prepended with the dash.
prefix = strings.TrimSuffix(prefix, "-")
pl := validation.DNS1123LabelMaxLength - len(uid)
if pl > len(prefix) {
pl = len(prefix)
}
return prefix[:pl] + uid

// A dot must be followed by [a-z0-9] to be DNS1123 compliant. Make sure we are not joining a dot and a dash.
return strings.TrimSuffix(prefix, ".") + uid
}
10 changes: 10 additions & 0 deletions pkg/utils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,16 @@ func TestGenerateFixedName(t *testing.T) {
prefix: "default-text-extractor-",
expected: "default-text-extractor-2d6c09e1-aa54-11e9-9d6a-42010a8a0062",
},
"dot in prefix": {
uid: "2d6c09e1-aa54-11e9-9d6a-42010a8a0062",
prefix: "default-text-extractor.",
expected: "default-text-extractor-2d6c09e1-aa54-11e9-9d6a-42010a8a0062",
},
"too long and dot in prefix": {
uid: "2d6c09e1-aa54-11e9-9d6a-42010a8a0062",
prefix: "this-is-an-extremely-long.prefix-and-it-will-be-cut-at-the-dot",
expected: "this-is-an-extremely-long-2d6c09e1-aa54-11e9-9d6a-42010a8a0062",
},
}
for n, tc := range testCases {
t.Run(n, func(t *testing.T) {
Expand Down

0 comments on commit 93707e9

Please sign in to comment.