Recursive File Search by Extension

Walk a directory tree without following symlinks, skip hidden entries, and collect regular files matching one extension.

RustData Integrity

Code

snippet
use std::path::Path;
use walkdir::{DirEntry, WalkDir};

fn is_hidden(entry: &DirEntry) -> bool {
    entry
        .file_name()
        .to_str()
        .map(|name| name.starts_with('.'))
        .unwrap_or(false)
}

fn find_by_extension(root: &Path, extension: &str) -> Vec<String> {
    WalkDir::new(root)
        .follow_links(false)
        .into_iter()
        .filter_entry(|entry| entry.depth() == 0 || !is_hidden(entry))
        .filter_map(Result::ok)
        .filter(|entry| entry.file_type().is_file())
        .filter(|entry| {
            entry.path().extension().and_then(|ext| ext.to_str()) == Some(extension)
        })
        .map(|entry| entry.path().display().to_string())
        .collect()
}

fn main() {
    let matches = find_by_extension(Path::new("."), "rs");
    for path in matches.iter().take(5) {
        println!("{path}");
    }
    println!("total: {}", matches.len());
}