BurntSushi / walkdir

Rust library for walking directories recursively.
The Unlicense
1.24k stars 107 forks source link

Unexpected `filter_entry` behavior #2

Closed zitsen closed 8 years ago

zitsen commented 8 years ago

If I want to get all the files in a WalkDir root path, here is the code:

    for entry in WalkDir::new("/tmp/").into_iter().filter_entry(|e| e.file_type().is_file()) {
        let entry = entry.unwrap();
        println!("{}", entry.path().display());
    }

which I expect that all the files in "/tmp/" dir should be printed out, it just skips the root path(because it is not a file) and prints nothing.

Is this a code mistake or I must have missed some tips?

Thanks for help.

BurntSushi commented 8 years ago

Here is the relevant part of the documentation for filter_entry:

Yields only entries which satisfy the given predicate and skips descending into directories that do not satisfy the given predicate.

Since no directory will satisfy that is_file predicate, namely, the root directory, it won't be descended into. Stated differently, filter_entry is only useful when you want to avoid descending into directories.

It's not clear from your issue, but it seems to me like you explicitly don't want to avoid descending into directories. So why not use filter instead? e.g.,

for entry in WalkDir::new("/tmp/").into_iter().filter_map(|e| e.ok()).filter(|e| e.file_type().is_file()) {
    println!("{}", entry.path().display());
}

The filter_map says "skip entries that could not be read" (e.g., permission error). The filter says "skip entries that aren't files." This will run over every entry in /tmp/ and all directories will be descended into.

zitsen commented 8 years ago

Got it. Thanks @BurntSushi for your reply.