BurntSushi / walkdir

Rust library for walking directories recursively.
The Unlicense
1.21k stars 106 forks source link

Crawl only to a certain depth of folders? #137

Closed casperstorm closed 4 years ago

casperstorm commented 4 years ago

I have a directory structure looking like:

example-data/
    ├── foo/
    │   ├── foo-file.html
    │   └── foo-folder/
    │       └── foo-file-2.html
    └── bar/
    │   ├── bar-file.html
    │   └── bar-folder/
    │       └── bar-file-2.html
    └── baz/
        ├── baz-file.html
        └── baz-folder/
            └── baz-file-2.html

I would like to do some actions on all .html files inside the first folder (foo/, bar/ and baz/), thus ignoring the folders foo-folder, bar-folder, and baz-folder and their content (which also has some .html files).

I am a little new to Rust, and working on a small project, here is what I have so far, which walks through all the folders:

use walkdir::WalkDir;
use std::path::Path;
use std::ffi::OsStr;

fn main() {
    for e in WalkDir::new("./example-data").into_iter().filter_map(|e| e.ok()) {
        if e.metadata().unwrap().is_file() {
            let file_name = e.file_name();
            let file_extension = get_extension_from_filename(file_name);
            if file_extension == Some("html") {
                println!("do action...")
            }
        }
    }
}

// https://stackoverflow.com/a/45292067
fn get_extension_from_filename(filename: &OsStr) -> Option<&str> {
    Path::new(filename)
        .extension()
        .and_then(OsStr::to_str)
}

Is there any idiomatically way of doing this, in this crate? Or how would you approach this?

BurntSushi commented 4 years ago

Have you tried using the max_depth option?

casperstorm commented 4 years ago

Have you tried using the max_depth option?

I completely missed that. That fixed it. Thanks, and sorry for missing that.