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
/*!
Crate `finder` is a very simple and lightweight file searcher with the filtering of files.
It provides an efficient implementation of recursive file search.

To use this crate, add `finder` as a dependency to your project's
`Cargo.toml`:

```toml
[dependencies]
finder = "0.1"
```

# Example

The following code recursively search all files in `/foo` and `/bar` diresctories:

```no_run
extern crate finder;

use finder::Finder;

fn main() {
  let finders = Finder::new("/foo:/bar");
  for i in finders.into_iter() {
    println!("{}", i.path().to_str().unwrap());
  }
}
```

# Example with filter

The following code recursively search `.ttf` and `.ttc` files in `/foo` and `/bar` diresctories:

```no_run
extern crate finder;

use std::fs::DirEntry;

use finder::Finder;

fn is_font_file(e: &DirEntry) -> bool {
  if let Some(s) = e.path().file_name() {
    let name = String::from(s.to_str().unwrap());

    if (name.ends_with(".ttf") || name.ends_with(".ttc")) {
      return true;
    }
  }

  false
}

fn main() {
  let finders = Finder::new("/foo:/bar");
  for i in finders.filter(&is_font_file).into_iter() {
    println!("{}", i.path().to_str().unwrap());
  }
}
```

*/

extern crate log;

use log::warn;
use std::fs::{self, DirEntry, ReadDir};
use std::io;
use std::path::{Path, PathBuf};

struct FinderOptions {
  filter: &'static Fn(&DirEntry) -> bool,
}

pub struct Finder {
  opts: FinderOptions,
  root: PathBuf,
}

impl Finder {
  pub fn new<P: AsRef<Path>>(root: P) -> Self {
    Finder {
      opts: FinderOptions { filter: &|_e| true },
      root: root.as_ref().to_path_buf(),
    }
  }

  pub fn filter(mut self, filter: &'static Fn(&DirEntry) -> bool) -> Self {
    self.opts.filter = filter;
    self
  }
}

impl IntoIterator for Finder {
  type Item = DirEntry;
  type IntoIter = IntoIter;

  fn into_iter(self) -> IntoIter {
    IntoIter {
      opts: self.opts,
      start: Some(self.root),
      entries: vec![],
    }
  }
}

pub struct IntoIter {
  opts: FinderOptions,
  start: Option<PathBuf>,
  entries: Vec<List>,
}

impl Iterator for IntoIter {
  type Item = DirEntry;

  fn next(&mut self) -> Option<DirEntry> {
    if self.entries.is_empty() {
      if let Some(start) = self.start.take() {
        for path in String::from(start.to_str().unwrap()).split(":") {
          self.handle_entry(&Path::new(path).to_path_buf());
        }
      }
    }

    while !self.entries.is_empty() {
      let next = self
        .entries
        .last_mut()
        .expect("BUG: dirs should be non-empty")
        .next();
      match next {
        None => self.entries.pop(),
        Some(entry) => {
          let e = entry.unwrap();
          self.handle_entry(&e.path());
          if !e.path().is_dir() && (self.opts.filter)(&e) {
            return Some(e);
          }

          None
        }
      };
    }

    None
  }
}

impl IntoIter {
  pub fn handle_entry(&mut self, directory: &PathBuf) {
    let rd = fs::read_dir(directory);
    let list = List::Files { it: rd };
    self.entries.push(list);
  }
}

#[derive(Debug)]
enum List {
  Files { it: Result<ReadDir, io::Error> },
}

impl Iterator for List {
  type Item = Result<DirEntry, io::Error>;

  #[inline(always)]
  fn next(&mut self) -> Option<Result<DirEntry, io::Error>> {
    match *self {
      List::Files { ref mut it } => match *it {
        Err(ref mut err) => {
          warn!("{}", err);
          return None;
        }
        Ok(ref mut rd) => rd.next(),
      },
    }
  }
}