Skip to content

Commit

Permalink
fix(#187): truncate name at the last alphanumeric
Browse files Browse the repository at this point in the history
so the resulting name is compliant with kubernetes convention
  • Loading branch information
kirederik committed Jul 4, 2024
1 parent 3d8e63f commit 2bbd6f2
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/objectutil/name.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package objectutil

import (
"regexp"

"k8s.io/apimachinery/pkg/util/uuid"
)

Expand All @@ -11,7 +13,15 @@ func GenerateObjectName(name string) string {
name = name[0 : maxNameLength-1]
}

for !isAlphanumeric(name[len(name)-1]) {
name = name[0 : len(name)-1]
}

id := uuid.NewUUID()

return name + "-" + string(id[0:5])
}

func isAlphanumeric(s byte) bool {
return regexp.MustCompile(`^[a-zA-Z0-9]*$`).MatchString(string(s))
}
8 changes: 8 additions & 0 deletions lib/objectutil/name_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,12 @@ var _ = Describe("Name Utils", func() {
Expect(name).To(MatchRegexp(`^aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab-\b\w{5}\b$`))
})
})

When("truncating the name would result in an invalid name", func() {
It("truncates it properly", func() {
longName := "kratix-promise-1.-@$#%&*()_+{}|:<>?/\\`~[]"
name := objectutil.GenerateObjectName(longName)
Expect(name).To(MatchRegexp(`^kratix-promise-1-\b\w{5}\b$`))
})
})
})

0 comments on commit 2bbd6f2

Please sign in to comment.