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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
use std::{
fs::{self, ReadDir},
io,
path::{Path, PathBuf},
};
use crate::path_filter;
#[derive(Debug)]
pub struct FileDiscovery<F> where F: path_filter::Filter {
path_filter: F,
recursive: bool,
current: ReadDir,
sub_dirs: Option<Vec<PathBuf>>,
}
impl<F> Iterator for FileDiscovery<F> where F: path_filter::Filter {
type Item = io::Result<PathBuf>;
fn next(&mut self) -> Option<Self::Item> {
loop {
match self.current.next() {
Some(entry) => match entry {
Ok(entry) => match entry.file_type() {
Ok(file_type) => {
if file_type.is_dir() {
if self.recursive == false || file_type.is_symlink() {
continue;
}
let dir = entry.path();
if self.path_filter.accept(&dir) == false {
continue;
}
match self.sub_dirs.as_mut() {
Some(sub_dirs) => sub_dirs.push(dir),
None => self.sub_dirs = Some(vec![dir]),
};
} else if file_type.is_file() {
let file = entry.path();
if self.path_filter.accept(&file) == false {
continue;
}
return Some(Ok(file));
}
},
Err(err) => return Some(Err(err)),
},
Err(err) => return Some(Err(err)),
},
None => match self.sub_dirs.as_mut() {
None => return None,
Some(sub_dirs) => match sub_dirs.len() {
0 => return None,
_ => match fs::read_dir(sub_dirs.remove(0)) {
Ok(new) => self.current = new,
Err(err) => return Some(Err(err)),
},
},
},
};
}
}
}
pub fn find_files<P, F>(dir: P, recursive: bool, path_filter: F) -> io::Result<FileDiscovery<F>> where P: AsRef<Path>, F: path_filter::Filter {
Ok(FileDiscovery {
path_filter,
recursive,
current: fs::read_dir(dir)?,
sub_dirs: None,
})
}