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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
use crate::{File, FileType};

use std::{
    collections::VecDeque,
    ffi::OsStr,
    path::{Path, PathBuf},
};

#[derive(Debug, Clone)]
pub struct FilesIter<'a> {
    // Directories go at the back, files at the front
    // Has a aditional field for keeping track of depth
    file_deque: VecDeque<(&'a File, usize)>,
    // Accessed by `depth` method
    current_depth: usize,
    // Options
    files_before_directories: bool,
    skip_dirs: bool,
    skip_regular_files: bool,
    skip_symlinks: bool,
    min_depth: usize,
    max_depth: usize,
}

impl<'a> FilesIter<'a> {
    // file_deque is a
    pub(crate) fn new(start_file: &'a File) -> Self {
        let mut file_deque = VecDeque::new();
        // Start a deque from `start_file`, at depth 0, which can increase for each file
        // if self is a directory
        file_deque.push_back((start_file, 0));

        Self {
            file_deque,
            // Default start
            current_depth: 0,
            files_before_directories: false,
            skip_dirs: false,
            skip_regular_files: false,
            skip_symlinks: false,
            min_depth: usize::MIN,
            max_depth: usize::MAX,
        }
    }

    /// Access depth of last element, starts at 0 (root has no depth).
    pub fn depth(&self) -> usize {
        self.current_depth
    }

    pub fn paths(self) -> PathsIter<'a> {
        PathsIter::new(self)
    }

    // Applying filters
    pub fn files_before_directories(mut self, arg: bool) -> Self {
        self.files_before_directories = arg;
        self
    }

    pub fn skip_dirs(mut self, arg: bool) -> Self {
        self.skip_dirs = arg;
        self
    }

    pub fn skip_regular_files(mut self, arg: bool) -> Self {
        self.skip_regular_files = arg;
        self
    }

    pub fn skip_symlinks(mut self, arg: bool) -> Self {
        self.skip_symlinks = arg;
        self
    }

    pub fn min_depth(mut self, min: usize) -> Self {
        self.min_depth = min;
        self
    }

    pub fn max_depth(mut self, max: usize) -> Self {
        self.max_depth = max;
        self
    }
}

impl<'a> Iterator for FilesIter<'a> {
    type Item = &'a File;

    fn next(&mut self) -> Option<Self::Item> {
        if self.file_deque.is_empty() {
            return None;
        }

        // Pop from left or right?
        //
        // If self.files_before_directories is set, always pop from the left, where
        // files are located
        //
        // Else, pop files from the right, that are directories, until there's no
        // directory left, then start popping from the left
        //
        // Note: last_file_is_directory <-> there is a directory in the deque
        let last_file_is_directory = self.file_deque.back().unwrap().0.file_type.is_dir();
        let pop_from_the_left = self.files_before_directories || !last_file_is_directory;

        // Unpack popped file and depth
        let (file, depth) = if pop_from_the_left {
            self.file_deque.pop_front()
        } else {
            self.file_deque.pop_back()
        }
        .unwrap();

        // Update current_depth, useful for .depth() method and PathsIter
        self.current_depth = depth;

        // If directory, add children, and check for `self.skip_dirs`
        if let FileType::Directory(ref children) = &file.file_type {
            // Reversed, because late nodes stay at the tip
            // We want at the tip the first ones
            for child in children.iter().rev() {
                if child.file_type.is_dir() {
                    self.file_deque.push_back((child, depth + 1));
                } else {
                    self.file_deque.push_front((child, depth + 1));
                }
            }
        }

        // If should skip due to depth limits
        if self.min_depth > depth || self.max_depth < depth {
            return self.next();
        }

        // If should skip due file type specific skip filters
        if self.skip_regular_files && file.file_type.is_regular()
            || self.skip_dirs && file.file_type.is_dir()
            || self.skip_dirs && file.file_type.is_dir()
        {
            return self.next();
        }

        Some(&file)
    }
}

#[derive(Debug, Clone)]
pub struct PathsIter<'a> {
    file_iter: FilesIter<'a>,
    // options
    only_show_last_segment: bool,
}

impl<'a> PathsIter<'a> {
    pub fn new(file_iter: FilesIter<'a>) -> Self {
        Self {
            file_iter,
            only_show_last_segment: false,
        }
    }

