From 21b5a76fa75af67b10e6e4608289db0ea43a8191 Mon Sep 17 00:00:00 2001 From: Oleg Lobanov Date: Tue, 12 Jan 2021 19:14:23 +0100 Subject: [PATCH] chore: refactor search function --- search/search.go | 46 +++++++++++++++++++++------------------------- 1 file changed, 21 insertions(+), 25 deletions(-) diff --git a/search/search.go b/search/search.go index 7f3de2be..8920f92c 100644 --- a/search/search.go +++ b/search/search.go @@ -2,6 +2,8 @@ package search import ( "os" + "path" + "path/filepath" "strings" "github.com/spf13/afero" @@ -19,34 +21,28 @@ type searchOptions struct { func Search(fs afero.Fs, scope, query string, checker rules.Checker, found func(path string, f os.FileInfo) error) error { search := parseSearch(query) - scope = strings.Replace(scope, "\\", "/", -1) - scope = strings.TrimPrefix(scope, "/") - scope = strings.TrimSuffix(scope, "/") - scope = "/" + scope + "/" + scope = filepath.ToSlash(filepath.Clean(scope)) + scope = path.Join("/", scope) - return afero.Walk(fs, scope, func(originalPath string, f os.FileInfo, err error) error { - originalPath = strings.Replace(originalPath, "\\", "/", -1) - originalPath = strings.TrimPrefix(originalPath, "/") - originalPath = "/" + originalPath - path := originalPath + return afero.Walk(fs, scope, func(fPath string, f os.FileInfo, err error) error { + fPath = filepath.ToSlash(filepath.Clean(fPath)) + fPath = path.Join("/", fPath) + relativePath := strings.TrimPrefix(fPath, scope) + relativePath = strings.TrimPrefix(relativePath, "/") - if path == scope { + if fPath == scope { return nil } - if !checker.Check(path) { + if !checker.Check(fPath) { return nil } - if !search.CaseSensitive { - path = strings.ToLower(path) - } - if len(search.Conditions) > 0 { match := false for _, t := range search.Conditions { - if t(path) { + if t(fPath) { match = true break } @@ -59,18 +55,18 @@ func Search(fs afero.Fs, scope, query string, checker rules.Checker, found func( if len(search.Terms) > 0 { for _, term := range search.Terms { - if strings.Contains(path, term) { - originalPath = strings.TrimPrefix(originalPath, scope) - originalPath = strings.TrimPrefix(originalPath, "/") - return found(originalPath, f) + _, fileName := path.Split(fPath) + if !search.CaseSensitive { + fileName = strings.ToLower(fileName) + term = strings.ToLower(term) + } + if strings.Contains(fileName, term) { + return found(relativePath, f) } } - } else { - originalPath = strings.TrimPrefix(originalPath, scope) - originalPath = strings.TrimPrefix(originalPath, "/") - return found(originalPath, f) + return nil } - return nil + return found(relativePath, f) }) }