From 4f5be8a89755dfdece7b2ec60c90d74bfde1b707 Mon Sep 17 00:00:00 2001 From: Alan Pearce Date: Sun, 12 May 2024 14:37:59 +0200 Subject: refactor: extract index deletion function --- internal/search/indexer.go | 43 ++++++++++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 17 deletions(-) (limited to 'internal/search') diff --git a/internal/search/indexer.go b/internal/search/indexer.go index e2e23c2..a74189e 100644 --- a/internal/search/indexer.go +++ b/internal/search/indexer.go @@ -137,6 +137,30 @@ var expectedDataFiles = []string{ "sources", } +func deleteIndex(dataRoot string) error { + dir, err := os.ReadDir(dataRoot) + if err != nil { + return errors.WithMessagef(err, "could not read data directory %s", dataRoot) + } + remainingFiles := slices.DeleteFunc(dir, func(e fs.DirEntry) bool { + return slices.Contains(expectedDataFiles, e.Name()) + }) + if len(remainingFiles) > 0 { + return errors.Errorf( + "cowardly refusing to remove data directory %s as it contains unknown files: %v", + dataRoot, + remainingFiles, + ) + } + + err = os.RemoveAll(dataRoot) + if err != nil { + return errors.WithMessagef(err, "could not remove data directory %s", dataRoot) + } + + return nil +} + func NewIndexer(dataRoot string, force bool) (*WriteIndex, error) { var err error bleve.SetLog(log.Default()) @@ -157,24 +181,9 @@ func NewIndexer(dataRoot string, force bool) (*WriteIndex, error) { var meta *IndexMeta if !exists || force { if force { - dir, err := os.ReadDir(dataRoot) - if err != nil { - return nil, errors.WithMessagef(err, "could not read data directory %s", dataRoot) - } - remainingFiles := slices.DeleteFunc(dir, func(e fs.DirEntry) bool { - return slices.Contains(expectedDataFiles, e.Name()) - }) - if len(remainingFiles) > 0 { - return nil, errors.Errorf( - "cowardly refusing to remove data directory %s as it contains unknown files: %v", - dataRoot, - remainingFiles, - ) - } - - err = os.RemoveAll(dataRoot) + err = deleteIndex(dataRoot) if err != nil { - return nil, errors.WithMessagef(err, "could not remove index file %s", indexPath) + return nil, err } } idx, err = createIndex(indexPath) -- cgit 1.4.1