Skip to content

[libs] add recursive variant of fs::read_dir #69684

@yoshuawuyts

Description

@yoshuawuyts

Motivation

As part of the fs module there exist various recursive and non-recursive operations. create_dir and create_dir_all. remove_dir and remove_dir_all. But to read the contents of a directory there currently only exists read_dir, but no recursive counterpart:

Action Kind Base function Recursive variant
Create a directory fs::create_dir fs::create_dir_all
Remove a directory fs::remove_dir fs::remove_dir_all
Read a directory's contents fs::read_dir ...

I noticed the omission of this method when trying to read out a directory recursively, and discovered this was the only directory operation that doesn't have a recursive counterpart.

Usage overview

I'd imagine fs::read_dir_all would be used in much the same way as fs::read_dir:

for entry in fs::read_dir_all(dir)? {
    let entry = entry?;
    dbg!(entry.path());
}

Implementation overview

Roughly the API additions to std::fs would look like this:

#[derive(Debug)]
pub struct ReadDirAll;

impl Iterator for ReadDirAll {
    type Item = Result<DirEntry>;
}

pub fn read_dir_all<P: AsRef<Path>>(path: P) -> Result<ReadDirAll>;

Potential drawbacks

I remember reading something about the readdir(3) syscall, and a file filtering as part of the kernel. But I can't seem to find any reference to that anymore. I also thought this had been referenced in a prior RFC, but that too I cannot find.

But for argument's sake, even if there was a variant for readdir variant that took a filter I'd argue that since std::fs::read_dir doesn't provide filtering, neither should std::fs_read_dir_all. And if we'd want a variant that does provide filtering, it would not be a clean counterpart to fs::read_dir, so it would warrant introducing under a new name.

These functions should be able to co-exist with each other, much the same way fs::read_to_string and io::Read::read_to_string co-exist (both useful, but is a simplified version of the other).

Similar functionality in other languages

Conclusion

I think fs::read_dir_all makes for a straight forward addition to the stdlib. People expect this functionality to exist by default, and the shape and name of this function doesn't seem controversial. Even if filtering supersets of this functionality could possibly exist, they would likely be a different shape, and could co-exist with this function. Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions