Skip to content

Commit

Permalink
EnsureValidName should strip leading or trailing dash
Browse files Browse the repository at this point in the history
EnsureValidName converts all invalid chars to a dash ('-') but
that could leave a leading or trailing dash which is invalid so
just strip a leading or trailing dash.

Signed-off-by: Tom Pantelis <tompantelis@gmail.com>
  • Loading branch information
tpantelis committed Aug 26, 2024
1 parent 129ea41 commit bc8cd35
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
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

0 comments on commit bc8cd35

Please sign in to comment.