-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfilters.rs
83 lines (76 loc) · 2.36 KB
/
filters.rs
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use fancy_regex::Regex;
use url::Url;
#[derive(Debug, Clone)]
pub enum Filter {
Regex(Regex),
Domain(Vec<String>),
}
impl Filter {
pub fn is_ignored(&self, url: &Url) -> bool {
match self {
Self::Regex(regex) => regex.is_match(url.as_str()).unwrap(),
Self::Domain(filter) => url
.domain()
.map(|h| {
filter
.iter()
.any(|d| h.trim_start_matches("www.") == d.trim_start_matches("www."))
})
.map(|found| !found)
.unwrap_or(true),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_regex() {
let f = Filter::Regex(Regex::new(".jpg$").unwrap());
assert_eq!(
f.is_ignored(&Url::parse("http://google.com").unwrap()),
false
);
assert_eq!(
f.is_ignored(&Url::parse("http://google.com/image.png").unwrap()),
false
);
assert_eq!(
f.is_ignored(&Url::parse("http://google.com/some/thing/second.jpg").unwrap()),
true
);
let f = Filter::Regex(Regex::new("^http://google.com").unwrap());
assert_eq!(
f.is_ignored(&Url::parse("http://google.com").unwrap()),
true
);
assert_eq!(
f.is_ignored(&Url::parse("http://google.com/image.png").unwrap()),
true
);
assert_eq!(
f.is_ignored(&Url::parse("http://microsoft.com").unwrap()),
false
);
}
#[test]
fn test_domain() {
let f = Filter::Domain(vec!["google.com".to_string(), "www.bing.com".to_string()]);
assert_eq!(
f.is_ignored(&Url::parse("http://google.com").unwrap()),
false
);
assert_eq!(
f.is_ignored(&Url::parse("http://google.com/image.png").unwrap()),
false
);
assert_eq!(
f.is_ignored(&Url::parse("http://bing.com/image.png?asd=13").unwrap()),
false
);
assert_eq!(f.is_ignored(&Url::parse("http://yahoo.com").unwrap()), true);
}
}