-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrfind.go
80 lines (69 loc) · 1.47 KB
/
rfind.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
73
74
75
76
77
78
79
80
package rfind
import (
"errors"
"math"
"os"
"path/filepath"
)
type Rfind struct {
MaxUpwardDepth uint
MaxDepthFromRoot uint
Limit uint
IsFile bool
IsDir bool
}
func (r *Rfind) Find(originPath string, targets []string) ([]string, error) {
var searchPaths []string
for {
searchPaths = append(searchPaths, originPath)
parentDir := filepath.Dir(originPath)
if parentDir == originPath {
// reaches to the root dir
break
}
originPath = parentDir
}
maxUpwardDepth := math.MaxInt
if r.MaxUpwardDepth > 0 {
maxUpwardDepth = int(r.MaxUpwardDepth)
}
maxDepthFromRoot := math.MaxInt
if r.MaxDepthFromRoot > 0 {
maxDepthFromRoot = len(searchPaths) - int(r.MaxDepthFromRoot)
}
limit := math.MaxInt
if r.Limit > 0 {
limit = int(r.Limit)
}
numOfFound := 0
var foundItems []string
searchLoop:
for _, searchPath := range searchPaths {
maxUpwardDepth--
if maxUpwardDepth < 0 {
break
}
maxDepthFromRoot--
if maxDepthFromRoot < 0 {
break
}
for _, target := range targets {
targetFullPath := filepath.Join(searchPath, target)
stat, err := os.Stat(targetFullPath)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
continue
}
return nil, err
}
if (r.IsFile && stat.Mode().IsRegular()) || (r.IsDir && stat.Mode().IsDir()) {
foundItems = append(foundItems, targetFullPath)
numOfFound++
if numOfFound >= limit {
break searchLoop
}
}
}
}
return foundItems, nil
}