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>,
}
/// Build the filetree
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)
.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)