Improve name formatting logic and add more tests

Signed-off-by: Carlisia <carlisia@vmware.com>
This commit is contained in:
Carlisia
2020-12-14 18:32:37 -08:00
parent 2de7c7924c
commit 63301213bd
2 changed files with 35 additions and 9 deletions
+10 -9
View File
@@ -44,29 +44,30 @@ func ForPluginContainer(image string, pullPolicy corev1api.PullPolicy) *Containe
}
// getName returns the 'name' component of a docker
// image that includes its reposiroty name, and transforms the combined
// image that includes the entire string except the registry name, and transforms the combined
// string into a DNS-1123 compatible name.
func getName(image string) string {
slashIndex := strings.Index(image, "/")
slashCount := strings.Count(image[slashIndex:], "/")
colonIndex := strings.LastIndex(image, ":")
slashCount := 0
if slashIndex >= 0 {
slashCount = strings.Count(image[slashIndex:], "/")
}
// this removes the registry name when there is one, but keeps the repository name
start := 0
if slashCount == 1 {
start = 0
} else {
// this will be the first character after the first found slash
if slashCount > 1 || slashIndex == 0 {
// always start after the first slash when there is a registry name
// or if the string starts with a slash.
start = slashIndex + 1
}
// this removes the tag
colonIndex := strings.LastIndex(image, ":")
end := len(image)
if colonIndex > 0 {
end = colonIndex
}
return strings.Replace(image[start:end], "/", "-", 1) // this makes it DNS-1123 compatible
return strings.Replace(image[start:end], "/", "-", -1) // this makes it DNS-1123 compatible
}
// Result returns the built Container.
+25
View File
@@ -52,6 +52,31 @@ func TestGetName(t *testing.T) {
image: "mycustomregistry.io:8080/my-repo/my-image:latest",
expected: "my-repo-my-image",
},
{
name: "image name with no / in it",
image: "my-image",
expected: "my-image",
},
{
name: "image name starting with / in it",
image: "/my-image",
expected: "my-image",
},
{
name: "image name with repo starting with a / as first char",
image: "/my-repo/my-image",
expected: "my-repo-my-image",
},
{
name: "image name with registry hostname, etoomany slashes, without tag",
image: "gcr.io/my-repo/mystery/another/my-image",
expected: "my-repo-mystery-another-my-image",
},
{
name: "image name with registry hostname starting with a / will include the registry name ¯\\_(ツ)_/¯",
image: "/gcr.io/my-repo/mystery/another/my-image",
expected: "gcr.io-my-repo-mystery-another-my-image",
},
}
for _, test := range tests {