From 1431a3bf35ad7793a5b35768fdd7730146885a63 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 1 Apr 2024 16:42:49 +0200 Subject: [PATCH] use filter_map instead of a for loop --- src/routes/cours.rs | 46 +++++++++++++++++++-------------------------- 1 file changed, 19 insertions(+), 27 deletions(-) diff --git a/src/routes/cours.rs b/src/routes/cours.rs index ffa8e0d..1f72197 100644 --- a/src/routes/cours.rs +++ b/src/routes/cours.rs @@ -38,41 +38,33 @@ struct FileNode { children: Vec, } -/// Build the filetree fn get_filetree(dir_path: &str, exclusion_list: Vec) -> FileNode { - let entries = std::fs::read_dir(dir_path).unwrap(); + let children = std::fs::read_dir(dir_path).unwrap() + .filter_map(Result::ok) + .filter_map(|entry| { + let entry_path = entry.path(); + let entry_name = entry_path.file_name()?.to_str()?; - let mut children = Vec::new(); - for entry in entries.filter_map(Result::ok) { - let entry_path = entry.path(); - let entry_name = entry_path.file_name().and_then(|n| n.to_str()).unwrap(); + // Exclude element with the exclusion_list + if exclusion_list.iter().any(|pattern| { + Regex::new(pattern) + .map(|re| re.is_match(entry_name)) + .unwrap_or(false) + }) { + return None; + } - // We should support regex? - if !exclusion_list - .iter() - .any(|pattern| match Regex::new(pattern) { - Ok(re) => re.is_match(entry_name), - Err(e) => { - eprintln!("{e}"); - false - } - }) - { - let filename = entry_name.to_string(); if entry_path.is_file() { - children.push(FileNode { - name: filename, + Some(FileNode { + name: entry_name.to_string(), is_dir: false, children: vec![], - }); + }) } else { - children.push(get_filetree( - entry_path.to_str().unwrap(), - exclusion_list.to_owned(), - )); + Some(get_filetree(entry_path.to_str().unwrap(), exclusion_list.clone())) } - } - } + }) + .collect(); FileNode { name: Path::new(dir_path)