1use crate::config::Config;
4use std::ffi::OsStr;
5use std::path::Path;
6use std::sync::Arc;
7
8pub struct PatternMatcher {
10 config: Arc<Config>,
11 directories: Vec<CompiledPattern>,
12 files: Vec<usize>,
13}
14
15enum CompiledPattern {
16 Exact(usize),
17 Suffix(usize),
18}
19
20impl PatternMatcher {
21 pub fn new(config: Arc<Config>) -> Self {
22 let directories = config
23 .directories
24 .iter()
25 .enumerate()
26 .map(|(index, pattern)| {
27 if pattern.starts_with('*') {
28 CompiledPattern::Suffix(index)
29 } else {
30 CompiledPattern::Exact(index)
31 }
32 })
33 .collect();
34 let files = (0..config.files.len()).collect();
35 Self {
36 config,
37 directories,
38 files,
39 }
40 }
41
42 #[inline]
44 pub fn is_temp_directory(&self, name: impl AsRef<OsStr>) -> bool {
45 let Some(name) = name.as_ref().to_str() else {
46 return false;
47 };
48 for pattern in &self.directories {
49 match *pattern {
50 CompiledPattern::Exact(index) if name == self.config.directories[index] => {
51 return true;
52 }
53 CompiledPattern::Suffix(index)
54 if name.ends_with(&self.config.directories[index][1..]) =>
55 {
56 return true;
57 }
58 _ => {}
59 }
60 }
61 false
62 }
63
64 #[inline]
66 pub fn is_temp_file(&self, name: impl AsRef<OsStr>) -> bool {
67 let Some(name) = name.as_ref().to_str() else {
68 return false;
69 };
70 for &index in &self.files {
71 if name.ends_with(self.config.files[index].as_str()) {
72 return true;
73 }
74 }
75 false
76 }
77
78 #[inline]
80 #[allow(dead_code)]
81 pub fn matches(&self, path: &Path, is_dir: bool) -> bool {
82 if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
83 if is_dir {
84 self.is_temp_directory(OsStr::new(name))
85 } else {
86 self.is_temp_file(OsStr::new(name))
87 }
88 } else {
89 false
90 }
91 }
92
93 #[allow(dead_code)]
95 pub fn directory_patterns(&self) -> &[String] {
96 &self.config.directories
97 }
98
99 #[allow(dead_code)]
101 pub fn file_patterns(&self) -> &[String] {
102 &self.config.files
103 }
104
105 pub fn config(&self) -> Arc<Config> {
106 Arc::clone(&self.config)
107 }
108}
109
110#[cfg(test)]
111mod tests {
112 use super::*;
113
114 fn test_config() -> Arc<Config> {
115 Arc::new(Config {
116 directories: vec![
117 ".terraform".to_string(),
118 "target".to_string(),
119 "node_modules".to_string(),
120 "__pycache__".to_string(),
121 "*.egg-info".to_string(),
122 ],
123 files: vec![".DS_Store".to_string(), ".pyc".to_string(), "~".to_string()],
124 days: None,
125 force: false,
126 })
127 }
128
129 #[test]
130 fn test_temp_directories() {
131 let matcher = PatternMatcher::new(test_config());
132 assert!(matcher.is_temp_directory(".terraform"));
133 assert!(matcher.is_temp_directory("target"));
134 assert!(matcher.is_temp_directory("node_modules"));
135 assert!(matcher.is_temp_directory("__pycache__"));
136 assert!(!matcher.is_temp_directory("src"));
137 assert!(!matcher.is_temp_directory("lib"));
138 }
139
140 #[test]
141 fn test_temp_files() {
142 let matcher = PatternMatcher::new(test_config());
143 assert!(matcher.is_temp_file(".DS_Store"));
144 assert!(matcher.is_temp_file("test.pyc"));
145 assert!(matcher.is_temp_file("backup~"));
146 assert!(!matcher.is_temp_file("main.rs"));
147 }
148
149 #[test]
150 fn test_egg_info() {
151 let matcher = PatternMatcher::new(test_config());
152 assert!(matcher.is_temp_directory("mypackage.egg-info"));
153 assert!(!matcher.is_temp_directory("egg-info.mypackage"));
154 }
155
156 #[test]
157 fn matches_paths_and_exposes_configured_patterns() {
158 let matcher = PatternMatcher::new(test_config());
159 assert!(matcher.matches(Path::new("some/target"), true));
160 assert!(matcher.matches(Path::new("some/module.pyc"), false));
161 assert!(!matcher.matches(Path::new("some/main.rs"), false));
162 assert_eq!(matcher.directory_patterns()[0], ".terraform");
163 assert_eq!(matcher.file_patterns()[0], ".DS_Store");
164 }
165
166 #[cfg(unix)]
167 #[test]
168 fn non_utf8_path_does_not_match() {
169 use std::os::unix::ffi::OsStrExt;
170 let matcher = PatternMatcher::new(test_config());
171 let path = Path::new(std::ffi::OsStr::from_bytes(b"\xff"));
172 assert!(!matcher.matches(path, false));
173 }
174
175 #[test]
176 #[ignore = "manual release microbenchmark"]
177 fn manual_profile_pattern_lookup() {
178 use foldhash::HashSet;
179 use std::collections::HashSet as StdHashSet;
180 use std::hint::black_box;
181 use std::time::Instant;
182
183 let config = test_config();
184 let matcher = PatternMatcher::new(Arc::clone(&config));
185 let names = ["src", "target", "module.pyc", "package.egg-info"];
186 let iterations = 1_000_000;
187
188 let start = Instant::now();
189 for index in 0..iterations {
190 black_box(matcher.is_temp_directory(names[index % names.len()]));
191 }
192 let linear = start.elapsed();
193
194 let std_exact: StdHashSet<&str> = config
195 .directories
196 .iter()
197 .filter(|pattern| !pattern.starts_with('*'))
198 .map(String::as_str)
199 .collect();
200 let fold_exact: HashSet<&str> = config
201 .directories
202 .iter()
203 .filter(|pattern| !pattern.starts_with('*'))
204 .map(String::as_str)
205 .collect();
206 let suffixes: Vec<_> = config
207 .directories
208 .iter()
209 .filter_map(|pattern| pattern.strip_prefix('*'))
210 .collect();
211
212 let start = Instant::now();
213 for index in 0..iterations {
214 let name = names[index % names.len()];
215 black_box(
216 std_exact.contains(name) || suffixes.iter().any(|suffix| name.ends_with(suffix)),
217 );
218 }
219 let std_hash = start.elapsed();
220
221 let start = Instant::now();
222 for index in 0..iterations {
223 let name = names[index % names.len()];
224 black_box(
225 fold_exact.contains(name) || suffixes.iter().any(|suffix| name.ends_with(suffix)),
226 );
227 }
228 let fold_hash = start.elapsed();
229
230 println!("pattern lookup: linear={linear:?} std_hash={std_hash:?} foldhash={fold_hash:?}");
231 }
232}