Struct WalkDir
struct WalkDir { ... }
A builder to create an iterator for recursively walking a directory.
Results are returned in depth first fashion, with directories yielded
before their contents. If contents_first is true, contents are yielded
before their directories. The order is unspecified but if sort_by is
given, directory entries are sorted according to this function. Directory
entries . and .. are always omitted.
If an error occurs at any point during iteration, then it is returned in place of its corresponding directory entry and iteration continues as normal. If an error occurs while opening a directory for reading, then it is not descended into (but the error is still yielded by the iterator). Iteration may be stopped at any time. When the iterator is destroyed, all resources associated with it are freed.
Usage
This type implements IntoIterator so that it may be used as the subject
of a for loop. You may need to call into_iter explicitly if you want
to use iterator adapters such as filter_entry.
Idiomatic use of this type should use method chaining to set desired
options. For example, this only shows entries with a depth of 1, 2 or
3 (relative to foo):
use walkdir::WalkDir;
# use walkdir::Error;
# fn try_main() -> Result<(), Error> {
for entry in WalkDir::new("foo").min_depth(1).max_depth(3) {
println!("{}", entry?.path().display());
}
# Ok(())
# }
Note that the iterator by default includes the top-most directory. Since
this is the only directory yielded with depth 0, it is easy to ignore it
with the min_depth setting:
use walkdir::WalkDir;
# use walkdir::Error;
# fn try_main() -> Result<(), Error> {
for entry in WalkDir::new("foo").min_depth(1) {
println!("{}", entry?.path().display());
}
# Ok(())
# }
This will only return descendents of the foo directory and not foo
itself.
Loops
This iterator (like most/all recursive directory iterators) assumes that no loops can be made with hard links on your file system. In particular, this would require creating a hard link to a directory such that it creates a loop. On most platforms, this operation is illegal.
Note that when following symbolic/soft links, loops are detected and an error is reported.
Implementations
impl WalkDir
fn new<P: AsRef<Path>>(root: P) -> SelfCreate a builder for a recursive directory iterator starting at the file path
root. Ifrootis a directory, then it is the first item yielded by the iterator. Ifrootis a file, then it is the first and only item yielded by the iterator. Ifrootis a symlink, then it is always followed for the purposes of directory traversal. (A rootDirEntrystill obeys its documentation with respect to symlinks and thefollow_linkssetting.)fn min_depth(self: Self, depth: usize) -> SelfSet the minimum depth of entries yielded by the iterator.
The smallest depth is
0and always corresponds to the path given to thenewfunction on this type. Its direct descendents have depth1, and their descendents have depth2, and so on.fn max_depth(self: Self, depth: usize) -> SelfSet the maximum depth of entries yield by the iterator.
The smallest depth is
0and always corresponds to the path given to thenewfunction on this type. Its direct descendents have depth1, and their descendents have depth2, and so on.Note that this will not simply filter the entries of the iterator, but it will actually avoid descending into directories when the depth is exceeded.
fn follow_links(self: Self, yes: bool) -> SelfFollow symbolic links. By default, this is disabled.
When
yesistrue, symbolic links are followed as if they were normal directories and files. If a symbolic link is broken or is involved in a loop, an error is yielded.When enabled, the yielded
DirEntryvalues represent the target of the link while the path corresponds to the link. See theDirEntrytype for more details.fn follow_root_links(self: Self, yes: bool) -> SelfFollow symbolic links if these are the root of the traversal. By default, this is enabled.
When
yesistrue, symbolic links on root paths are followed which is effective if the symbolic link points to a directory. If a symbolic link is broken or is involved in a loop, an error is yielded as the first entry of the traversal.When enabled, the yielded
DirEntryvalues represent the target of the link while the path corresponds to the link. See theDirEntrytype for more details, and all future entries will be contained within the resolved directory behind the symbolic link of the root path.fn max_open(self: Self, n: usize) -> SelfSet the maximum number of simultaneously open file descriptors used by the iterator.
nmust be greater than or equal to1. Ifnis0, then it is set to1automatically. If this is not set, then it defaults to some reasonably low number.This setting has no impact on the results yielded by the iterator (even when
nis1). Instead, this setting represents a trade off between scarce resources (file descriptors) and memory. Namely, when the maximum number of file descriptors is reached and a new directory needs to be opened to continue iteration, then a previous directory handle is closed and has its unyielded entries stored in memory. In practice, this is a satisfying trade off because it scales with respect to the depth of your file tree. Therefore, low values (even1) are acceptable.Note that this value does not impact the number of system calls made by an exhausted iterator.
Platform behavior
On Windows, if
follow_linksis enabled, then this limit is not respected. In particular, the maximum number of file descriptors opened is proportional to the depth of the directory tree traversed.fn sort_by<F>(self: Self, cmp: F) -> Self where F: FnMut(&DirEntry, &DirEntry) -> Ordering + Send + Sync + 'staticSet a function for sorting directory entries with a comparator function.
If a compare function is set, the resulting iterator will return all paths in sorted order. The compare function will be called to compare entries from the same directory.
use cmp; use OsString; use WalkDir; new.sort_by;fn sort_by_key<K, F>(self: Self, cmp: F) -> Self where F: FnMut(&DirEntry) -> K + Send + Sync + 'static, K: OrdSet a function for sorting directory entries with a key extraction function.
If a compare function is set, the resulting iterator will return all paths in sorted order. The compare function will be called to compare entries from the same directory.
use cmp; use OsString; use WalkDir; new.sort_by_key;fn sort_by_file_name(self: Self) -> SelfSort directory entries by file name, to ensure a deterministic order.
This is a convenience function for calling
Self::sort_by().use WalkDir; new.sort_by_file_name;fn contents_first(self: Self, yes: bool) -> SelfYield a directory's contents before the directory itself. By default, this is disabled.
When
yesisfalse(as is the default), the directory is yielded before its contents are read. This is useful when, e.g. you want to skip processing of some directories.When
yesistrue, the iterator yields the contents of a directory before yielding the directory itself. This is useful when, e.g. you want to recursively delete a directory.Example
Assume the following directory tree:
foo/ abc/ qrs tuv def/With contents_first disabled (the default), the following code visits the directory tree in depth-first order:
use walkdir::WalkDir; for entry in WalkDir::new("foo") { let entry = entry.unwrap(); println!("{}", entry.path().display()); } // foo // foo/abc // foo/abc/qrs // foo/abc/tuv // foo/defWith contents_first enabled:
use walkdir::WalkDir; for entry in WalkDir::new("foo").contents_first(true) { let entry = entry.unwrap(); println!("{}", entry.path().display()); } // foo/abc/qrs // foo/abc/tuv // foo/abc // foo/def // foofn same_file_system(self: Self, yes: bool) -> SelfDo not cross file system boundaries.
When this option is enabled, directory traversal will not descend into directories that are on a different file system from the root path.
Currently, this option is only supported on Unix and Windows. If this option is used on an unsupported platform, then directory traversal will immediately return an error and will not yield any entries.
impl Debug for WalkDir
fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<'_>) -> $crate::fmt::Result
impl Freeze for WalkDir
impl IntoIterator for WalkDir
fn into_iter(self: Self) -> IntoIter
impl RefUnwindSafe for WalkDir
impl Send for WalkDir
impl Sync for WalkDir
impl Unpin for WalkDir
impl UnwindSafe for WalkDir
impl<T> Any for WalkDir
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for WalkDir
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for WalkDir
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> From for WalkDir
fn from(t: T) -> TReturns the argument unchanged.
impl<T, U> Into for WalkDir
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for WalkDir
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for WalkDir
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>