1use std::{os::unix::ffi::OsStrExt as _, path::Path};
21
22use globset::{GlobBuilder, GlobSet, GlobSetBuilder};
23use kizz_trace::AbsolutePath;
24use regex::bytes::{Regex, RegexSet};
25
26pub const REGEX_PREFIX: &str = "re:";
28
29const HOME_PREFIX: &str = "~/";
31
32const GLOB_CHARACTERS: [char; 4] = ['*', '?', '[', '{'];
34
35#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
37pub enum PatternError {
38 #[error("invalid glob pattern `{pattern}`: {message}")]
40 Glob {
41 pattern: String,
43 message: String,
45 },
46 #[error("invalid regular expression in pattern `{pattern}`: {message}")]
48 Regex {
49 pattern: String,
51 message: String,
53 },
54 #[error("pattern `{pattern}` starts with `~/`, but the caller environment has no HOME")]
56 NoHome {
57 pattern: String,
59 },
60}
61
62#[derive(Debug, Clone)]
64pub struct PathPatterns {
65 paths: Vec<AbsolutePath>,
67 globs: GlobSet,
69 regexes: RegexSet,
71}
72
73impl Default for PathPatterns {
74 fn default() -> Self {
75 Self {
76 paths: Vec::new(),
77 globs: GlobSet::empty(),
78 regexes: RegexSet::empty(),
79 }
80 }
81}
82
83fn is_glob(pattern: &str) -> bool {
85 pattern.contains(GLOB_CHARACTERS)
86}
87
88impl PathPatterns {
89 pub fn new(
97 patterns: &[String],
98 task_dir: &AbsolutePath,
99 home: Option<&AbsolutePath>,
100 ) -> Result<Self, PatternError> {
101 let mut paths = Vec::new();
102 let mut globs = GlobSetBuilder::new();
103 let mut regexes = Vec::new();
104 for pattern in patterns {
105 if let Some(regex) = pattern.strip_prefix(REGEX_PREFIX) {
106 Regex::new(regex).map_err(|error| {
107 PatternError::Regex {
108 pattern: pattern.clone(),
109 message: error.to_string(),
110 }
111 })?;
112 regexes.push(regex);
113 continue;
114 }
115 let (base, rest) = if let Some(rest) = pattern.strip_prefix(HOME_PREFIX) {
116 let home = home.ok_or_else(|| {
117 PatternError::NoHome {
118 pattern: pattern.clone(),
119 }
120 })?;
121 (home, rest)
122 } else {
123 (task_dir, pattern.as_str())
125 };
126 if is_glob(rest) {
127 let glob = GlobBuilder::new(&anchor_glob(base, rest))
128 .literal_separator(true)
129 .backslash_escape(true)
130 .build()
131 .map_err(|error| {
132 PatternError::Glob {
133 pattern: pattern.clone(),
134 message: error.kind().to_string(),
135 }
136 })?;
137 globs.add(glob);
138 } else {
139 paths.push(base.join(rest));
140 }
141 }
142 let globs = globs.build().map_err(|error| {
143 PatternError::Glob {
144 pattern: error.glob().unwrap_or_default().to_owned(),
145 message: error.kind().to_string(),
146 }
147 })?;
148 let regexes = RegexSet::new(®exes).map_err(|error| {
149 PatternError::Regex {
150 pattern: regexes
151 .iter()
152 .map(|regex| format!("{REGEX_PREFIX}{regex}"))
153 .collect::<Vec<_>>()
154 .join(", "),
155 message: error.to_string(),
156 }
157 })?;
158 Ok(Self {
159 paths,
160 globs,
161 regexes,
162 })
163 }
164
165 #[must_use]
167 pub fn is_empty(&self) -> bool {
168 self.paths.is_empty() && self.globs.is_empty() && self.regexes.is_empty()
169 }
170
171 #[must_use]
173 pub fn matches(
174 &self,
175 path: &AbsolutePath,
176 ) -> bool {
177 self.paths.contains(path)
178 || self.globs.is_match(path.as_path())
179 || self.regexes.is_match(path.as_path().as_os_str().as_bytes())
180 }
181}
182
183fn anchor_glob(
186 base: &AbsolutePath,
187 rest: &str,
188) -> String {
189 let anchored = if Path::new(rest).is_absolute() {
190 rest.to_owned()
191 } else {
192 format!(
193 "{}/{rest}",
194 globset::escape(&base.as_path().to_string_lossy())
195 )
196 };
197 let components: Vec<&str> = anchored
198 .split('/')
199 .filter(|component| !component.is_empty() && *component != ".")
200 .collect();
201 format!("/{}", components.join("/"))
202}
203
204#[cfg(test)]
206#[allow(
207 clippy::disallowed_macros,
208 clippy::disallowed_methods,
209 reason = "test code: the tests assert and lock"
210)]
211mod tests {
212 use super::*;
213
214 fn path(text: &str) -> AbsolutePath {
216 AbsolutePath::new(text).unwrap()
217 }
218
219 fn compile(patterns: &[&str]) -> Result<PathPatterns, PatternError> {
222 let patterns: Vec<String> = patterns.iter().map(|&pattern| pattern.to_owned()).collect();
223 PathPatterns::new(&patterns, &path("/work/task"), Some(&path("/home/me")))
224 }
225
226 #[test]
227 fn paths_match_exactly_after_anchoring() {
228 let patterns = compile(&["out/./log.txt", "/etc//hosts", "~/.profile"]).unwrap();
229 assert!(patterns.matches(&path("/work/task/out/log.txt")));
230 assert!(patterns.matches(&path("/etc/hosts")));
231 assert!(patterns.matches(&path("/home/me/.profile")));
232 assert!(!patterns.matches(&path("/work/task/out/log.txt.bak")));
233 assert!(!patterns.matches(&path("/work/task/out")));
234 assert!(!patterns.matches(&path("/etc/hosts/x")));
235 }
236
237 #[test]
238 fn globs_are_anchored_and_keep_components_apart() {
239 let patterns = compile(&["build/*.o", "~/.cache/go-build/**", "/tmp/[ab]?"]).unwrap();
240 assert!(patterns.matches(&path("/work/task/build/main.o")));
241 assert!(!patterns.matches(&path("/work/task/build/sub/main.o")));
242 assert!(!patterns.matches(&path("/elsewhere/build/main.o")));
243 assert!(patterns.matches(&path("/home/me/.cache/go-build/ab/cd-d")));
244 assert!(patterns.matches(&path("/tmp/a1")));
245 assert!(!patterns.matches(&path("/tmp/c1")));
246 }
247
248 #[test]
249 fn regular_expressions_match_absolute_paths() {
250 let patterns = compile(&[r"re:\.pyc$", r"re:^/var/"]).unwrap();
251 assert!(patterns.matches(&path("/work/task/a/b.pyc")));
252 assert!(patterns.matches(&path("/var/log")));
253 assert!(!patterns.matches(&path("/work/var/x")));
254 assert!(!patterns.is_empty());
255 assert!(compile(&[]).unwrap().is_empty());
256 }
257
258 #[test]
259 fn task_directories_with_glob_characters_are_escaped() {
260 let dir = path("/work/[x]");
261 let patterns = PathPatterns::new(&["*.txt".to_owned()], &dir, None).unwrap();
262 assert!(patterns.matches(&path("/work/[x]/a.txt")));
263 assert!(!patterns.matches(&path("/work/x/a.txt")));
264 }
265
266 #[test]
267 fn bad_patterns_are_errors() {
268 assert!(matches!(
269 compile(&["re:("]),
270 Err(PatternError::Regex { pattern, .. }) if pattern == "re:("
271 ));
272 assert!(matches!(
273 compile(&["a/[b"]),
274 Err(PatternError::Glob { pattern, .. }) if pattern == "a/[b"
275 ));
276 let error = PathPatterns::new(&["~/x".to_owned()], &path("/w"), None).unwrap_err();
277 assert_eq!(error, PatternError::NoHome {
278 pattern: "~/x".to_owned()
279 });
280 assert!(error.to_string().contains("no HOME"), "{error}");
281 }
282}