    pub fn only_show_last_segment(mut self, arg: bool) -> Self {
        self.only_show_last_segment = arg;
        self
    }

    pub fn depth(&self) -> usize {
        self.file_iter.depth()
    }

    /// True implementation of `Iterator` for `PathsIter`, without `.clone()`
    pub fn next_ref(&mut self) -> Option<&Path> {
        let file = self.file_iter.next()?;

        if self.only_show_last_segment {
            file.path.file_name().map(OsStr::as_ref)
        } else {
            Some(&file.path)
        }
    }
}

impl Iterator for PathsIter<'_> {
    type Item = PathBuf;

    fn next(&mut self) -> Option<Self::Item> {
        let path_buf = self.next_ref()?.to_path_buf();
        Some(path_buf)
    }
}

#[cfg(test)]
mod tests {
    #[test] // Huge test ahead
    #[rustfmt::skip]
    fn testing_files_and_paths_iters() {
        use std::path::PathBuf;
        use crate::{File, FileType::*};

        // Implementing a syntax sugar util to make tests readable
        impl File {
            fn c(&self, index: usize) -> &File {
                &self.file_type.children().unwrap()[index]
            }
        }

        // We will test the following structure:
        // ".config": [
        //     "i3": [
        //         "file1"
        //         "file2"
        //         "dir": [
        //             "innerfile1"
        //             "innerfile2"
        //         ]
        //         "file3"
        //     ]
        //     "outerfile1"
        //     "outerfile2"
        // ]

        // Create the strucutre
        #[rustfmt::skip]
        let root = File::new(".config/", Directory(vec![
            File::new(".config/i3/", Directory(vec![
                File::new(".config/i3/file1", Regular),
                File::new(".config/i3/file2", Regular),
                File::new(".config/i3/dir/", Directory(vec![
                    File::new(".config/i3/dir/innerfile1", Regular),
                    File::new(".config/i3/dir/innerfile2", Regular)
                ])),
                File::new(".config/i3/file3", Regular),
            ])),
            File::new(".config/outerfile1", Regular),
            File::new(".config/outerfile2", Regular)
        ]));

        #[rustfmt::skip]
        // Get the references in line order, from top to bottom
        let refs = vec![
            /* 0 */ &root,                // .config/
            /* 1 */ &root.c(0),           // .config/i3/
            /* 2 */ &root.c(0).c(0),      // .config/i3/file1
            /* 3 */ &root.c(0).c(1),      // .config/i3/file2
            /* 4 */ &root.c(0).c(2),      // .config/i3/dir/
            /* 5 */ &root.c(0).c(2).c(0), // .config/i3/dir/innerfile1
            /* 6 */ &root.c(0).c(2).c(1), // .config/i3/dir/innerfile2
            /* 7 */ &root.c(0).c(3),      // .config/i3/file3
            /* 8 */ &root.c(1),           // .config/outerfile1
            /* 9 */ &root.c(2),           // .config/outerfile2
        ];

        let mut it = root.files();
        assert_eq!(it.next(), Some(refs[0])); // .config/
        assert_eq!(it.next(), Some(refs[1])); // .config/i3/
        assert_eq!(it.next(), Some(refs[4])); // .config/i3/dir/
        assert_eq!(it.next(), Some(refs[5])); // .config/i3/dir/innerfile1
        assert_eq!(it.next(), Some(refs[6])); // .config/i3/dir/innerfile2
        assert_eq!(it.next(), Some(refs[2])); // .config/i3/file1
        assert_eq!(it.next(), Some(refs[3])); // .config/i3/file2
        assert_eq!(it.next(), Some(refs[7])); // .config/i3/file3
        assert_eq!(it.next(), Some(refs[8])); // .config/outerfile1
        assert_eq!(it.next(), Some(refs[9])); // .config/outerfile2

        let mut it = root.files().files_before_directories(true);
        assert_eq!(it.next(), Some(refs[0])); // .config/
        assert_eq!(it.next(), Some(refs[8])); // .config/outerfile1
        assert_eq!(it.next(), Some(refs[9])); // .config/outerfile2
        assert_eq!(it.next(), Some(refs[1])); // .config/i3/
        assert_eq!(it.next(), Some(refs[2])); // .config/i3/file1
        assert_eq!(it.next(), Some(refs[3])); // .config/i3/file2
        assert_eq!(it.next(), Some(refs[7])); // .config/i3/file3
        assert_eq!(it.next(), Some(refs[4])); // .config/i3/dir/
        assert_eq!(it.next(), Some(refs[5])); // .config/i3/dir/innerfile1
        assert_eq!(it.next(), Some(refs[6])); // .config/i3/dir/innerfile2

        let mut it = root.files().skip_dirs(true);
        assert_eq!(it.next(), Some(refs[5])); // .config/i3/dir/innerfile1
        assert_eq!(it.next(), Some(refs[6])); // .config/i3/dir/innerfile2
        assert_eq!(it.next(), Some(refs[2])); // .config/i3/file1
        assert_eq!(it.next(), Some(refs[3])); // .config/i3/file2
        assert_eq!(it.next(), Some(refs[7])); // .config/i3/file3
        assert_eq!(it.next(), Some(refs[8])); // .config/outerfile1
        assert_eq!(it.next(), Some(refs[9])); // .config/outerfile2

        let mut it = root.files().skip_regular_files(true);
        assert_eq!(it.next(), Some(refs[0])); // .config/
        assert_eq!(it.next(), Some(refs[1])); // .config/i3/
        assert_eq!(it.next(), Some(refs[4])); // .config/i3/dir/

        // min and max depth (1 <= d <= 2)
        //
        // skips:
        // .config/
        // .config/i3/dir/innerfile1
        // .config/i3/dir/innerfile2
        let mut it = root.files().min_depth(1).max_depth(2);
        assert_eq!(it.next(), Some(refs[1])); // .config/i3/
        assert_eq!(it.next(), Some(refs[4])); // .config/i3/dir/
        assert_eq!(it.next(), Some(refs[2])); // .config/i3/file1
        assert_eq!(it.next(), Some(refs[3])); // .config/i3/file2
        assert_eq!(it.next(), Some(refs[7])); // .config/i3/file3
        assert_eq!(it.next(), Some(refs[8])); // .config/outerfile1
        assert_eq!(it.next(), Some(refs[9])); // .config/outerfile2

        // Paths iterator testing
        let mut it = root.paths();
        assert_eq!(it.next().unwrap(), PathBuf::from(".config/"));                  // [0]
        assert_eq!(it.next().unwrap(), PathBuf::from(".config/i3/"));               // [1]
        assert_eq!(it.next().unwrap(), PathBuf::from(".config/i3/dir/"));           // [4]
        assert_eq!(it.next().unwrap(), PathBuf::from(".config/i3/dir/innerfile1")); // [5]
        assert_eq!(it.next().unwrap(), PathBuf::from(".config/i3/dir/innerfile2")); // [6]
        assert_eq!(it.next().unwrap(), PathBuf::from(".config/i3/file1"));          // [2]
        assert_eq!(it.next().unwrap(), PathBuf::from(".config/i3/file2"));          // [3]
        assert_eq!(it.next().unwrap(), PathBuf::from(".config/i3/file3"));          // [7]
        assert_eq!(it.next().unwrap(), PathBuf::from(".config/outerfile1"));        // [8]
        assert_eq!(it.next().unwrap(), PathBuf::from(".config/outerfile2"));        // [9]

        let mut it = root.paths().only_show_last_segment(true);
        assert_eq!(it.next().unwrap(), PathBuf::from(".config/"));   // [0]
        assert_eq!(it.next().unwrap(), PathBuf::from("i3/"));        // [1]
        assert_eq!(it.next().unwrap(), PathBuf::from("dir/"));       // [4]
        assert_eq!(it.next().unwrap(), PathBuf::from("innerfile1")); // [5]
        assert_eq!(it.next().unwrap(), PathBuf::from("innerfile2")); // [6]
        assert_eq!(it.next().unwrap(), PathBuf::from("file1"));      // [2]
        assert_eq!(it.next().unwrap(), PathBuf::from("file2"));      // [3]
        assert_eq!(it.next().unwrap(), PathBuf::from("file3"));      // [7]
        assert_eq!(it.next().unwrap(), PathBuf::from("outerfile1")); // [8]
        assert_eq!(it.next().unwrap(), PathBuf::from("outerfile2")); // [9]
    }
}