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    /// When `true`, only fire on directories that contain at
14    /// least one git-tracked file. The canonical use case is
15    /// "don't let `target/` be committed" — with this flag set,
16    /// a developer's locally-built `target/` (gitignored, no
17    /// tracked content) doesn't trigger; a `target/` whose
18    /// contents made it into git's index does.
19    git_tracked_only: bool,
20}
21
22impl Rule for DirAbsentRule {
23    fn id(&self) -> &str {
24        &self.id
25    }
26    fn level(&self) -> Level {
27        self.level
28    }
29    fn policy_url(&self) -> Option<&str> {
30        self.policy_url.as_deref()
31    }
32    fn wants_git_tracked(&self) -> bool {
33        self.git_tracked_only
34    }
35
36    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
37        let mut violations = Vec::new();
38        for entry in ctx.index.dirs() {
39            if !self.scope.matches(&entry.path) {
40                continue;
41            }
42            if self.git_tracked_only && !ctx.dir_has_tracked_files(&entry.path) {
43                continue;
44            }
45            let msg = self.message.clone().unwrap_or_else(|| {
46                let tracked = if self.git_tracked_only {
47                    " and has tracked content"
48                } else {
49                    ""
50                };
51                format!(
52                    "directory is forbidden (matches [{}]{tracked}): {}",
53                    self.patterns.join(", "),
54                    entry.path.display()
55                )
56            });
57            violations.push(Violation::new(msg).with_path(&entry.path));
58        }
59        Ok(violations)
60    }
61}
62
63pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
64    let Some(paths) = &spec.paths else {
65        return Err(Error::rule_config(
66            &spec.id,
67            "dir_absent requires a `paths` field",
68        ));
69    };
70    Ok(Box::new(DirAbsentRule {
71        id: spec.id.clone(),
72        level: spec.level,
73        policy_url: spec.policy_url.clone(),
74        message: spec.message.clone(),
75        scope: Scope::from_paths_spec(paths)?,
76        patterns: patterns_of(paths),
77        git_tracked_only: spec.git_tracked_only,
78    }))
79}
80
81fn patterns_of(spec: &PathsSpec) -> Vec<String> {
82    match spec {
83        PathsSpec::Single(s) => vec![s.clone()],
84        PathsSpec::Many(v) => v.clone(),
85        PathsSpec::IncludeExclude { include, .. } => include.clone(),
86    }
87}