From cfb097f4078f7dc5e5d30c247299f7c6d8f0170e Mon Sep 17 00:00:00 2001 From: Colin Hoglund Date: Sat, 10 Feb 2018 17:41:49 -0500 Subject: [PATCH] use Trim functions to avoid index out of range panic --- cmd/drone-docker-ecr/main.go | 8 +++++--- cmd/drone-docker-ecr/main_test.go | 11 ++++++----- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/cmd/drone-docker-ecr/main.go b/cmd/drone-docker-ecr/main.go index 35b86b4..a090e6c 100644 --- a/cmd/drone-docker-ecr/main.go +++ b/cmd/drone-docker-ecr/main.go @@ -55,7 +55,7 @@ func main() { } if create { - err = ensureRepoExists(svc, getRepoName(repo)) + err = ensureRepoExists(svc, trimHostname(repo, registry)) if err != nil { log.Fatal(fmt.Sprintf("error creating ECR repo: %v", err)) } @@ -75,8 +75,10 @@ func main() { } } -func getRepoName(repo string) string { - return strings.SplitN(repo, "/", 2)[1] +func trimHostname(repo, registry string) string { + repo = strings.TrimPrefix(repo, registry) + repo = strings.TrimLeft(repo, "/") + return repo } func ensureRepoExists(svc *ecr.ECR, name string) (err error) { diff --git a/cmd/drone-docker-ecr/main_test.go b/cmd/drone-docker-ecr/main_test.go index fed5abc..5c50ba5 100644 --- a/cmd/drone-docker-ecr/main_test.go +++ b/cmd/drone-docker-ecr/main_test.go @@ -2,16 +2,17 @@ package main 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 repos := map[string]string{ - "000000000000.dkr.ecr.us-east-1.amazonaws.com/repo": "repo", - "000000000000.dkr.ecr.us-east-1.amazonaws.com/namespace/repo": "namespace/repo", - "000000000000.dkr.ecr.us-east-1.amazonaws.com/namespace/namespace/repo": "namespace/namespace/repo", + registry + "/repo": "repo", + registry + "/namespace/repo": "namespace/repo", + registry + "/namespace/namespace/repo": "namespace/namespace/repo", } for repo, name := range repos { - splitName := getRepoName(repo) + splitName := trimHostname(repo, registry) if splitName != name { t.Errorf("%s is not equal to %s.", splitName, name) }