Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Get File Paths Without Directoires Using Walkdir In Rust

Code

//! ```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);
}

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()
}

Results

[_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",
]