Skip to content

Commit

Permalink
Canonicalize suggested name
Browse files Browse the repository at this point in the history
  • Loading branch information
corneliusweig committed Sep 11, 2019
1 parent eae213d commit 3693b15
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
14 changes: 13 additions & 1 deletion pkg/skaffold/initializer/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strings"

Expand Down Expand Up @@ -430,7 +431,18 @@ func suggestConfigName() (string, error) {
return "", nil
}

return base, nil
return canonicalizeName(base), nil
}

// canonicalizeName converts a given string to a valid k8s name string.
// See https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names for details
func canonicalizeName(name string) string {
forbidden := regexp.MustCompile(`[^-.a-z]+`)
canonicalized := forbidden.ReplaceAllString(strings.ToLower(name), "-")
if len(canonicalized) <= 253 {
return canonicalized
}
return canonicalized[:253]
}

func printAnalyzeJSONNoJib(out io.Writer, skipBuild bool, pairs []builderImagePair, unresolvedBuilders []InitBuilder, unresolvedImages []string) error {
Expand Down
41 changes: 41 additions & 0 deletions pkg/skaffold/initializer/init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -498,3 +498,44 @@ func TestProcessCliArtifacts(t *testing.T) {
})
}
}

func Test_canonicalizeName(t *testing.T) {
const length253 = "aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa-aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa-aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaa"
tests := []struct {
in, out string
}{
{
in: "abc def",
out: "abc-def",
},
{
in: "abc def",
out: "abc-def",
},
{
in: "abc...def",
out: "abc...def",
},
{
in: "abc---def",
out: "abc---def",
},
{
in: "aBc DeF",
out: "abc-def",
},
{
in: length253 + "XXXXXXX",
out: length253,
},
}

for _, test := range tests {
t.Run(test.in, func(t *testing.T) {
actual := canonicalizeName(test.in)
if actual != test.out {
t.Errorf("%s: expected %s, found %s", test.in, test.out, actual)
}
})
}
}

0 comments on commit 3693b15

Please sign in to comment.