-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
search.go
72 lines (58 loc) 路 1.4 KB
/
search.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package search
import (
"os"
"path"
"path/filepath"
"strings"
"github.com/spf13/afero"
"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)
scope = filepath.ToSlash(filepath.Clean(scope))
scope = path.Join("/", scope)
return afero.Walk(fs, scope, func(fPath string, f os.FileInfo, _ error) error {
fPath = filepath.ToSlash(filepath.Clean(fPath))
fPath = path.Join("/", fPath)
relativePath := strings.TrimPrefix(fPath, scope)
relativePath = strings.TrimPrefix(relativePath, "/")
if fPath == scope {
return nil
}
if !checker.Check(fPath) {
return nil
}
if len(search.Conditions) > 0 {
match := false
for _, t := range search.Conditions {
if t(fPath) {
match = true
break
}
}
if !match {
return nil
}
}
if len(search.Terms) > 0 {
for _, term := range search.Terms {
_, fileName := path.Split(fPath)
if !search.CaseSensitive {
fileName = strings.ToLower(fileName)
term = strings.ToLower(term)
}
if strings.Contains(fileName, term) {
return found(relativePath, f)
}
}
return nil
}
return found(relativePath, f)
})
}