use std::collections::HashSet;
use super::word::{WordGlob, cannot_fail};
use super::{GlobPattern, ShellPattern, split_negation};
use crate::policy::PolicyError;
#[derive(Debug, Default)]
pub(crate) struct Checked {
globs: HashSet<String>,
words: HashSet<String>,
}
impl GlobPattern {
pub(crate) fn check(raw: &str, checked: &mut Checked) -> Result<(), PolicyError> {
let (_, body) = split_negation(raw);
if body.is_empty() {
return Err(PolicyError::EmptyPattern);
}
if cannot_fail(body) || checked.globs.contains(raw) {
return Ok(());
}
Self::compile(raw, false)?;
checked.globs.insert(raw.to_owned());
Ok(())
}
}
impl ShellPattern {
pub(crate) fn check(raw: &str, checked: &mut Checked) -> Result<(), PolicyError> {
let (_, words, _) = Self::words(raw)?;
for word in words {
if word == "*" || cannot_fail(&word) || checked.words.contains(&word) {
continue;
}
WordGlob::new(&word).map_err(|e| PolicyError::BadGlob {
pattern: raw.to_owned(),
error: e,
})?;
checked.words.insert(word);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::Checked;
use crate::pattern::{GlobPattern, ShellPattern};
#[test]
fn check_answers_as_compile_does() {
let globs = [
"/a/**",
"!/a/**",
"",
"!",
"**/.env",
"/a/{b,c}",
"/a/{b",
"/a/b}",
"[z-a]",
"a\\",
"/x/[ab]/**",
"/x/{a/**",
"*.pem",
"é/*",
];
let mut checked = Checked::default();
for g in globs.iter().chain(&globs) {
assert_eq!(
format!("{:?}", GlobPattern::check(g, &mut checked)),
format!("{:?}", GlobPattern::compile(g, false).map(drop)),
"{g}"
);
}
let shells = [
"git push --force*",
"!find * -exec*",
"",
"$",
"env $",
"{gh,*/gh} auth token*",
"{gh,*/gh} auth status",
"x {a",
"x [z-a] {b",
"cat <<EOF",
"echo 'unclosed",
"x a\\\\b",
"* | sh",
];
let mut checked = Checked::default();
for s in shells.iter().chain(&shells) {
assert_eq!(
format!("{:?}", ShellPattern::check(s, &mut checked)),
format!("{:?}", ShellPattern::compile(s).map(drop)),
"{s}"
);
}
}
}