Skip to main content

isideload_walkdir/
lib.rs

1/*!
2Crate `walkdir` provides an efficient and cross platform implementation
3of recursive directory traversal. Several options are exposed to control
4iteration, such as whether to follow symbolic links (default off), limit the
5maximum number of simultaneous open file descriptors and the ability to
6efficiently skip descending into directories.
7
8To use this crate, add `walkdir` as a dependency to your project's
9`Cargo.toml`:
10
11```toml
12[dependencies]
13walkdir = "2"
14```
15
16# From the top
17
18The [`WalkDir`] type builds iterators. The [`DirEntry`] type describes values
19yielded by the iterator. Finally, the [`Error`] type is a small wrapper around
20[`std::io::Error`] with additional information, such as if a loop was detected
21while following symbolic links (not enabled by default).
22
23[`WalkDir`]: struct.WalkDir.html
24[`DirEntry`]: struct.DirEntry.html
25[`Error`]: struct.Error.html
26[`std::io::Error`]: https://doc.rust-lang.org/stable/std/io/struct.Error.html
27
28# Example
29
30The following code recursively iterates over the directory given and prints
31the path for each entry:
32
33```no_run
34use walkdir::WalkDir;
35# use walkdir::Error;
36
37# fn try_main() -> Result<(), Error> {
38for entry in WalkDir::new("foo") {
39    println!("{}", entry?.path().display());
40}
41# Ok(())
42# }
43```
44
45Or, if you'd like to iterate over all entries and ignore any errors that
46may arise, use [`filter_map`]. (e.g., This code below will silently skip
47directories that the owner of the running process does not have permission to
48access.)
49
50```no_run
51use walkdir::WalkDir;
52
53for entry in WalkDir::new("foo").into_iter().filter_map(|e| e.ok()) {
54    println!("{}", entry.path().display());
55}
56```
57
58[`filter_map`]: https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.filter_map
59
60# Example: follow symbolic links
61
62The same code as above, except [`follow_links`] is enabled:
63
64```no_run
65use walkdir::WalkDir;
66# use walkdir::Error;
67
68# fn try_main() -> Result<(), Error> {
69for entry in WalkDir::new("foo").follow_links(true) {
70    println!("{}", entry?.path().display());
71}
72# Ok(())
73# }
74```
75
76[`follow_links`]: struct.WalkDir.html#method.follow_links
77
78# Example: skip hidden files and directories on unix
79
80This uses the [`filter_entry`] iterator adapter to avoid yielding hidden files
81and directories efficiently (i.e. without recursing into hidden directories):
82
83```no_run
84use walkdir::{DirEntry, WalkDir};
85# use walkdir::Error;
86
87fn is_hidden(entry: &DirEntry) -> bool {
88    entry.file_name()
89         .to_str()
90         .map(|s| s.starts_with("."))
91         .unwrap_or(false)
92}
93
94# fn try_main() -> Result<(), Error> {
95let walker = WalkDir::new("foo").into_iter();
96for entry in walker.filter_entry(|e| !is_hidden(e)) {
97    println!("{}", entry?.path().display());
98}
99# Ok(())
100# }
101```
102
103[`filter_entry`]: struct.IntoIter.html#method.filter_entry
104*/
105
106#![deny(missing_docs)]
107#![allow(unknown_lints)]
108
109#[cfg(doctest)]
110doc_comment::doctest!("../README.md");
111
112use isideload_vfs::fs::{self, ReadDir};
113use std::cmp::{min, Ordering};
114use std::fmt;
115use std::io;
116use std::iter;
117use std::path::{Path, PathBuf};
118use std::result;
119use std::vec;
120
121use same_file::Handle;
122
123pub use crate::dent::DirEntry;
124#[cfg(unix)]
125pub use crate::dent::DirEntryExt;
126pub use crate::error::Error;
127
128mod dent;
129mod error;
130mod util;
131
132/// Like try, but for iterators that return [`Option<Result<_, _>>`].
133///
134/// [`Option<Result<_, _>>`]: https://doc.rust-lang.org/stable/std/option/enum.Option.html
135macro_rules! itry {
136    ($e:expr) => {
137        match $e {
138            Ok(v) => v,
139            Err(err) => return Some(Err(From::from(err))),
140        }
141    };
142}
143
144/// A result type for walkdir operations.
145///
146/// Note that this result type embeds the error type in this crate. This
147/// is only useful if you care about the additional information provided by
148/// the error (such as the path associated with the error or whether a loop
149/// was dectected). If you want things to Just Work, then you can use
150/// [`io::Result`] instead since the error type in this package will
151/// automatically convert to an [`io::Result`] when using the [`try!`] macro.
152///
153/// [`io::Result`]: https://doc.rust-lang.org/stable/std/io/type.Result.html
154/// [`try!`]: https://doc.rust-lang.org/stable/std/macro.try.html
155pub type Result<T> = ::std::result::Result<T, Error>;
156
157/// A builder to create an iterator for recursively walking a directory.
158///
159/// Results are returned in depth first fashion, with directories yielded
160/// before their contents. If [`contents_first`] is true, contents are yielded
161/// before their directories. The order is unspecified but if [`sort_by`] is
162/// given, directory entries are sorted according to this function. Directory
163/// entries `.` and `..` are always omitted.
164///
165/// If an error occurs at any point during iteration, then it is returned in
166/// place of its corresponding directory entry and iteration continues as
167/// normal. If an error occurs while opening a directory for reading, then it
168/// is not descended into (but the error is still yielded by the iterator).
169/// Iteration may be stopped at any time. When the iterator is destroyed, all
170/// resources associated with it are freed.
171///
172/// [`contents_first`]: struct.WalkDir.html#method.contents_first
173/// [`sort_by`]: struct.WalkDir.html#method.sort_by
174///
175/// # Usage
176///
177/// This type implements [`IntoIterator`] so that it may be used as the subject
178/// of a `for` loop. You may need to call [`into_iter`] explicitly if you want
179/// to use iterator adapters such as [`filter_entry`].
180///
181/// Idiomatic use of this type should use method chaining to set desired
182/// options. For example, this only shows entries with a depth of `1`, `2` or
183/// `3` (relative to `foo`):
184///
185/// ```no_run
186/// use walkdir::WalkDir;
187/// # use walkdir::Error;
188///
189/// # fn try_main() -> Result<(), Error> {
190/// for entry in WalkDir::new("foo").min_depth(1).max_depth(3) {
191///     println!("{}", entry?.path().display());
192/// }
193/// # Ok(())
194/// # }
195/// ```
196///
197/// [`IntoIterator`]: https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html
198/// [`into_iter`]: https://doc.rust-lang.org/nightly/core/iter/trait.IntoIterator.html#tymethod.into_iter
199/// [`filter_entry`]: struct.IntoIter.html#method.filter_entry
200///
201/// Note that the iterator by default includes the top-most directory. Since
202/// this is the only directory yielded with depth `0`, it is easy to ignore it
203/// with the [`min_depth`] setting:
204///
205/// ```no_run
206/// use walkdir::WalkDir;
207/// # use walkdir::Error;
208///
209/// # fn try_main() -> Result<(), Error> {
210/// for entry in WalkDir::new("foo").min_depth(1) {
211///     println!("{}", entry?.path().display());
212/// }
213/// # Ok(())
214/// # }
215/// ```
216///
217/// [`min_depth`]: struct.WalkDir.html#method.min_depth
218///
219/// This will only return descendents of the `foo` directory and not `foo`
220/// itself.
221///
222/// # Loops
223///
224/// This iterator (like most/all recursive directory iterators) assumes that
225/// no loops can be made with *hard* links on your file system. In particular,
226/// this would require creating a hard link to a directory such that it creates
227/// a loop. On most platforms, this operation is illegal.
228///
229/// Note that when following symbolic/soft links, loops are detected and an
230/// error is reported.
231#[derive(Debug)]
232pub struct WalkDir {
233    opts: WalkDirOptions,
234    root: PathBuf,
235}
236
237struct WalkDirOptions {
238    follow_links: bool,
239    follow_root_links: bool,
240    max_open: usize,
241    min_depth: usize,
242    max_depth: usize,
243    sorter: Option<Box<dyn FnMut(&DirEntry, &DirEntry) -> Ordering + Send + Sync + 'static>>,
244    contents_first: bool,
245    same_file_system: bool,
246}
247
248impl fmt::Debug for WalkDirOptions {
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> result::Result<(), fmt::Error> {
250        let sorter_str = if self.sorter.is_some() {
251            // FnMut isn't `Debug`
252            "Some(...)"
253        } else {
254            "None"
255        };
256        f.debug_struct("WalkDirOptions")
257            .field("follow_links", &self.follow_links)
258            .field("follow_root_link", &self.follow_root_links)
259            .field("max_open", &self.max_open)
260            .field("min_depth", &self.min_depth)
261            .field("max_depth", &self.max_depth)
262            .field("sorter", &sorter_str)
263            .field("contents_first", &self.contents_first)
264            .field("same_file_system", &self.same_file_system)
265            .finish()
266    }
267}
268
269impl WalkDir {
270    /// Create a builder for a recursive directory iterator starting at the
271    /// file path `root`. If `root` is a directory, then it is the first item
272    /// yielded by the iterator. If `root` is a file, then it is the first
273    /// and only item yielded by the iterator. If `root` is a symlink, then it
274    /// is always followed for the purposes of directory traversal. (A root
275    /// `DirEntry` still obeys its documentation with respect to symlinks and
276    /// the `follow_links` setting.)
277    pub fn new<P: AsRef<Path>>(root: P) -> Self {
278        WalkDir {
279            opts: WalkDirOptions {
280                follow_links: false,
281                follow_root_links: true,
282                max_open: 10,
283                min_depth: 0,
284                max_depth: ::std::usize::MAX,
285                sorter: None,
286                contents_first: false,
287                same_file_system: false,
288            },
289            root: root.as_ref().to_path_buf(),
290        }
291    }
292
293    /// Set the minimum depth of entries yielded by the iterator.
294    ///
295    /// The smallest depth is `0` and always corresponds to the path given
296    /// to the `new` function on this type. Its direct descendents have depth
297    /// `1`, and their descendents have depth `2`, and so on.
298    pub fn min_depth(mut self, depth: usize) -> Self {
299        self.opts.min_depth = depth;
300        if self.opts.min_depth > self.opts.max_depth {
301            self.opts.min_depth = self.opts.max_depth;
302        }
303        self
304    }
305
306    /// Set the maximum depth of entries yield by the iterator.
307    ///
308    /// The smallest depth is `0` and always corresponds to the path given
309    /// to the `new` function on this type. Its direct descendents have depth
310    /// `1`, and their descendents have depth `2`, and so on.
311    ///
312    /// Note that this will not simply filter the entries of the iterator, but
313    /// it will actually avoid descending into directories when the depth is
314    /// exceeded.
315    pub fn max_depth(mut self, depth: usize) -> Self {
316        self.opts.max_depth = depth;
317        if self.opts.max_depth < self.opts.min_depth {
318            self.opts.max_depth = self.opts.min_depth;
319        }
320        self
321    }
322
323    /// Follow symbolic links. By default, this is disabled.
324    ///
325    /// When `yes` is `true`, symbolic links are followed as if they were
326    /// normal directories and files. If a symbolic link is broken or is
327    /// involved in a loop, an error is yielded.
328    ///
329    /// When enabled, the yielded [`DirEntry`] values represent the target of
330    /// the link while the path corresponds to the link. See the [`DirEntry`]
331    /// type for more details.
332    ///
333    /// [`DirEntry`]: struct.DirEntry.html
334    pub fn follow_links(mut self, yes: bool) -> Self {
335        self.opts.follow_links = yes;
336        self
337    }
338
339    /// Follow symbolic links if these are the root of the traversal.
340    /// By default, this is enabled.
341    ///
342    /// When `yes` is `true`, symbolic links on root paths are followed
343    /// which is effective if the symbolic link points to a directory.
344    /// If a symbolic link is broken or is involved in a loop, an error is yielded
345    /// as the first entry of the traversal.
346    ///
347    /// When enabled, the yielded [`DirEntry`] values represent the target of
348    /// the link while the path corresponds to the link. See the [`DirEntry`]
349    /// type for more details, and all future entries will be contained within
350    /// the resolved directory behind the symbolic link of the root path.
351    ///
352    /// [`DirEntry`]: struct.DirEntry.html
353    pub fn follow_root_links(mut self, yes: bool) -> Self {
354        self.opts.follow_root_links = yes;
355        self
356    }
357
358    /// Set the maximum number of simultaneously open file descriptors used
359    /// by the iterator.
360    ///
361    /// `n` must be greater than or equal to `1`. If `n` is `0`, then it is set
362    /// to `1` automatically. If this is not set, then it defaults to some
363    /// reasonably low number.
364    ///
365    /// This setting has no impact on the results yielded by the iterator
366    /// (even when `n` is `1`). Instead, this setting represents a trade off
367    /// between scarce resources (file descriptors) and memory. Namely, when
368    /// the maximum number of file descriptors is reached and a new directory
369    /// needs to be opened to continue iteration, then a previous directory
370    /// handle is closed and has its unyielded entries stored in memory. In
371    /// practice, this is a satisfying trade off because it scales with respect
372    /// to the *depth* of your file tree. Therefore, low values (even `1`) are
373    /// acceptable.
374    ///
375    /// Note that this value does not impact the number of system calls made by
376    /// an exhausted iterator.
377    ///
378    /// # Platform behavior
379    ///
380    /// On Windows, if `follow_links` is enabled, then this limit is not
381    /// respected. In particular, the maximum number of file descriptors opened
382    /// is proportional to the depth of the directory tree traversed.
383    pub fn max_open(mut self, mut n: usize) -> Self {
384        if n == 0 {
385            n = 1;
386        }
387        self.opts.max_open = n;
388        self
389    }
390
391    /// Set a function for sorting directory entries with a comparator
392    /// function.
393    ///
394    /// If a compare function is set, the resulting iterator will return all
395    /// paths in sorted order. The compare function will be called to compare
396    /// entries from the same directory.
397    ///
398    /// ```rust,no_run
399    /// use std::cmp;
400    /// use std::ffi::OsString;
401    /// use walkdir::WalkDir;
402    ///
403    /// WalkDir::new("foo").sort_by(|a,b| a.file_name().cmp(b.file_name()));
404    /// ```
405    pub fn sort_by<F>(mut self, cmp: F) -> Self
406    where
407        F: FnMut(&DirEntry, &DirEntry) -> Ordering + Send + Sync + 'static,
408    {
409        self.opts.sorter = Some(Box::new(cmp));
410        self
411    }
412
413    /// Set a function for sorting directory entries with a key extraction
414    /// function.
415    ///
416    /// If a compare function is set, the resulting iterator will return all
417    /// paths in sorted order. The compare function will be called to compare
418    /// entries from the same directory.
419    ///
420    /// ```rust,no_run
421    /// use std::cmp;
422    /// use std::ffi::OsString;
423    /// use walkdir::WalkDir;
424    ///
425    /// WalkDir::new("foo").sort_by_key(|a| a.file_name().to_owned());
426    /// ```
427    pub fn sort_by_key<K, F>(self, mut cmp: F) -> Self
428    where
429        F: FnMut(&DirEntry) -> K + Send + Sync + 'static,
430        K: Ord,
431    {
432        self.sort_by(move |a, b| cmp(a).cmp(&cmp(b)))
433    }
434
435    /// Sort directory entries by file name, to ensure a deterministic order.
436    ///
437    /// This is a convenience function for calling `Self::sort_by()`.
438    ///
439    /// ```rust,no_run
440    /// use walkdir::WalkDir;
441    ///
442    /// WalkDir::new("foo").sort_by_file_name();
443    /// ```
444    pub fn sort_by_file_name(self) -> Self {
445        self.sort_by(|a, b| a.file_name().cmp(b.file_name()))
446    }
447
448    /// Yield a directory's contents before the directory itself. By default,
449    /// this is disabled.
450    ///
451    /// When `yes` is `false` (as is the default), the directory is yielded
452    /// before its contents are read. This is useful when, e.g. you want to
453    /// skip processing of some directories.
454    ///
455    /// When `yes` is `true`, the iterator yields the contents of a directory
456    /// before yielding the directory itself. This is useful when, e.g. you
457    /// want to recursively delete a directory.
458    ///
459    /// # Example
460    ///
461    /// Assume the following directory tree:
462    ///
463    /// ```text
464    /// foo/
465    ///   abc/
466    ///     qrs
467    ///     tuv
468    ///   def/
469    /// ```
470    ///
471    /// With contents_first disabled (the default), the following code visits
472    /// the directory tree in depth-first order:
473    ///
474    /// ```no_run
475    /// use walkdir::WalkDir;
476    ///
477    /// for entry in WalkDir::new("foo") {
478    ///     let entry = entry.unwrap();
479    ///     println!("{}", entry.path().display());
480    /// }
481    ///
482    /// // foo
483    /// // foo/abc
484    /// // foo/abc/qrs
485    /// // foo/abc/tuv
486    /// // foo/def
487    /// ```
488    ///
489    /// With contents_first enabled:
490    ///
491    /// ```no_run
492    /// use walkdir::WalkDir;
493    ///
494    /// for entry in WalkDir::new("foo").contents_first(true) {
495    ///     let entry = entry.unwrap();
496    ///     println!("{}", entry.path().display());
497    /// }
498    ///
499    /// // foo/abc/qrs
500    /// // foo/abc/tuv
501    /// // foo/abc
502    /// // foo/def
503    /// // foo
504    /// ```
505    pub fn contents_first(mut self, yes: bool) -> Self {
506        self.opts.contents_first = yes;
507        self
508    }
509
510    /// Do not cross file system boundaries.
511    ///
512    /// When this option is enabled, directory traversal will not descend into
513    /// directories that are on a different file system from the root path.
514    ///
515    /// Currently, this option is only supported on Unix and Windows. If this
516    /// option is used on an unsupported platform, then directory traversal
517    /// will immediately return an error and will not yield any entries.
518    pub fn same_file_system(mut self, yes: bool) -> Self {
519        self.opts.same_file_system = yes;
520        self
521    }
522}
523
524impl IntoIterator for WalkDir {
525    type Item = Result<DirEntry>;
526    type IntoIter = IntoIter;
527
528    fn into_iter(self) -> IntoIter {
529        IntoIter {
530            opts: self.opts,
531            start: Some(self.root),
532            stack_list: vec![],
533            stack_path: vec![],
534            oldest_opened: 0,
535            depth: 0,
536            deferred_dirs: vec![],
537            root_device: None,
538        }
539    }
540}
541
542/// An iterator for recursively descending into a directory.
543///
544/// A value with this type must be constructed with the [`WalkDir`] type, which
545/// uses a builder pattern to set options such as min/max depth, max open file
546/// descriptors and whether the iterator should follow symbolic links. After
547/// constructing a `WalkDir`, call [`.into_iter()`] at the end of the chain.
548///
549/// The order of elements yielded by this iterator is unspecified.
550///
551/// [`WalkDir`]: struct.WalkDir.html
552/// [`.into_iter()`]: struct.WalkDir.html#into_iter.v
553#[derive(Debug)]
554pub struct IntoIter {
555    /// Options specified in the builder. Depths, max fds, etc.
556    opts: WalkDirOptions,
557    /// The start path.
558    ///
559    /// This is only `Some(...)` at the beginning. After the first iteration,
560    /// this is always `None`.
561    start: Option<PathBuf>,
562    /// A stack of open (up to max fd) or closed handles to directories.
563    /// An open handle is a plain [`fs::ReadDir`] while a closed handle is
564    /// a `Vec<fs::DirEntry>` corresponding to the as-of-yet consumed entries.
565    ///
566    /// [`fs::ReadDir`]: https://doc.rust-lang.org/stable/std/fs/struct.ReadDir.html
567    stack_list: Vec<DirList>,
568    /// A stack of file paths.
569    ///
570    /// This is *only* used when [`follow_links`] is enabled. In all other
571    /// cases this stack is empty.
572    ///
573    /// [`follow_links`]: struct.WalkDir.html#method.follow_links
574    stack_path: Vec<Ancestor>,
575    /// An index into `stack_list` that points to the oldest open directory
576    /// handle. If the maximum fd limit is reached and a new directory needs to
577    /// be read, the handle at this index is closed before the new directory is
578    /// opened.
579    oldest_opened: usize,
580    /// The current depth of iteration (the length of the stack at the
581    /// beginning of each iteration).
582    depth: usize,
583    /// A list of DirEntries corresponding to directories, that are
584    /// yielded after their contents has been fully yielded. This is only
585    /// used when `contents_first` is enabled.
586    deferred_dirs: Vec<DirEntry>,
587    /// The device of the root file path when the first call to `next` was
588    /// made.
589    ///
590    /// If the `same_file_system` option isn't enabled, then this is always
591    /// `None`. Conversely, if it is enabled, this is always `Some(...)` after
592    /// handling the root path.
593    root_device: Option<u64>,
594}
595
596/// An ancestor is an item in the directory tree traversed by walkdir, and is
597/// used to check for loops in the tree when traversing symlinks.
598#[derive(Debug)]
599struct Ancestor {
600    /// The path of this ancestor.
601    path: PathBuf,
602    /// An open file to this ancesor. This is only used on Windows where
603    /// opening a file handle appears to be quite expensive, so we choose to
604    /// cache it. This comes at the cost of not respecting the file descriptor
605    /// limit set by the user.
606    #[cfg(windows)]
607    handle: Handle,
608}
609
610impl Ancestor {
611    /// Create a new ancestor from the given directory path.
612    #[cfg(windows)]
613    fn new(dent: &DirEntry) -> io::Result<Ancestor> {
614        let handle = Handle::from_path(dent.path())?;
615        Ok(Ancestor {
616            path: dent.path().to_path_buf(),
617            handle,
618        })
619    }
620
621    /// Create a new ancestor from the given directory path.
622    #[cfg(not(windows))]
623    fn new(dent: &DirEntry) -> io::Result<Ancestor> {
624        Ok(Ancestor {
625            path: dent.path().to_path_buf(),
626        })
627    }
628
629    /// Returns true if and only if the given open file handle corresponds to
630    /// the same directory as this ancestor.
631    #[cfg(windows)]
632    fn is_same(&self, child: &Handle) -> io::Result<bool> {
633        Ok(child == &self.handle)
634    }
635
636    /// Returns true if and only if the given open file handle corresponds to
637    /// the same directory as this ancestor.
638    #[cfg(not(windows))]
639    fn is_same(&self, child: &Handle) -> io::Result<bool> {
640        Ok(child == &Handle::from_path(&self.path)?)
641    }
642}
643
644/// A sequence of unconsumed directory entries.
645///
646/// This represents the opened or closed state of a directory handle. When
647/// open, future entries are read by iterating over the raw `fs::ReadDir`.
648/// When closed, all future entries are read into memory. Iteration then
649/// proceeds over a [`Vec<fs::DirEntry>`].
650///
651/// [`fs::ReadDir`]: https://doc.rust-lang.org/stable/std/fs/struct.ReadDir.html
652/// [`Vec<fs::DirEntry>`]: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html
653#[derive(Debug)]
654enum DirList {
655    /// An opened handle.
656    ///
657    /// This includes the depth of the handle itself.
658    ///
659    /// If there was an error with the initial [`fs::read_dir`] call, then it
660    /// is stored here. (We use an [`Option<...>`] to make yielding the error
661    /// exactly once simpler.)
662    ///
663    /// [`fs::read_dir`]: https://doc.rust-lang.org/stable/std/fs/fn.read_dir.html
664    /// [`Option<...>`]: https://doc.rust-lang.org/stable/std/option/enum.Option.html
665    Opened {
666        depth: usize,
667        it: result::Result<ReadDir, Option<Error>>,
668    },
669    /// A closed handle.
670    ///
671    /// All remaining directory entries are read into memory.
672    Closed(vec::IntoIter<Result<DirEntry>>),
673}
674
675impl Iterator for IntoIter {
676    type Item = Result<DirEntry>;
677    /// Advances the iterator and returns the next value.
678    ///
679    /// # Errors
680    ///
681    /// If the iterator fails to retrieve the next value, this method returns
682    /// an error value. The error will be wrapped in an Option::Some.
683    fn next(&mut self) -> Option<Result<DirEntry>> {
684        if let Some(start) = self.start.take() {
685            if self.opts.same_file_system {
686                let result =
687                    util::device_num(&start).map_err(|e| Error::from_path(0, start.clone(), e));
688                self.root_device = Some(itry!(result));
689            }
690            let dent = itry!(DirEntry::from_path(0, start, false));
691            if let Some(result) = self.handle_entry(dent) {
692                return Some(result);
693            }
694        }
695        while !self.stack_list.is_empty() {
696            self.depth = self.stack_list.len();
697            if let Some(dentry) = self.get_deferred_dir() {
698                return Some(Ok(dentry));
699            }
700            if self.depth > self.opts.max_depth {
701                // If we've exceeded the max depth, pop the current dir
702                // so that we don't descend.
703                self.pop();
704                continue;
705            }
706            // Unwrap is safe here because we've verified above that
707            // `self.stack_list` is not empty
708            let next = self
709                .stack_list
710                .last_mut()
711                .expect("BUG: stack should be non-empty")
712                .next();
713            match next {
714                None => self.pop(),
715                Some(Err(err)) => return Some(Err(err)),
716                Some(Ok(dent)) => {
717                    if let Some(result) = self.handle_entry(dent) {
718                        return Some(result);
719                    }
720                }
721            }
722        }
723        if self.opts.contents_first {
724            self.depth = self.stack_list.len();
725            if let Some(dentry) = self.get_deferred_dir() {
726                return Some(Ok(dentry));
727            }
728        }
729        None
730    }
731}
732
733impl IntoIter {
734    /// Skips the current directory.
735    ///
736    /// This causes the iterator to stop traversing the contents of the least
737    /// recently yielded directory. This means any remaining entries in that
738    /// directory will be skipped (including sub-directories).
739    ///
740    /// Note that the ergonomics of this method are questionable since it
741    /// borrows the iterator mutably. Namely, you must write out the looping
742    /// condition manually. For example, to skip hidden entries efficiently on
743    /// unix systems:
744    ///
745    /// ```no_run
746    /// use walkdir::{DirEntry, WalkDir};
747    ///
748    /// fn is_hidden(entry: &DirEntry) -> bool {
749    ///     entry.file_name()
750    ///          .to_str()
751    ///          .map(|s| s.starts_with("."))
752    ///          .unwrap_or(false)
753    /// }
754    ///
755    /// let mut it = WalkDir::new("foo").into_iter();
756    /// loop {
757    ///     let entry = match it.next() {
758    ///         None => break,
759    ///         Some(Err(err)) => panic!("ERROR: {}", err),
760    ///         Some(Ok(entry)) => entry,
761    ///     };
762    ///     if is_hidden(&entry) {
763    ///         if entry.file_type().is_dir() {
764    ///             it.skip_current_dir();
765    ///         }
766    ///         continue;
767    ///     }
768    ///     println!("{}", entry.path().display());
769    /// }
770    /// ```
771    ///
772    /// You may find it more convenient to use the [`filter_entry`] iterator
773    /// adapter. (See its documentation for the same example functionality as
774    /// above.)
775    ///
776    /// [`filter_entry`]: #method.filter_entry
777    pub fn skip_current_dir(&mut self) {
778        if !self.stack_list.is_empty() {
779            self.pop();
780        }
781    }
782
783    /// Yields only entries which satisfy the given predicate and skips
784    /// descending into directories that do not satisfy the given predicate.
785    ///
786    /// The predicate is applied to all entries. If the predicate is
787    /// true, iteration carries on as normal. If the predicate is false, the
788    /// entry is ignored and if it is a directory, it is not descended into.
789    ///
790    /// This is often more convenient to use than [`skip_current_dir`]. For
791    /// example, to skip hidden files and directories efficiently on unix
792    /// systems:
793    ///
794    /// ```no_run
795    /// use walkdir::{DirEntry, WalkDir};
796    /// # use walkdir::Error;
797    ///
798    /// fn is_hidden(entry: &DirEntry) -> bool {
799    ///     entry.file_name()
800    ///          .to_str()
801    ///          .map(|s| s.starts_with("."))
802    ///          .unwrap_or(false)
803    /// }
804    ///
805    /// # fn try_main() -> Result<(), Error> {
806    /// for entry in WalkDir::new("foo")
807    ///                      .into_iter()
808    ///                      .filter_entry(|e| !is_hidden(e)) {
809    ///     println!("{}", entry?.path().display());
810    /// }
811    /// # Ok(())
812    /// # }
813    /// ```
814    ///
815    /// Note that the iterator will still yield errors for reading entries that
816    /// may not satisfy the predicate.
817    ///
818    /// Note that entries skipped with [`min_depth`] and [`max_depth`] are not
819    /// passed to this predicate.
820    ///
821    /// Note that if the iterator has `contents_first` enabled, then this
822    /// method is no different than calling the standard `Iterator::filter`
823    /// method (because directory entries are yielded after they've been
824    /// descended into).
825    ///
826    /// [`skip_current_dir`]: #method.skip_current_dir
827    /// [`min_depth`]: struct.WalkDir.html#method.min_depth
828    /// [`max_depth`]: struct.WalkDir.html#method.max_depth
829    pub fn filter_entry<P>(self, predicate: P) -> FilterEntry<Self, P>
830    where
831        P: FnMut(&DirEntry) -> bool,
832    {
833        FilterEntry {
834            it: self,
835            predicate,
836        }
837    }
838
839    fn handle_entry(&mut self, mut dent: DirEntry) -> Option<Result<DirEntry>> {
840        if self.opts.follow_links && dent.file_type().is_symlink() {
841            dent = itry!(self.follow(dent));
842        }
843        let is_normal_dir = !dent.file_type().is_symlink() && dent.is_dir();
844        if is_normal_dir {
845            if self.opts.same_file_system && dent.depth() > 0 {
846                if itry!(self.is_same_file_system(&dent)) {
847                    itry!(self.push(&dent));
848                }
849            } else {
850                itry!(self.push(&dent));
851            }
852        } else if dent.depth() == 0 && dent.file_type().is_symlink() && self.opts.follow_root_links
853        {
854            // As a special case, if we are processing a root entry, then we
855            // always follow it even if it's a symlink and follow_links is
856            // false. We are careful to not let this change the semantics of
857            // the DirEntry however. Namely, the DirEntry should still respect
858            // the follow_links setting. When it's disabled, it should report
859            // itself as a symlink. When it's enabled, it should always report
860            // itself as the target.
861            let md = itry!(fs::metadata(dent.path())
862                .map_err(|err| { Error::from_path(dent.depth(), dent.path().to_path_buf(), err) }));
863            if md.file_type().is_dir() {
864                itry!(self.push(&dent));
865            }
866        }
867        if is_normal_dir && self.opts.contents_first {
868            self.deferred_dirs.push(dent);
869            None
870        } else if self.skippable() {
871            None
872        } else {
873            Some(Ok(dent))
874        }
875    }
876
877    fn get_deferred_dir(&mut self) -> Option<DirEntry> {
878        if self.opts.contents_first {
879            if self.depth < self.deferred_dirs.len() {
880                // Unwrap is safe here because we've guaranteed that
881                // `self.deferred_dirs.len()` can never be less than 1
882                let deferred: DirEntry = self
883                    .deferred_dirs
884                    .pop()
885                    .expect("BUG: deferred_dirs should be non-empty");
886                if !self.skippable() {
887                    return Some(deferred);
888                }
889            }
890        }
891        None
892    }
893
894    fn push(&mut self, dent: &DirEntry) -> Result<()> {
895        // Make room for another open file descriptor if we've hit the max.
896        let free = self
897            .stack_list
898            .len()
899            .checked_sub(self.oldest_opened)
900            .unwrap();
901        if free == self.opts.max_open {
902            self.stack_list[self.oldest_opened].close();
903        }
904        // Open a handle to reading the directory's entries.
905        let rd = fs::read_dir(dent.path())
906            .map_err(|err| Some(Error::from_path(self.depth, dent.path().to_path_buf(), err)));
907        let mut list = DirList::Opened {
908            depth: self.depth,
909            it: rd,
910        };
911        if let Some(ref mut cmp) = self.opts.sorter {
912            let mut entries: Vec<_> = list.collect();
913            entries.sort_by(|a, b| match (a, b) {
914                (&Ok(ref a), &Ok(ref b)) => cmp(a, b),
915                (&Err(_), &Err(_)) => Ordering::Equal,
916                (&Ok(_), &Err(_)) => Ordering::Greater,
917                (&Err(_), &Ok(_)) => Ordering::Less,
918            });
919            list = DirList::Closed(entries.into_iter());
920        }
921        if self.opts.follow_links {
922            let ancestor = Ancestor::new(&dent).map_err(|err| Error::from_io(self.depth, err))?;
923            self.stack_path.push(ancestor);
924        }
925        // We push this after stack_path since creating the Ancestor can fail.
926        // If it fails, then we return the error and won't descend.
927        self.stack_list.push(list);
928        // If we had to close out a previous directory stream, then we need to
929        // increment our index the oldest still-open stream. We do this only
930        // after adding to our stack, in order to ensure that the oldest_opened
931        // index remains valid. The worst that can happen is that an already
932        // closed stream will be closed again, which is a no-op.
933        //
934        // We could move the close of the stream above into this if-body, but
935        // then we would have more than the maximum number of file descriptors
936        // open at a particular point in time.
937        if free == self.opts.max_open {
938            // Unwrap is safe here because self.oldest_opened is guaranteed to
939            // never be greater than `self.stack_list.len()`, which implies
940            // that the subtraction won't underflow and that adding 1 will
941            // never overflow.
942            self.oldest_opened = self.oldest_opened.checked_add(1).unwrap();
943        }
944        Ok(())
945    }
946
947    fn pop(&mut self) {
948        self.stack_list
949            .pop()
950            .expect("BUG: cannot pop from empty stack");
951        if self.opts.follow_links {
952            self.stack_path
953                .pop()
954                .expect("BUG: list/path stacks out of sync");
955        }
956        // If everything in the stack is already closed, then there is
957        // room for at least one more open descriptor and it will
958        // always be at the top of the stack.
959        self.oldest_opened = min(self.oldest_opened, self.stack_list.len());
960    }
961
962    fn follow(&self, mut dent: DirEntry) -> Result<DirEntry> {
963        dent = DirEntry::from_path(self.depth, dent.path().to_path_buf(), true)?;
964        // The only way a symlink can cause a loop is if it points
965        // to a directory. Otherwise, it always points to a leaf
966        // and we can omit any loop checks.
967        if dent.is_dir() {
968            self.check_loop(dent.path())?;
969        }
970        Ok(dent)
971    }
972
973    fn check_loop<P: AsRef<Path>>(&self, child: P) -> Result<()> {
974        let hchild = Handle::from_path(&child).map_err(|err| Error::from_io(self.depth, err))?;
975        for ancestor in self.stack_path.iter().rev() {
976            let is_same = ancestor
977                .is_same(&hchild)
978                .map_err(|err| Error::from_io(self.depth, err))?;
979            if is_same {
980                return Err(Error::from_loop(self.depth, &ancestor.path, child.as_ref()));
981            }
982        }
983        Ok(())
984    }
985
986    fn is_same_file_system(&mut self, dent: &DirEntry) -> Result<bool> {
987        let dent_device =
988            util::device_num(dent.path()).map_err(|err| Error::from_entry(dent, err))?;
989        Ok(self
990            .root_device
991            .map(|d| d == dent_device)
992            .expect("BUG: called is_same_file_system without root device"))
993    }
994
995    fn skippable(&self) -> bool {
996        self.depth < self.opts.min_depth || self.depth > self.opts.max_depth
997    }
998}
999
1000impl iter::FusedIterator for IntoIter {}
1001
1002impl DirList {
1003    fn close(&mut self) {
1004        if let DirList::Opened { .. } = *self {
1005            *self = DirList::Closed(self.collect::<Vec<_>>().into_iter());
1006        }
1007    }
1008}
1009
1010impl Iterator for DirList {
1011    type Item = Result<DirEntry>;
1012
1013    #[inline(always)]
1014    fn next(&mut self) -> Option<Result<DirEntry>> {
1015        match *self {
1016            DirList::Closed(ref mut it) => it.next(),
1017            DirList::Opened { depth, ref mut it } => match *it {
1018                Err(ref mut err) => err.take().map(Err),
1019                Ok(ref mut rd) => rd.next().map(|r| match r {
1020                    Ok(r) => DirEntry::from_entry(depth + 1, &r),
1021                    Err(err) => Err(Error::from_io(depth + 1, err)),
1022                }),
1023            },
1024        }
1025    }
1026}
1027
1028/// A recursive directory iterator that skips entries.
1029///
1030/// Values of this type are created by calling [`.filter_entry()`] on an
1031/// `IntoIter`, which is formed by calling [`.into_iter()`] on a `WalkDir`.
1032///
1033/// Directories that fail the predicate `P` are skipped. Namely, they are
1034/// never yielded and never descended into.
1035///
1036/// Entries that are skipped with the [`min_depth`] and [`max_depth`] options
1037/// are not passed through this filter.
1038///
1039/// If opening a handle to a directory resulted in an error, then it is yielded
1040/// and no corresponding call to the predicate is made.
1041///
1042/// Type parameter `I` refers to the underlying iterator and `P` refers to the
1043/// predicate, which is usually `FnMut(&DirEntry) -> bool`.
1044///
1045/// [`.filter_entry()`]: struct.IntoIter.html#method.filter_entry
1046/// [`.into_iter()`]: struct.WalkDir.html#into_iter.v
1047/// [`min_depth`]: struct.WalkDir.html#method.min_depth
1048/// [`max_depth`]: struct.WalkDir.html#method.max_depth
1049#[derive(Debug)]
1050pub struct FilterEntry<I, P> {
1051    it: I,
1052    predicate: P,
1053}
1054
1055impl<P> Iterator for FilterEntry<IntoIter, P>
1056where
1057    P: FnMut(&DirEntry) -> bool,
1058{
1059    type Item = Result<DirEntry>;
1060
1061    /// Advances the iterator and returns the next value.
1062    ///
1063    /// # Errors
1064    ///
1065    /// If the iterator fails to retrieve the next value, this method returns
1066    /// an error value. The error will be wrapped in an `Option::Some`.
1067    fn next(&mut self) -> Option<Result<DirEntry>> {
1068        loop {
1069            let dent = match self.it.next() {
1070                None => return None,
1071                Some(result) => itry!(result),
1072            };
1073            if !(self.predicate)(&dent) {
1074                if dent.is_dir() {
1075                    self.it.skip_current_dir();
1076                }
1077                continue;
1078            }
1079            return Some(Ok(dent));
1080        }
1081    }
1082}
1083
1084impl<P> iter::FusedIterator for FilterEntry<IntoIter, P> where P: FnMut(&DirEntry) -> bool {}
1085
1086impl<P> FilterEntry<IntoIter, P>
1087where
1088    P: FnMut(&DirEntry) -> bool,
1089{
1090    /// Yields only entries which satisfy the given predicate and skips
1091    /// descending into directories that do not satisfy the given predicate.
1092    ///
1093    /// The predicate is applied to all entries. If the predicate is
1094    /// true, iteration carries on as normal. If the predicate is false, the
1095    /// entry is ignored and if it is a directory, it is not descended into.
1096    ///
1097    /// This is often more convenient to use than [`skip_current_dir`]. For
1098    /// example, to skip hidden files and directories efficiently on unix
1099    /// systems:
1100    ///
1101    /// ```no_run
1102    /// use walkdir::{DirEntry, WalkDir};
1103    /// # use walkdir::Error;
1104    ///
1105    /// fn is_hidden(entry: &DirEntry) -> bool {
1106    ///     entry.file_name()
1107    ///          .to_str()
1108    ///          .map(|s| s.starts_with("."))
1109    ///          .unwrap_or(false)
1110    /// }
1111    ///
1112    /// # fn try_main() -> Result<(), Error> {
1113    /// for entry in WalkDir::new("foo")
1114    ///                      .into_iter()
1115    ///                      .filter_entry(|e| !is_hidden(e)) {
1116    ///     println!("{}", entry?.path().display());
1117    /// }
1118    /// # Ok(())
1119    /// # }
1120    /// ```
1121    ///
1122    /// Note that the iterator will still yield errors for reading entries that
1123    /// may not satisfy the predicate.
1124    ///
1125    /// Note that entries skipped with [`min_depth`] and [`max_depth`] are not
1126    /// passed to this predicate.
1127    ///
1128    /// Note that if the iterator has `contents_first` enabled, then this
1129    /// method is no different than calling the standard `Iterator::filter`
1130    /// method (because directory entries are yielded after they've been
1131    /// descended into).
1132    ///
1133    /// [`skip_current_dir`]: #method.skip_current_dir
1134    /// [`min_depth`]: struct.WalkDir.html#method.min_depth
1135    /// [`max_depth`]: struct.WalkDir.html#method.max_depth
1136    pub fn filter_entry(self, predicate: P) -> FilterEntry<Self, P> {
1137        FilterEntry {
1138            it: self,
1139            predicate,
1140        }
1141    }
1142
1143    /// Skips the current directory.
1144    ///
1145    /// This causes the iterator to stop traversing the contents of the least
1146    /// recently yielded directory. This means any remaining entries in that
1147    /// directory will be skipped (including sub-directories).
1148    ///
1149    /// Note that the ergonomics of this method are questionable since it
1150    /// borrows the iterator mutably. Namely, you must write out the looping
1151    /// condition manually. For example, to skip hidden entries efficiently on
1152    /// unix systems:
1153    ///
1154    /// ```no_run
1155    /// use walkdir::{DirEntry, WalkDir};
1156    ///
1157    /// fn is_hidden(entry: &DirEntry) -> bool {
1158    ///     entry.file_name()
1159    ///          .to_str()
1160    ///          .map(|s| s.starts_with("."))
1161    ///          .unwrap_or(false)
1162    /// }
1163    ///
1164    /// let mut it = WalkDir::new("foo").into_iter();
1165    /// loop {
1166    ///     let entry = match it.next() {
1167    ///         None => break,
1168    ///         Some(Err(err)) => panic!("ERROR: {}", err),
1169    ///         Some(Ok(entry)) => entry,
1170    ///     };
1171    ///     if is_hidden(&entry) {
1172    ///         if entry.file_type().is_dir() {
1173    ///             it.skip_current_dir();
1174    ///         }
1175    ///         continue;
1176    ///     }
1177    ///     println!("{}", entry.path().display());
1178    /// }
1179    /// ```
1180    ///
1181    /// You may find it more convenient to use the [`filter_entry`] iterator
1182    /// adapter. (See its documentation for the same example functionality as
1183    /// above.)
1184    ///
1185    /// [`filter_entry`]: #method.filter_entry
1186    pub fn skip_current_dir(&mut self) {
1187        self.it.skip_current_dir();
1188    }
1189}