From bbd794887454ee3a60866f7912fc5289b474f0f9 Mon Sep 17 00:00:00 2001 From: Tomas <40318863+tomasmik@users.noreply.github.com> Date: Mon, 1 Jul 2024 15:46:35 +0300 Subject: [PATCH] Improve repository name detection (#233) --- internal/cmd/stack/open_command.go | 21 +++++++++++++++++---- internal/cmd/stack/open_command_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 4 deletions(-) create mode 100644 internal/cmd/stack/open_command_test.go diff --git a/internal/cmd/stack/open_command.go b/internal/cmd/stack/open_command.go index 5d0df5b..3a393c0 100644 --- a/internal/cmd/stack/open_command.go +++ b/internal/cmd/stack/open_command.go @@ -85,11 +85,24 @@ func getRepositoryName() (string, error) { return "", err } - result := strings.SplitN(string(out), ":", 2) - if len(result) != 2 { - return "", errors.New("could not parse result") + return cleanupRepositoryString(string(out)) +} + +func cleanupRepositoryString(s string) (string, error) { + var userRepo string + + switch { + case strings.HasPrefix(s, "https://"): + userRepo = strings.TrimPrefix(s, "https://") + userRepo = userRepo[strings.Index(userRepo, "/")+1:] + case strings.HasPrefix(s, "git@"): + userRepo = strings.TrimPrefix(s, "git@") + userRepo = userRepo[strings.Index(userRepo, ":")+1:] + default: + return "", fmt.Errorf("unsupported repository string: %s", s) } - return strings.TrimSuffix(strings.TrimSpace(result[1]), ".git"), nil + + return strings.TrimSuffix(strings.TrimSpace(userRepo), ".git"), nil } func getGitCurrentBranch() (string, error) { diff --git a/internal/cmd/stack/open_command_test.go b/internal/cmd/stack/open_command_test.go new file mode 100644 index 0000000..c3a3058 --- /dev/null +++ b/internal/cmd/stack/open_command_test.go @@ -0,0 +1,24 @@ +package stack + +import "testing" + +func Test_cleanupRepositoryString(t *testing.T) { + tests := []struct { + input string + expected string + }{ + {"https://github.com/username/tftest.git", "username/tftest"}, + {"git@github.com:username/spacelift-local.git", "username/spacelift-local"}, + {"https://gitlab.com/username/project.git", "username/project"}, + {"git@gitlab.com:username/project.git", "username/project"}, + } + + for _, test := range tests { + t.Run(test.input, func(t *testing.T) { + result, _ := cleanupRepositoryString(test.input) + if result != test.expected { + t.Errorf("expected %q, got %q", test.expected, result) + } + }) + } +}