From 2cacb4c9d315430abd62d03e155fefae42ba9e1a Mon Sep 17 00:00:00 2001 From: kinjelom Date: Mon, 26 Aug 2024 07:09:11 +0200 Subject: [PATCH] keystore.List fix + tests --- internal/keystore/keystore.go | 16 +++++++++++----- internal/keystore/keystore_test.go | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/internal/keystore/keystore.go b/internal/keystore/keystore.go index 8b3a1097..d8a30cbf 100644 --- a/internal/keystore/keystore.go +++ b/internal/keystore/keystore.go @@ -19,28 +19,34 @@ func List(names []string, prefix string, n int) ([]string, string, error) { const N = 1024 slices.Sort(names) + // If a prefix is provided, filter the list to start with the first name that matches the prefix if prefix != "" { i := slices.IndexFunc(names, func(name string) bool { return strings.HasPrefix(name, prefix) }) if i < 0 { - return []string{}, "", nil + return []string{}, "", nil // Return empty if no match found } names = names[i:] + // Find the range of names that match the prefix for i, name := range names { if !strings.HasPrefix(name, prefix) { + // Return the slice of names that match the prefix return names[:i], "", nil } - if (n > 0 && i > n) || i == N { - if i == len(names)-1 { - return names, "", nil + if (n > 0 && i+1 == n) || i+1 == N { + if i+1 == len(names) { + // Return all names if the list ends here + return names[:i+1], "", nil } - return names[:i], names[i], nil + // Return the first n names or N names, plus the next name to continue from + return names[:i+1], names[i+1], nil } } } + // If no prefix or entire list matches the prefix switch { case (n <= 0 && len(names) <= N) || len(names) <= n: return names, "", nil diff --git a/internal/keystore/keystore_test.go b/internal/keystore/keystore_test.go index 8606d852..b78ea8af 100644 --- a/internal/keystore/keystore_test.go +++ b/internal/keystore/keystore_test.go @@ -53,4 +53,18 @@ var listTests = []struct { List: []string{"my-key"}, ContinueAt: "my-key2", }, + { + Names: []string{"my-key1", "my-key2", "other-key3", "my-key3"}, + Prefix: "my", + N: 2, + List: []string{"my-key1", "my-key2"}, + ContinueAt: "my-key3", + }, + { + Names: []string{"other-key", "my-key4", "my-key2", "my-key1", "my-key3"}, + Prefix: "my", + N: 2, + List: []string{"my-key1", "my-key2"}, + ContinueAt: "my-key3", + }, }