use Trim functions to avoid index out of range panic

This commit is contained in:
Colin Hoglund 2018-02-10 17:41:49 -05:00
parent a8da259d52
commit cfb097f407
2 changed files with 11 additions and 8 deletions

View File

@ -55,7 +55,7 @@ func main() {
} }
if create { if create {
err = ensureRepoExists(svc, getRepoName(repo)) err = ensureRepoExists(svc, trimHostname(repo, registry))
if err != nil { if err != nil {
log.Fatal(fmt.Sprintf("error creating ECR repo: %v", err)) log.Fatal(fmt.Sprintf("error creating ECR repo: %v", err))
} }
@ -75,8 +75,10 @@ func main() {
} }
} }
func getRepoName(repo string) string { func trimHostname(repo, registry string) string {
return strings.SplitN(repo, "/", 2)[1] repo = strings.TrimPrefix(repo, registry)
repo = strings.TrimLeft(repo, "/")
return repo
} }
func ensureRepoExists(svc *ecr.ECR, name string) (err error) { func ensureRepoExists(svc *ecr.ECR, name string) (err error) {

View File

@ -2,16 +2,17 @@ package main
import "testing" import "testing"
func TestGetRepoName(t *testing.T) { func TestTrimHostname(t *testing.T) {
registry := "000000000000.dkr.ecr.us-east-1.amazonaws.com"
// map full repo path to expected repo name // map full repo path to expected repo name
repos := map[string]string{ repos := map[string]string{
"000000000000.dkr.ecr.us-east-1.amazonaws.com/repo": "repo", registry + "/repo": "repo",
"000000000000.dkr.ecr.us-east-1.amazonaws.com/namespace/repo": "namespace/repo", registry + "/namespace/repo": "namespace/repo",
"000000000000.dkr.ecr.us-east-1.amazonaws.com/namespace/namespace/repo": "namespace/namespace/repo", registry + "/namespace/namespace/repo": "namespace/namespace/repo",
} }
for repo, name := range repos { for repo, name := range repos {
splitName := getRepoName(repo) splitName := trimHostname(repo, registry)
if splitName != name { if splitName != name {
t.Errorf("%s is not equal to %s.", splitName, name) t.Errorf("%s is not equal to %s.", splitName, name)
} }