diff --git a/src/main.rs b/src/main.rs index 328b92c..8a139fa 100644 --- a/src/main.rs +++ b/src/main.rs @@ -20,6 +20,64 @@ Written by Hatter Jiang } // --------------------------------------------------------------------------------------------------------- + +fn walk_dir(dir: &Path, + func_read_error: &FError, + func_process_file: &FProcess, + func_filter_dir: &FFilter) -> XResult<()> + where FError: Fn(&Path, Box) -> (), + FProcess: Fn(&Path) -> (), + FFilter: Fn(&Path) -> bool { + walk_dir_with_depth_check(&mut 0u32, dir, func_read_error, func_process_file, func_filter_dir) +} + +fn walk_dir_with_depth_check(depth: &mut u32, dir: &Path, + func_read_error: &FError, + func_process_file: &FProcess, + func_filter_dir: &FFilter) -> XResult<()> + where FError: Fn(&Path, Box) -> (), + FProcess: Fn(&Path) -> (), + FFilter: Fn(&Path) -> bool { + if *depth > 100u32 { + return Err(Box::new(std::io::Error::new(std::io::ErrorKind::Other, format!("Depth exceed, depth: {}, path: {:?}", *depth, dir)))); + } + let read_dir = match dir.read_dir() { + Err(err) => { + func_read_error(&dir, Box::new(err)); + return Ok(()); + }, + Ok(rd) => rd, + }; + for dir_entry_item in read_dir { + let dir_entry = match dir_entry_item { + Err(err) => { + func_read_error(&dir, Box::new(err)); + continue; // Ok? + }, + Ok(item) => item, + }; + + let path_buf = dir_entry.path(); + let sub_dir = path_buf.as_path(); + if sub_dir.is_file() { + func_process_file(&sub_dir); + } else if sub_dir.is_dir() { + if func_filter_dir(&sub_dir) { + *depth += 1; + match walk_dir_with_depth_check(depth, &sub_dir, func_read_error, func_process_file, func_filter_dir) { + Err(err) => { + func_read_error(&sub_dir, err); + () + }, + Ok(_) => (), + } + *depth -= 1; + } + } // should process else ? not file, dir + } + Ok(()) +} + fn check_path(path: &Path) { //println!("-------------- {:?} {}", path, path.is_dir()); }