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
//! # Filter
//!
//! Commony types for filtering paths to visit.
//!
//! ## Note
//! There is a branch (`unstable/fn-traits`) that adds support for rust
//! [`unboxed_closures`](https://doc.rust-lang.org/beta/unstable-book/language-features/unboxed-closures.html)
//! and [`fn_traits`](https://doc.rust-lang.org/beta/unstable-book/library-features/fn-traits.html)
//! which will solve the need for those separated types.
//!

use std::num::NonZeroUsize;
use std::path::Path;

/// Accepts all directories.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Accept;

/// Accepts all directories which are not symlinks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NoSymlink;

/// Accepts directories up to a certain depth.
///
/// The depth 1 means that only the base directory is visited.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MaxDepth(pub(crate) NonZeroUsize);

impl MaxDepth {
    const SINGLE_DEPTH: NonZeroUsize = unsafe { NonZeroUsize::new_unchecked(1) };

    /// Creates a max depth filter.
    ///
    /// This filter is dependant on the starting `dir`, it first retrieves
    /// the depth of the `dir` (right from the root ancestor) and then
    /// ensures that visited directories does not exceed the given depth
    /// (`path to visit ancestor count - dir ancestor count`).
    ///
    /// You can also use [`Path::canonicalize`] to get the absolute path, which will also
    /// produce a higher depth (if it is not already canonical), however, ensure to only pass
    /// the canonicalized version to the visitor, otherwise, their depths will never match.
    pub fn new(max_depth: NonZeroUsize) -> Self {
        Self(max_depth)
    }

    /// Creates a single depth filter (i.e, only visits files of provided directory).
    ///
    /// This filter is dependant on the starting `dir`, it first retrieves
    /// the depth of the `dir` (right from the root ancestor) and then
    /// ensures that visited directories does not exceed the given depth
    /// (`path to visit ancestor count - dir ancestor count`).
    ///
    /// You can also use [`Path::canonicalize`] to get the absolute path, which will also
    /// produce a higher depth (if it is not already canonical), however, ensure to only pass
    /// the canonicalized version to the visitor, otherwise, their depths will never match.
    pub fn single_depth() -> Self {
        Self(Self::SINGLE_DEPTH)
    }
}

/// Closure based predicate.
///
/// ## Create
///
/// This type can be created through [`From`] and [`Into`] traits for any type,
/// however, it only implements [`Filter`] when `F: Fn(&Path) -> bool`
///
/// You can also use [`Closure::new`] to create a closure for filter composition, or [`Closure::from_fn`]
/// to avoid the need to introduce explicit types.
#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Closure<F> {
    closure: F,
}

pub trait Filter {
    /// Checks whether `path_to_visit` should be visited or not. The `base_path` is
    /// the initial directory provided to the visitor.
    ///
    /// This filter is called only for directories, if it returns `true`
    /// it means that the directory should be visited, otherwise, it will
    /// be skipped.
    ///
    /// The directory will be emitted by the iterator regardless of the
    /// return value of this function.
    fn filter(&self, base_path: &Path, path_to_visit: &Path) -> bool;

    /// Creates a filter that only accepts both this and the `other` condition.
    fn and<B>(self, other: B) -> And<Self, B>
    where
        Self: Sized,
        B: Filter,
    {
        And { a: self, b: other }
    }

    /// Creates a filter that accepts this or the `other` condition.
    fn or<B>(self, other: B) -> Or<Self, B>
    where
        Self: Sized,
        B: Filter,
    {
        Or { a: self, b: other }
    }

    /// Creates a filter that negates when this filter accepts.
    fn not(self) -> Not<Self>
    where
        Self: Sized,
    {
        Not { a: self }
    }
}

impl Filter for Accept {
    fn filter(&self, _: &Path, _: &Path) -> bool {
        true
    }
}

impl Filter for NoSymlink {
    fn filter(&self, _: &Path, p: &Path) -> bool {
        return !p.is_dir() || !p.is_symlink();
    }
}

impl Filter for MaxDepth {
    fn filter(&self, base_path: &Path, p: &Path) -> bool {
        let depth = base_path.ancestors().count();
        let MaxDepth(max_depth) = *self;
        let ancestors = p.ancestors().count();
        return if ancestors >= depth {
            ancestors - depth <= max_depth.get() - 1
        } else {
            false
        };
    }
}

impl<F> Closure<F> {
    pub fn new(closure: F) -> Self {
        Self { closure }
    }

    pub fn from_fn(closure: F) -> Self
    where
        F: Fn(&Path) -> bool,
    {
        Self { closure }
    }
}

impl<F> From<F> for Closure<F> {
    fn from(f: F) -> Self {
        Self { closure: f }
    }
}

impl<F> Filter for Closure<F>
where
    F: Fn(&Path, &Path) -> bool,
{
    fn filter(&self, base_dir: &Path, directory: &Path) -> bool {
        (self.closure)(base_dir, directory)
    }
}

#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct And<A, B> {
    a: A,
    b: B,
}

#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Or<A, B> {
    a: A,
    b: B,
}

#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Not<A> {
    a: A,
}

#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct This<A> {
    a: A,
}

impl<A> This<A> {
    pub fn new(a: A) -> Self {
        Self { a }
    }
}

impl<A, B> Filter for And<A, B>
where
    A: Filter,
    B: Filter,
{
    fn filter(&self, base_path: &Path, directory: &Path) -> bool {
        self.a.filter(base_path, directory) && self.b.filter(base_path, directory)
    }
}

impl<A, B> Filter for Or<A, B>
where
    A: Filter,
    B: Filter,
{
    fn filter(&self, base_path: &Path, directory: &Path) -> bool {
        self.a.filter(base_path, directory) || self.b.filter(base_path, directory)
    }
}

impl<A> Filter for Not<A>
where
    A: Filter,
{
    fn filter(&self, base_path: &Path, directory: &Path) -> bool {
        !self.a.filter(base_path, directory)
    }
}

impl<A> Filter for This<A>
where
    A: Filter,
{
    fn filter(&self, base_path: &Path, directory: &Path) -> bool {
        self.a.filter(base_path, directory)
    }
}