summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLars Wirzenius <liw@liw.fi>2022-10-15 09:44:16 +0300
committerLars Wirzenius <liw@liw.fi>2022-10-15 09:44:16 +0300
commitc2c8e50248a27ca99318b584dda10b87646beaff (patch)
tree14918f2e15e48eb57545553a586f1cc42decf05e
parent0ef43d65aac17b5a294cab318182d73da6c0c545 (diff)
downloadriki-c2c8e50248a27ca99318b584dda10b87646beaff.tar.gz
refactor: add PathFilter
Sponsored-by: author
-rw-r--r--src/srcdir.rs73
1 files changed, 73 insertions, 0 deletions
diff --git a/src/srcdir.rs b/src/srcdir.rs
index f8d3949..8d19a62 100644
--- a/src/srcdir.rs
+++ b/src/srcdir.rs
@@ -36,3 +36,76 @@ impl SouceDir {
&self.files
}
}
+
+#[derive(Default)]
+pub struct PathFilter {
+ excluded_substrings: Vec<&'static str>,
+ excluded_suffixes: Vec<&'static str>,
+}
+
+impl PathFilter {
+ pub fn exclude_substring(&mut self, s: &'static str) {
+ self.excluded_substrings.push(s);
+ }
+
+ pub fn exclude_suffix(&mut self, s: &'static str) {
+ self.excluded_suffixes.push(s);
+ }
+
+
+ pub fn is_included<P>(&self, path: P) -> bool
+ where
+ P: AsRef<Path>
+ {
+ let path = path.as_ref().to_string_lossy();
+ for pat in self.excluded_suffixes.iter() {
+ if path.ends_with(pat) {
+ return false;
+ }
+ }
+ for pat in self.excluded_substrings.iter() {
+ if path.contains(pat) {
+ return false;
+ }
+ }
+ true
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::PathFilter;
+
+ #[test]
+ fn includes_dotgit_by_default() {
+ let filter = PathFilter::default();
+ assert!(filter.is_included(".git"));
+ }
+
+ #[test]
+ fn excludes_dotgit_if_requested() {
+ let mut filter = PathFilter::default();
+ filter.exclude_substring(".git");
+ assert!(!filter.is_included(".git"));
+ }
+
+ #[test]
+ fn includes_footilde_by_default() {
+ let filter = PathFilter::default();
+ assert!(filter.is_included("foo~"));
+ }
+
+ #[test]
+ fn includes_footildebar_if_tilde_suffix_is_excluded() {
+ let mut filter = PathFilter::default();
+ filter.exclude_suffix("~");
+ assert!(filter.is_included("foo~bar"));
+ }
+
+ #[test]
+ fn excludes_footilde_if_tilde_suffix_is_excluded() {
+ let mut filter = PathFilter::default();
+ filter.exclude_suffix("~");
+ assert!(!filter.is_included("foo~"));
+ }
+}