1use std::{ path::Path, fs, error::Error };
6
7use crate::FindConfig;
8
9fn traverse(path: &Path, query: &str, depth: usize, i: usize) -> i32 {
10 if i > depth { return 0 };
11
12 let mut found_count = 0;
13
14 match fs::read_dir(path) {
15 Err(e) => println!("Cannot read directory {:?}: {}", path.file_name().unwrap(), e),
16 Ok(entries) => {
17 for entry in entries.flatten() {
18 if entry.file_name().to_str().unwrap().contains(query) {
19 println!("{}", entry.path().to_str().unwrap());
20 found_count += 1;
21 }
22
23 if let Ok(metadata) = entry.metadata() {
24 if metadata.is_dir() {
25 found_count += traverse(&entry.path(), query, depth, i + 1);
26 }
27 }
28 }
29 }
30 };
31
32 found_count
33}
34
35pub fn run_find(config: FindConfig) -> Result<(), Box<dyn Error>> {
37 println!("Searching for {} in {:?}", config.query, config.path);
38
39 let found_count = traverse(config.path, config.query.as_str(), config.depth, 0);
40
41 if found_count == 0 {
42 println!("No match found.");
43 } else {
44 println!("Found {} matches.", found_count);
45 }
46
47 Ok(())
48}