-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpredicate.go
59 lines (53 loc) · 1.12 KB
/
predicate.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
package find
import (
"fmt"
"os"
"path/filepath"
)
type predicate interface {
Match(root string, path string) (bool, error)
}
type PredicateError struct {
errType error
errMessage string
}
func (p PredicateError) Error() string {
return fmt.Sprintf("%q: %s", p.errType, p.errMessage)
}
type predicates []predicate
func (ps predicates) Evaluate(root string) ([]string, error) {
results := []string{}
err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
allMatched := true
for _, p := range ps {
matched := false
if matched, err = p.Match(root, path); err != nil {
if pe, ok := err.(PredicateError); ok {
// ignore the directory if encountered a different filesystem
if pe.errType == ErrorFSType {
return filepath.SkipDir
} else {
fmt.Fprintf(os.Stderr, "error: %s\n", pe.errMessage)
return nil
}
}
return err
}
if !matched {
allMatched = false
break
}
}
if allMatched {
results = append(results, path)
}
return nil
})
if err != nil {
return nil, err
}
return results, nil
}