Skip to main content

alint_rules/
dir_absent.rs

1//! `dir_absent` — no directory matching `paths` may exist.
2
3use alint_core::{Context, Error, Level, PathsSpec, Result, Rule, RuleSpec, Scope, Violation};
4
5#[derive(Debug)]
6pub struct DirAbsentRule {
7    id: String,
8    level: Level,
9    policy_url: Option<String>,
10    message: Option<String>,
11    scope: Scope,
12    patterns: Vec<String>,
13}
14
15impl Rule for DirAbsentRule {
16    fn id(&self) -> &str {
17        &self.id
18    }
19    fn level(&self) -> Level {
20        self.level
21    }
22    fn policy_url(&self) -> Option<&str> {
23        self.policy_url.as_deref()
24    }
25
26    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
27        let mut violations = Vec::new();
28        for entry in ctx.index.dirs() {
29            if self.scope.matches(&entry.path) {
30                let msg = self.message.clone().unwrap_or_else(|| {
31                    format!(
32                        "directory is forbidden (matches [{}]): {}",
33                        self.patterns.join(", "),
34                        entry.path.display()
35                    )
36                });
37                violations.push(Violation::new(msg).with_path(&entry.path));
38            }
39        }
40        Ok(violations)
41    }
42}
43
44pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
45    let Some(paths) = &spec.paths else {
46        return Err(Error::rule_config(
47            &spec.id,
48            "dir_absent requires a `paths` field",
49        ));
50    };
51    Ok(Box::new(DirAbsentRule {
52        id: spec.id.clone(),
53        level: spec.level,
54        policy_url: spec.policy_url.clone(),
55        message: spec.message.clone(),
56        scope: Scope::from_paths_spec(paths)?,
57        patterns: patterns_of(paths),
58    }))
59}
60
61fn patterns_of(spec: &PathsSpec) -> Vec<String> {
62    match spec {
63        PathsSpec::Single(s) => vec![s.clone()],
64        PathsSpec::Many(v) => v.clone(),
65        PathsSpec::IncludeExclude { include, .. } => include.clone(),
66    }
67}