Get File Paths Without Directoires Using Walkdir In Rust
//! ```cargo
//! [dependencies]
//! walkdir = "2"
//! ```
use std::path::PathBuf;
use walkdir::WalkDir;
fn main() {
let source_dir = PathBuf::from("glob_test");
let ext = "txt";
let file_list = get_file_paths(&source_dir, ext);
dbg!(file_list);
}
pub fn get_file_paths(source_dir: &PathBuf, extension: &str) -> Vec<PathBuf> {
let walker = WalkDir::new(source_dir).into_iter();
walker
.filter_map(|path_result| match path_result {
Ok(path) => match path.path().extension() {
Some(ext) => {
if ext == extension {
Some(path.path().to_path_buf())
} else {
None
}
}
None => None,
},
Err(_) => None,
})
.collect()
}
Output:
[_active_nvim_run:13] file_list = [
"glob_test/echo.txt",
"glob_test/BRAVO.txt",
"glob_test/fOxtrOt.txt",
"glob_test/hotel.txt",
"glob_test/charlie.txt",
"glob_test/golf.txt",
"glob_test/delta.txt",
"glob_test/alfa.txt",
]
Notes
-
The example on the walkdir page uses
filter_entry()
but that doesn't descend into a directory if it doesn't match. So, it doesn't find all matching files. -
This gets all files based off extension without that filter blocking them.
This also converts the
WalkDir
DirEntry
s toPathBuf
s
-- end of line --