Skip to content

Commit

Permalink
SplitByKnownRegistries: handle case where prefix == full path
Browse files Browse the repository at this point in the history
Also add test case.

See for full context kubernetes-sigs#188
  • Loading branch information
Linus Arver committed Mar 5, 2020
1 parent e7ccb02 commit e348bb6
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 3 deletions.
14 changes: 11 additions & 3 deletions lib/dockerregistry/inventory.go
Original file line number Diff line number Diff line change
Expand Up @@ -1489,11 +1489,19 @@ func SplitByKnownRegistries(
if strings.HasPrefix(string(r), string(rc.Name)) {
trimmed := strings.TrimPrefix(string(r), string(rc.Name))

// Remove leading "/" character, if any.
if trimmed[0] == '/' {
if trimmed == "" {
// The unparsed full image path `r` and rc.Name is the same ---
// this happens for images pushed to the root directory. Just
// get everything past the last '/' seen in `r` to get the image
// name.
i := strings.LastIndex(string(r), "/")
return rc.Name[:i], ImageName(string(r)[i+1:]), nil
} else if trimmed[0] == '/' {
// Remove leading "/" character, if any.
return rc.Name, ImageName(trimmed[1:]), nil
} else {
return rc.Name, ImageName(trimmed), nil
}
return rc.Name, ImageName(trimmed), nil
}
}

Expand Down
48 changes: 48 additions & 0 deletions lib/dockerregistry/inventory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -859,6 +859,54 @@ func TestSplitRegistryImagePath(t *testing.T) {
}
}

func TestSplitByKnownRegistries(t *testing.T) {
knownRegistryNames := []RegistryName{
// See
// https://github.com/kubernetes-sigs/k8s-container-image-promoter/issues/188.
`us.gcr.io/k8s-artifacts-prod/kube-state-metrics`,
}
knownRegistryContexts := make([]RegistryContext, 0)
for _, knownRegistryName := range knownRegistryNames {
rc := RegistryContext{}
rc.Name = knownRegistryName
knownRegistryContexts = append(knownRegistryContexts, rc)
}

var tests = []struct {
name string
input RegistryName
expectedRegistryName RegistryName
expectedImageName ImageName
expectedErr error
}{
{
`image at toplevel root path`,
`us.gcr.io/k8s-artifacts-prod/kube-state-metrics`,
`us.gcr.io/k8s-artifacts-prod`,
`kube-state-metrics`,
nil,
},
}
for _, test := range tests {
rootReg, imageName, err := SplitByKnownRegistries(test.input, knownRegistryContexts)
eqErr := checkEqual(rootReg, test.expectedRegistryName)
checkError(
t,
eqErr,
fmt.Sprintf("Test: `%v' failure (registry name mismatch)\n", test.input))
eqErr = checkEqual(imageName, test.expectedImageName)
checkError(
t,
eqErr,
fmt.Sprintf("Test: `%v' failure (image name mismatch)\n", test.input))
eqErr = checkEqual(err, test.expectedErr)
checkError(
t,
eqErr,
fmt.Sprintf("Test: `%v' failure (error mismatch)\n", test.input))
}
}

func TestCommandGeneration(t *testing.T) {
destRC := RegistryContext{
Name: "gcr.io/foo",
Expand Down

0 comments on commit e348bb6

Please sign in to comment.