filebrowser/search/search.go

73 lines
1.4 KiB
Go
Raw Normal View History

package search
import (
"os"
2021-01-12 18:14:23 +00:00
"path"
"path/filepath"
"strings"
"github.com/spf13/afero"
2020-05-31 23:12:36 +00:00
"github.com/filebrowser/filebrowser/v2/rules"
)
type searchOptions struct {
CaseSensitive bool
Conditions []condition
Terms []string
}
// Search searches for a query in a fs.
func Search(fs afero.Fs, scope, query string, checker rules.Checker, found func(path string, f os.FileInfo) error) error {
search := parseSearch(query)
2021-01-12 18:14:23 +00:00
scope = filepath.ToSlash(filepath.Clean(scope))
scope = path.Join("/", scope)
2024-04-01 16:24:06 +00:00
return afero.Walk(fs, scope, func(fPath string, f os.FileInfo, _ error) error {
2021-01-12 18:14:23 +00:00
fPath = filepath.ToSlash(filepath.Clean(fPath))
fPath = path.Join("/", fPath)
relativePath := strings.TrimPrefix(fPath, scope)
relativePath = strings.TrimPrefix(relativePath, "/")
2021-01-12 18:14:23 +00:00
if fPath == scope {
return nil
}
2021-01-12 18:14:23 +00:00
if !checker.Check(fPath) {
return nil
}
if len(search.Conditions) > 0 {
match := false
for _, t := range search.Conditions {
2021-01-12 18:14:23 +00:00
if t(fPath) {
match = true
break
}
}
if !match {
return nil
}
}
if len(search.Terms) > 0 {
for _, term := range search.Terms {
2021-01-12 18:14:23 +00:00
_, fileName := path.Split(fPath)
if !search.CaseSensitive {
fileName = strings.ToLower(fileName)
term = strings.ToLower(term)
}
if strings.Contains(fileName, term) {
return found(relativePath, f)
}
}
2021-01-12 18:14:23 +00:00
return nil
}
2021-01-12 18:14:23 +00:00
return found(relativePath, f)
})
}