Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Get File Paths Without Directoires Using Walkdir In Rust

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

- The example on the walkdir page uses [TODO: Code shorthand span ] 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 [TODO: Code shorthand span ] [TODO: Code shorthand span ] s to [TODO: Code shorthand span ] s