Skip to content

Commit 86d74cc

Browse files
committed
Added ReadDirRecursiveFiltered function
1 parent 8d03be0 commit 86d74cc

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

readdir.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,49 @@ func (p *Path) ReadDirRecursive() (PathList, error) {
8484
return paths, nil
8585
}
8686

87+
// ReadDirRecursiveFiltered returns a PathList containing the content of the directory
88+
// and its subdirectories pointed by the current Path, filtered by the given skipFilter
89+
// and filters:
90+
// - `recursionFilter` is a filter that is checked to determine if the subdirectory must
91+
// by visited recursively (if the filter rejects the entry, the entry is not visited
92+
// but can still be added to the result)
93+
// - `filters` are the filters that are checked to determine if the entry should be
94+
// added to the resulting PathList
95+
func (p *Path) ReadDirRecursiveFiltered(recursionFilter ReadDirFilter, filters ...ReadDirFilter) (PathList, error) {
96+
infos, err := ioutil.ReadDir(p.path)
97+
if err != nil {
98+
return nil, err
99+
}
100+
paths := PathList{}
101+
for _, info := range infos {
102+
path := p.Join(info.Name())
103+
104+
accept := true
105+
for _, filter := range filters {
106+
if !filter(path) {
107+
accept = false
108+
break
109+
}
110+
}
111+
if accept {
112+
paths.Add(path)
113+
}
114+
115+
if recursionFilter == nil || recursionFilter(path) {
116+
if isDir, err := path.IsDirCheck(); err != nil {
117+
return nil, err
118+
} else if isDir {
119+
subPaths, err := path.ReadDirRecursiveFiltered(recursionFilter, filters...)
120+
if err != nil {
121+
return nil, err
122+
}
123+
paths.AddAll(subPaths)
124+
}
125+
}
126+
}
127+
return paths, nil
128+
}
129+
87130
// FilterDirectories is a ReadDirFilter that accepts only directories
88131
func FilterDirectories() ReadDirFilter {
89132
return func(path *Path) bool {

0 commit comments

Comments
 (0)