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
// License: see LICENSE file at root directory of `master` branch

//! # Root

use std::{
    fs::{self, ReadDir},
    io::{self, Error, ErrorKind},
    path::{Path, PathBuf},
};

use crate::filter::Filter;

/// # File discovery
///
/// ## Notes
///
/// - You can make this struct by [`find_files()`][::find_files()].
/// - If sub directories are symlinks, they will be ignored.
///
/// [::find_files()]: fn.find_files.html
#[derive(Debug)]
pub struct FileDiscovery<F> where F: Filter {

    /// # Root directory
    root: PathBuf,

    /// # Filter
    filter: F,

    /// # Recursive
    recursive: bool,

    /// # Current
    current: ReadDir,

    /// # Sub directories
    sub_dirs: Option<Vec<PathBuf>>,

    /// # Max depth
    max_depth: Option<usize>,

}

impl<F> FileDiscovery<F> where F: Filter {

    /// # Makes new instance
    pub fn make<P>(dir: P, recursive: bool, filter: F, max_depth: Option<usize>) -> io::Result<Self> where P: AsRef<Path> {
        Ok(Self {
            root: dir.as_ref().canonicalize()?,
            filter,
            recursive,
            current: fs::read_dir(dir)?,
            sub_dirs: None,
            max_depth,
        })
    }

}

impl<F> Iterator for FileDiscovery<F> where F: Filter {

    type Item = io::Result<PathBuf>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            match self.current.next() {
                Some(entry) => match entry {
                    Ok(entry) => match entry.file_type() {
                        Ok(file_type) => {
                            let path = entry.path();
                            let is_symlink = file_type.is_symlink();
                            if file_type.is_dir() || (is_symlink && path.is_dir()) {
                                // If we accept symlinks, update code that calls ancestors()!
                                if self.recursive == false || is_symlink {
                                    continue;
                                }

                                if let Some(max_depth) = self.max_depth.as_ref() {
                                    match path.canonicalize() {
                                        // Symlinks are ignored, so using ancestors() is safe.
                                        Ok(path) => match depth_from(&self.root, &path) {
                                            Ok(depth) => if &depth >= max_depth {
                                                continue;
                                            },
                                            Err(err) => return Some(Err(err)),
                                        },
                                        Err(err) => return Some(Err(err)),
                                    };
                                }

                                if self.filter.accept(&path) == false {
                                    continue;
                                }

                                match self.sub_dirs.as_mut() {
                                    Some(sub_dirs) => sub_dirs.push(path),
                                    None => self.sub_dirs = Some(vec![path]),
                                };
                            } else if file_type.is_file() || (is_symlink && path.is_file()) {
                                if self.filter.accept(&path) == false {
                                    continue;
                                }
                                return Some(Ok(path));
                            }
                        },
                        Err(err) => return Some(Err(err)),
                    },
                    Err(err) => return Some(Err(err)),
                },
                None => match self.sub_dirs.as_mut() {
                    None => return None,
                    Some(sub_dirs) => match sub_dirs.len() {
                        0 => return None,
                        _ => match fs::read_dir(sub_dirs.remove(0)) {
                            Ok(new) => self.current = new,
                            Err(err) => return Some(Err(err)),
                        },
                    },
                },
            };
        }
    }

}

/// # Calculates depth of path from a root directory
///
/// ## Notes
///
/// - [`canonicalize()`][r://PathBuf/canonicalize()] is _not_ called on input paths.
///
/// [r://PathBuf/canonicalize()]: https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.canonicalize
fn depth_from<P>(root_dir: P, path: P) -> io::Result<usize> where P: AsRef<Path> {
    let root_dir = root_dir.as_ref();
    let path = path.as_ref();

    let mut depth: usize = 0;
    let mut found_root = false;
    for a in path.ancestors().skip(1) {
        match a == root_dir {
            true => {
                found_root = true;
                break;
            },
            false => match depth.checked_add(1) {
                Some(new_depth) => depth = new_depth,
                None => return Err(Error::new(ErrorKind::Other, format!("Directory level of {:?} is too deep: {}", path, depth))),
            },
        };
    }

    match found_root {
        true => Ok(depth),
        false => Err(Error::new(ErrorKind::Other, format!("{:?} was expected to be inside of {:?}, but not", path, root_dir))),
    }
}

/// # Finds files
///
/// This function makes new instance of [`FileDiscovery`][::FileDiscovery]. You should refer to that struct for notes on usage.
///
/// [::FileDiscovery]: struct.FileDiscovery.html
pub fn find_files<P, F>(dir: P, recursive: bool, filter: F) -> io::Result<FileDiscovery<F>> where P: AsRef<Path>, F: Filter {
    FileDiscovery::make(dir, recursive, filter, None)
}