Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

EnsureValidName should strip leading or trailing dash #979

Merged
merged 1 commit into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion pkg/resource/resource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,19 @@ var _ = Describe("EnsureValidName", func() {
})

When("the string has non-alphanumeric letters", func() {
It("should convert them approriately", func() {
It("should convert them appropriately", func() {
Expect(resource.EnsureValidName("no-!@*()#$-chars")).To(Equal("no---------chars"))
})
})

When("the string starts or ends with an invalid char", func() {
It("should strip the char", func() {
Expect(resource.EnsureValidName("-abc")).To(Equal("abc"))
Expect(resource.EnsureValidName("abc-")).To(Equal("abc"))
Expect(resource.EnsureValidName("-abc-")).To(Equal("abc"))
Expect(resource.EnsureValidName("%abc*")).To(Equal("abc"))
})
})
})

var _ = Describe("TrimManagedFields", func() {
Expand Down
4 changes: 3 additions & 1 deletion pkg/resource/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,14 +111,16 @@ func MustToMeta(obj interface{}) metav1.Object {
func EnsureValidName(name string) string {
// K8s only allows lower case alphanumeric characters, '-' or '.'. Regex used for validation is
// '[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*'
return strings.Map(func(c rune) rune {
name = strings.Map(func(c rune) rune {
c = unicode.ToLower(c)
if !unicode.IsDigit(c) && !unicode.IsLower(c) && c != '-' && c != '.' {
return '-'
}

return c
}, name)

return strings.Trim(name, "-")
}

func ToJSON(o any) string {
Expand Down
Loading