use filter_map instead of a for loop

This commit is contained in:
Mylloon 2024-04-01 16:42:49 +02:00
parent fd26454a72
commit 1431a3bf35
Signed by: Anri
GPG key ID: A82D63DFF8D1317F

View file

@ -38,41 +38,33 @@ struct FileNode {
children: Vec<FileNode>, children: Vec<FileNode>,
} }
/// Build the filetree
fn get_filetree(dir_path: &str, exclusion_list: Vec<String>) -> FileNode { fn get_filetree(dir_path: &str, exclusion_list: Vec<String>) -> FileNode {
let entries = std::fs::read_dir(dir_path).unwrap(); let children = std::fs::read_dir(dir_path).unwrap()
.filter_map(Result::ok)
let mut children = Vec::new(); .filter_map(|entry| {
for entry in entries.filter_map(Result::ok) {
let entry_path = entry.path(); let entry_path = entry.path();
let entry_name = entry_path.file_name().and_then(|n| n.to_str()).unwrap(); let entry_name = entry_path.file_name()?.to_str()?;
// We should support regex? // Exclude element with the exclusion_list
if !exclusion_list if exclusion_list.iter().any(|pattern| {
.iter() Regex::new(pattern)
.any(|pattern| match Regex::new(pattern) { .map(|re| re.is_match(entry_name))
Ok(re) => re.is_match(entry_name), .unwrap_or(false)
Err(e) => { }) {
eprintln!("{e}"); return None;
false
} }
})
{
let filename = entry_name.to_string();
if entry_path.is_file() { if entry_path.is_file() {
children.push(FileNode { Some(FileNode {
name: filename, name: entry_name.to_string(),
is_dir: false, is_dir: false,
children: vec![], children: vec![],
}); })
} else { } else {
children.push(get_filetree( Some(get_filetree(entry_path.to_str().unwrap(), exclusion_list.clone()))
entry_path.to_str().unwrap(),
exclusion_list.to_owned(),
));
}
}
} }
})
.collect();
FileNode { FileNode {
name: Path::new(dir_path) name: Path::new(dir_path)