1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
#![warn(clippy::all)]

//! Filesystem walk.
//!
//! - Performed in parallel using rayon
//! - Entries streamed in sorted order
//! - Custom sort/filter/skip
//!
//! # Example
//!
//! Recursively iterate over the "foo" directory sorting by name:
//!
//! ```no_run
//! # use std::io::Error;
//! use jwalk::{WalkDir};
//!
//! # fn try_main() -> Result<(), Error> {
//! for entry in WalkDir::new("foo").sort(true) {
//!   println!("{}", entry?.path().display());
//! }
//! # Ok(())
//! # }
//! ```

mod core;

use std::cmp::Ordering;
use std::ffi::OsStr;
use std::fs;
use std::io::Result;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use crate::core::ReadDir;

pub use crate::core::{DirEntry, DirEntryIter, ReadDirSpec};

/// Builder for walking a directory.
pub struct WalkDir {
  root: PathBuf,
  options: WalkDirOptions,
}

type ProcessEntriesFunction = Fn(&mut Vec<Result<DirEntry>>) + Send + Sync + 'static;

struct WalkDirOptions {
  sort: bool,
  max_depth: usize,
  skip_hidden: bool,
  num_threads: usize,
  preload_metadata: bool,
  process_entries: Option<Arc<ProcessEntriesFunction>>,
}

impl WalkDir {
  /// Create a builder for a recursive directory iterator starting at the file
  /// path root. If root is a directory, then it is the first item yielded by
  /// the iterator. If root is a file, then it is the first and only item
  /// yielded by the iterator.
  pub fn new<P: AsRef<Path>>(root: P) -> Self {
    WalkDir {
      root: root.as_ref().to_path_buf(),
      options: WalkDirOptions {
        sort: false,
        max_depth: ::std::usize::MAX,
        num_threads: 0,
        skip_hidden: true,
        preload_metadata: false,
        process_entries: None,
      },
    }
  }

  /// Sort entries by `file_name` per directory. Defaults to `false`. Use
  /// [`process_entries`](struct.WalkDir.html#method.process_entries) for custom
  /// sorting or filtering.
  pub fn sort(mut self, sort: bool) -> Self {
    self.options.sort = sort;
    self
  }

  /// Skip hidden entries. Enabled by default.
  pub fn skip_hidden(mut self, skip_hidden: bool) -> Self {
    self.options.skip_hidden = skip_hidden;
    self
  }

  /// Preload metadata before yeilding entries. When running in parrallel the
  /// metadata is loaded in rayon's thread pool.
  pub fn preload_metadata(mut self, preload_metadata: bool) -> Self {
    self.options.preload_metadata = preload_metadata;
    self
  }

  /// Maximum depth of entries yielded by the iterator. `0` corresponds to the
  /// root path of this walk.
  ///
  /// A depth < 2 will automatically change `thread_count` to 1. Parrallelism
  /// happens at the `fs::read_dir` level. It only makes sense to use multiple
  /// threads when reading more then one directory.
  pub fn max_depth(mut self, depth: usize) -> Self {
    self.options.max_depth = depth;
    if depth == 1 {
      self.options.num_threads = 1;
    }
    self
  }

  /// - `0` Use rayon global pool.
  /// - `1` Perform walk on calling thread.
  /// - `n > 1` Construct a new rayon ThreadPool to perform the walk.
  pub fn num_threads(mut self, n: usize) -> Self {
    self.options.num_threads = n;
    self
  }

  /// A callback function to process (sort/filter/skip) each directory of
  /// entries before they are yeilded. Modify the given array to sort/filter
  /// entries. Use [`entry.content_spec =
  /// None`](struct.DirEntry.html#field.content_spec) to yeild an entry but skip
  /// reading its contents.
  pub fn process_entries<F>(mut self, process_by: F) -> Self
  where
    F: Fn(&mut Vec<Result<DirEntry>>) + Send + Sync + 'static,
  {
    self.options.process_entries = Some(Arc::new(process_by));
    self
  }
}

impl IntoIterator for WalkDir {
  type Item = Result<DirEntry>;
  type IntoIter = DirEntryIter;

  fn into_iter(self) -> DirEntryIter {
    let sort = self.options.sort;
    let num_threads = self.options.num_threads;
    let skip_hidden = self.options.skip_hidden;
    let max_depth = self.options.max_depth;
    let preload_metadata = self.options.preload_metadata;
    let process_entries = self.options.process_entries.clone();

    core::walk(&self.root, num_threads, move |read_dir_spec| {
      let depth = read_dir_spec.depth + 1;
      let mut dir_entry_results: Vec<_> = fs::read_dir(&read_dir_spec.path)?
        .filter_map(|dir_entry_result| {
          let dir_entry = match dir_entry_result {
            Ok(dir_entry) => dir_entry,
            Err(err) => return Some(Err(err)),
          };

          let file_name = dir_entry.file_name();
          if skip_hidden && is_hidden(&file_name) {
            return None;
          }

          let file_type = dir_entry.file_type();
          let metadata = if preload_metadata {
            Some(dir_entry.metadata())
          } else {
            None
          };

          let content_spec = match file_type {
            Ok(file_type) => {
              if file_type.is_dir() && depth < max_depth {
                let path = read_dir_spec.path.join(dir_entry.file_name());
                Some(Arc::new(ReadDirSpec::new(path, depth, None)))
              } else {
                None
              }
            }
            Err(_) => None,
          };

          Some(Ok(DirEntry::new(
            depth,
            file_name,
            file_type,
            metadata,
            Some(read_dir_spec.clone()),
            content_spec,
          )))
        })
        .collect();

      if sort {
        dir_entry_results.sort_by(|a, b| match (a, b) {
          (Ok(a), Ok(b)) => a.file_name.cmp(&b.file_name),
          (Ok(_), Err(_)) => Ordering::Less,
          (Err(_), Ok(_)) => Ordering::Greater,
          (Err(_), Err(_)) => Ordering::Equal,
        });
      }

      if let Some(process_entries) = process_entries.as_ref() {
        process_entries(&mut dir_entry_results);
      }

      Ok(ReadDir::new(dir_entry_results))
    })
  }
}

impl Clone for WalkDirOptions {
  fn clone(&self) -> WalkDirOptions {
    WalkDirOptions {
      sort: false,
      max_depth: self.max_depth,
      num_threads: self.num_threads,
      skip_hidden: self.skip_hidden,
      preload_metadata: self.preload_metadata,
      process_entries: self.process_entries.clone(),
    }
  }
}

fn is_hidden(file_name: &OsStr) -> bool {
  file_name
    .to_str()
    .map(|s| s.starts_with('.'))
    .unwrap_or(false)
}