Skip to main content

kizz_core/
patterns.rs

1// Copyright (c) 2026 Sakura Industries LLC.
2//
3// SPDX-License-Identifier: AGPL-3.0-only
4
5//! The path patterns of `ignore` and `track`.
6//!
7//! A pattern is a path, a glob, or a regular expression prefixed with `re:`, and it
8//! is matched against absolute paths:
9//!
10//! * `re:` patterns are regular expressions that match anywhere in the path unless they
11//!   are anchored with `^` and `$`.
12//! * Any other pattern with a glob character (`*`, `?`, `[`, or `{`) is a glob, in which
13//!   `*` and `?` stay within one path component and `**` crosses components.
14//! * Every other pattern is a path, which matches exactly that path.
15//!
16//! A relative path or glob is anchored at the task directory, and a leading `~/`
17//! means the caller's home directory. Paths are normalized as the tracer reports
18//! them, so `a/./b` and `a//b` match `a/b`.
19
20use std::{os::unix::ffi::OsStrExt as _, path::Path};
21
22use globset::{GlobBuilder, GlobSet, GlobSetBuilder};
23use kizz_trace::AbsolutePath;
24use regex::bytes::{Regex, RegexSet};
25
26/// The prefix of a regular-expression pattern.
27pub const REGEX_PREFIX: &str = "re:";
28
29/// The prefix that stands for the caller's home directory.
30const HOME_PREFIX: &str = "~/";
31
32/// The characters that make a pattern a glob.
33const GLOB_CHARACTERS: [char; 4] = ['*', '?', '[', '{'];
34
35/// A pattern that cannot be used.
36#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
37pub enum PatternError {
38    /// A glob is malformed.
39    #[error("invalid glob pattern `{pattern}`: {message}")]
40    Glob {
41        /// The pattern, as written.
42        pattern: String,
43        /// What is wrong with it.
44        message: String,
45    },
46    /// A regular expression is malformed.
47    #[error("invalid regular expression in pattern `{pattern}`: {message}")]
48    Regex {
49        /// The pattern, as written.
50        pattern: String,
51        /// What is wrong with it.
52        message: String,
53    },
54    /// A pattern starts with `~/`, but the caller environment has no home directory.
55    #[error("pattern `{pattern}` starts with `~/`, but the caller environment has no HOME")]
56    NoHome {
57        /// The pattern, as written.
58        pattern: String,
59    },
60}
61
62/// A set of `ignore` or `track` patterns, ready to match absolute paths.
63#[derive(Debug, Clone)]
64pub struct PathPatterns {
65    /// The exact paths.
66    paths: Vec<AbsolutePath>,
67    /// The globs, anchored.
68    globs: GlobSet,
69    /// The regular expressions.
70    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
83/// Whether `pattern` holds a glob character.
84fn is_glob(pattern: &str) -> bool {
85    pattern.contains(GLOB_CHARACTERS)
86}
87
88impl PathPatterns {
89    /// Compile `patterns`, anchoring relative ones at `task_dir` and expanding a
90    /// leading `~/` to `home`, the caller's home directory.
91    ///
92    /// # Errors
93    ///
94    /// Returns [`PatternError`] for a malformed glob or regular expression, and for a
95    /// pattern that starts with `~/` when `home` is `None`.
96    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                // An absolute pattern replaces the task directory when joined to it.
124                (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(&regexes).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    /// Whether the set holds no pattern.
166    #[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    /// Whether any pattern matches the absolute path `path`.
172    #[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
183/// The glob `rest`, anchored at `base` unless it is absolute, with `.` components and
184/// repeated separators removed, as the tracer normalizes paths.
185fn 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/// Unit tests for each pattern form.
205#[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    /// An absolute path for a test.
215    fn path(text: &str) -> AbsolutePath {
216        AbsolutePath::new(text).unwrap()
217    }
218
219    /// The patterns `patterns` for a task in `/work/task` of a caller whose home is
220    /// `/home/me`.
221    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}