feat(Store): extracted suggestion logic into a helper so we can share it between list and delete-dbs

This commit is contained in:
Lewis Wynne 2025-11-06 22:52:14 +00:00
parent fa224d9b38
commit 0b980ed9dc
2 changed files with 43 additions and 20 deletions

View file

@ -22,6 +22,9 @@ THE SOFTWARE.
package cmd
import (
"errors"
"fmt"
"github.com/dgraph-io/badger/v4"
"github.com/spf13/cobra"
)
@ -38,10 +41,18 @@ func list(cmd *cobra.Command, args []string) error {
store := &Store{}
targetDB := "@default"
if len(args) == 1 {
dbName, err := store.parseDB(args[0], false)
rawArg := args[0]
dbName, err := store.parseDB(rawArg, false)
if err != nil {
return err
}
if _, err := store.FindStore(dbName); err != nil {
var notFound errNotFound
if errors.As(err, &notFound) {
return fmt.Errorf("%q does not exist, %s", rawArg, err.Error())
}
return err
}
targetDB = "@" + dbName
}

View file

@ -131,30 +131,17 @@ func (s *Store) FindStore(k string) (string, error) {
if err != nil {
return "", err
}
_, err = os.Stat(path)
if strings.TrimSpace(n) == "" || os.IsNotExist(err) {
stores, err := s.AllStores()
info, statErr := os.Stat(path)
if strings.TrimSpace(n) == "" || os.IsNotExist(statErr) || (statErr == nil && !info.IsDir()) {
suggestions, err := s.suggestStores(n)
if err != nil {
return "", err
}
var suggestions []string
minThreshold := 1
maxThreshold := 4
threshold := len(n) / 3
if threshold < minThreshold {
threshold = minThreshold
}
if threshold > maxThreshold {
threshold = maxThreshold
}
for _, store := range stores {
distance := levenshtein.ComputeDistance(n, store)
if distance <= threshold {
suggestions = append(suggestions, store)
}
}
return "", errNotFound{suggestions}
}
if statErr != nil {
return "", statErr
}
return path, nil
}
@ -212,3 +199,28 @@ func (s *Store) path(args ...string) (string, error) {
}
return filepath.Join(append([]string{dir}, args...)...), nil
}
func (s *Store) suggestStores(target string) ([]string, error) {
stores, err := s.AllStores()
if err != nil {
return nil, err
}
target = strings.TrimSpace(target)
minThreshold := 1
maxThreshold := 4
threshold := len(target) / 3
if threshold < minThreshold {
threshold = minThreshold
}
if threshold > maxThreshold {
threshold = maxThreshold
}
var suggestions []string
for _, store := range stores {
distance := levenshtein.ComputeDistance(target, store)
if distance <= threshold {
suggestions = append(suggestions, store)
}
}
return suggestions, nil
}