chore: refactor search function

pull/1241/head^2
Oleg Lobanov 2021-01-12 19:14:23 +01:00
parent b6263eb607
commit 21b5a76fa7
No known key found for this signature in database
GPG Key ID: 7CC64E41212621B0
1 changed files with 21 additions and 25 deletions

View File

@ -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)
})
}