diff --git a/internal/pathutil/pathutil.go b/internal/pathutil/pathutil.go index b6724263..b9fc7bf7 100644 --- a/internal/pathutil/pathutil.go +++ b/internal/pathutil/pathutil.go @@ -19,6 +19,8 @@ import ( "strings" "github.com/pkg/errors" + + "sigs.k8s.io/krew/pkg/constants" ) // IsSubPath checks if the extending path is an extension of the basePath, it will return the extending path @@ -42,3 +44,13 @@ func ReplaceBase(path, old, replacement string) (string, error) { } return filepath.Join(replacement, extendingPath), nil } + +// CanonicalPluginName resolves a plugin's index and name from input string. +// If an index is not specified, the default index name is assumed. +func CanonicalPluginName(in string) (string, string) { + if strings.Count(in, "/") == 0 { + return constants.DefaultIndexName, in + } + p := strings.SplitN(in, "/", 2) + return p[0], p[1] +} diff --git a/internal/pathutil/pathutil_test.go b/internal/pathutil/pathutil_test.go index 10c350ce..47f70293 100644 --- a/internal/pathutil/pathutil_test.go +++ b/internal/pathutil/pathutil_test.go @@ -184,3 +184,27 @@ func TestReplaceBase(t *testing.T) { }) } } + +func TestCanonicalPluginName(t *testing.T) { + tests := []struct { + in string + wantIndex string + wantName string + }{ + {"foo", "default", "foo"}, + {"", "default", ""}, // despite unsupported + {"a/b", "a", "b"}, + {"a/b/c", "a", "b/c"}, // despite unsupported + } + for _, tt := range tests { + t.Run(tt.in, func(t *testing.T) { + gotIndex, gotName := CanonicalPluginName(tt.in) + if gotIndex != tt.wantIndex { + t.Errorf("CanonicalPluginName(%q) gotIndex = %q, want = %q", tt.in, gotIndex, tt.wantIndex) + } + if gotName != tt.wantName { + t.Errorf("CanonicalPluginName(%q) gotName = %q, want = %q", tt.in, gotName, tt.wantName) + } + }) + } +} diff --git a/pkg/constants/constants.go b/pkg/constants/constants.go index bfa8cd8d..04dad804 100644 --- a/pkg/constants/constants.go +++ b/pkg/constants/constants.go @@ -22,4 +22,6 @@ const ( // IndexURI points to the upstream index. IndexURI = "https://github.com/kubernetes-sigs/krew-index.git" + // DefaultIndexName is a magic string that's used for a plugin name specified without an index. + DefaultIndexName = "default" )