use glob::Pattern;
use std::cell::RefCell;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Advice {
Before,
After,
Around,
}
struct Intercept {
pattern: Pattern,
advice: Advice,
handler: String,
}
thread_local! {
static INTERCEPTS: RefCell<Vec<Intercept>> = const { RefCell::new(Vec::new()) };
}
pub fn register(pattern: &str, advice: Advice, handler: &str) -> Result<(), String> {
let pat =
Pattern::new(pattern).map_err(|e| format!("bad intercept pattern '{pattern}': {e}"))?;
INTERCEPTS.with(|i| {
i.borrow_mut().push(Intercept {
pattern: pat,
advice,
handler: handler.to_string(),
})
});
Ok(())
}
pub fn clear() {
INTERCEPTS.with(|i| i.borrow_mut().clear());
}
pub fn matches(method: &str) -> Vec<(Advice, String)> {
INTERCEPTS.with(|i| {
i.borrow()
.iter()
.filter(|iv| iv.pattern.matches(method))
.map(|iv| (iv.advice, iv.handler.clone()))
.collect()
})
}
pub fn any() -> bool {
INTERCEPTS.with(|i| !i.borrow().is_empty())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn glob_matches_and_ordering() {
clear();
register("user_*", Advice::Before, "log_entry").unwrap();
register("__*__", Advice::Around, "guard_dunder").unwrap();
assert!(any());
let m = matches("user_create");
assert_eq!(m.len(), 1);
assert_eq!(m[0].0, Advice::Before);
let m = matches("__init__");
assert_eq!(m.len(), 1);
assert_eq!(m[0].1, "guard_dunder");
assert!(matches("plain").is_empty());
clear();
}
#[test]
fn bad_pattern_is_reported() {
assert!(register("[", Advice::Before, "x").is_err());
}
}