senile/
crawler.rs

1use std::error::Error;
2
3use crossbeam::channel::Sender;
4use fancy_regex::Regex;
5use walkdir::WalkDir;
6
7/// The crawler type that goes through a (sub-)tree of a file/directory (inode)
8/// and recursively gets files.
9pub struct Crawler<'s> {
10    matcher: &'s Regex,
11}
12impl<'s> Crawler<'s> {
13    /// Constructor for the crawler.
14    /// Accepting the regex which shall match the (fully qualified, relative)
15    /// file names.
16    pub fn new(matcher: &'s Regex) -> Self {
17        Self { matcher }
18    }
19
20    /// Executing the crawl, sending the results during the operation through
21    /// the sender argument.
22    pub fn crawl(&self, path: &str, sender: Sender<String>) -> Result<(), Box<dyn Error>> {
23        for entry in WalkDir::new(path)
24            .into_iter()
25            .filter_map(Result::ok)
26            .filter(|e| !e.file_type().is_dir())
27        {
28            let entry_path = entry.into_path();
29            let entry_path_str = entry_path.to_str().unwrap();
30            if !self.matcher.is_match(entry_path_str)? {
31                continue;
32            }
33            sender.send(entry_path_str.to_owned())?;
34        }
35        Ok(())
36    }
37}