2019-01-05 22:44:33 +00:00
|
|
|
package search
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/spf13/afero"
|
2020-05-31 23:12:36 +00:00
|
|
|
|
|
|
|
"github.com/filebrowser/filebrowser/v2/rules"
|
2019-01-05 22:44:33 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
2019-01-09 14:18:03 +00:00
|
|
|
scope = strings.Replace(scope, "\\", "/", -1)
|
|
|
|
scope = strings.TrimPrefix(scope, "/")
|
|
|
|
scope = strings.TrimSuffix(scope, "/")
|
|
|
|
scope = "/" + scope + "/"
|
2019-01-05 23:01:16 +00:00
|
|
|
|
2019-01-09 14:18:03 +00:00
|
|
|
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
|
|
|
|
|
|
|
|
if path == scope {
|
2019-01-05 22:44:33 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-01-09 14:18:03 +00:00
|
|
|
if !checker.Check(path) {
|
|
|
|
return nil
|
2019-01-05 22:44:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if !search.CaseSensitive {
|
|
|
|
path = strings.ToLower(path)
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(search.Conditions) > 0 {
|
|
|
|
match := false
|
|
|
|
|
|
|
|
for _, t := range search.Conditions {
|
|
|
|
if t(path) {
|
|
|
|
match = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if !match {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(search.Terms) > 0 {
|
|
|
|
for _, term := range search.Terms {
|
|
|
|
if strings.Contains(path, term) {
|
2019-01-09 14:18:03 +00:00
|
|
|
return found(strings.TrimPrefix(originalPath, scope), f)
|
2019-01-05 22:44:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
}
|