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 git_tracked_mode(&self) -> alint_core::GitTrackedMode {
33        if self.git_tracked_only {
34            alint_core::GitTrackedMode::DirAware
35        } else {
36            alint_core::GitTrackedMode::Off
37        }
38    }
39
40    fn requires_full_index(&self) -> bool {
41        // See `dir_exists::requires_full_index` — directory
42        // scopes don't intersect a file-path-based changed-set
43        // cleanly, so we always evaluate this rule on the full
44        // tree in `--changed` mode. One O(N) scan per rule.
45        true
46    }
47
48    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
49        let mut violations = Vec::new();
50        // v0.9.11: when `git_tracked_only` is set the engine
51        // hands us a pre-filtered `ctx.index` (dir_aware mode);
52        // the per-entry `dir_has_tracked_files` check that lived
53        // here is now subsumed by the engine narrowing.
54        for entry in ctx.index.dirs() {
55            if !self.scope.matches(&entry.path, ctx.index) {
56                continue;
57            }
58            let msg = self.message.clone().unwrap_or_else(|| {
59                let tracked = if self.git_tracked_only {
60                    " and has tracked content"
61                } else {
62                    ""
63                };
64                format!(
65                    "directory is forbidden (matches [{}]{tracked}): {}",
66                    self.patterns.join(", "),
67                    entry.path.display()
68                )
69            });
70            violations.push(Violation::new(msg).with_path(entry.path.clone()));
71        }
72        Ok(violations)
73    }
74}
75
76pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
77    let Some(paths) = &spec.paths else {
78        return Err(Error::rule_config(
79            &spec.id,
80            "dir_absent requires a `paths` field",
81        ));
82    };
83    // v0.9.18: dir_absent honours `scope_filter` so the same
84    // ancestor-manifest gate that scopes per-file rules can scope
85    // dir-iterating rules — required by `hygiene-no-js-build-outputs`
86    // (only fire on `dist/`/`build/` whose ancestor chain contains
87    // a `package.json`, so polyglot monorepos with non-JS dirs of
88    // the same name don't see false positives).
89    Ok(Box::new(DirAbsentRule {
90        id: spec.id.clone(),
91        level: spec.level,
92        policy_url: spec.policy_url.clone(),
93        message: spec.message.clone(),
94        scope: Scope::from_spec(spec)?,
95        patterns: patterns_of(paths),
96        git_tracked_only: spec.git_tracked_only,
97    }))
98}
99
100fn patterns_of(spec: &PathsSpec) -> Vec<String> {
101    match spec {
102        PathsSpec::Single(s) => vec![s.clone()],
103        PathsSpec::Many(v) => v.clone(),
104        PathsSpec::IncludeExclude { include, .. } => include.clone(),
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111    use crate::test_support::{ctx, index_with_dirs, spec_yaml};
112    use std::path::Path;
113
114    #[test]
115    fn build_rejects_missing_paths_field() {
116        let spec = spec_yaml(
117            "id: t\n\
118             kind: dir_absent\n\
119             level: error\n",
120        );
121        let err = build(&spec).unwrap_err().to_string();
122        assert!(err.contains("paths"), "unexpected: {err}");
123    }
124
125    #[test]
126    fn evaluate_passes_when_no_matching_dir_present() {
127        let spec = spec_yaml(
128            "id: t\n\
129             kind: dir_absent\n\
130             paths: \"target\"\n\
131             level: error\n",
132        );
133        let rule = build(&spec).unwrap();
134        let idx = index_with_dirs(&[("src", true), ("docs", true)]);
135        let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
136        assert!(v.is_empty(), "unexpected: {v:?}");
137    }
138
139    #[test]
140    fn evaluate_fires_one_violation_per_forbidden_dir() {
141        let spec = spec_yaml(
142            "id: t\n\
143             kind: dir_absent\n\
144             paths: \"**/target\"\n\
145             level: error\n",
146        );
147        let rule = build(&spec).unwrap();
148        let idx = index_with_dirs(&[("target", true), ("crates/foo/target", true), ("src", true)]);
149        let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
150        assert_eq!(v.len(), 2, "expected one violation per target dir: {v:?}");
151    }
152
153    #[test]
154    fn evaluate_ignores_files_with_matching_name() {
155        let spec = spec_yaml(
156            "id: t\n\
157             kind: dir_absent\n\
158             paths: \"target\"\n\
159             level: error\n",
160        );
161        let rule = build(&spec).unwrap();
162        // A file named "target" should NOT fire `dir_absent`.
163        let idx = index_with_dirs(&[("target", false)]);
164        let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
165        assert!(v.is_empty(), "file named 'target' shouldn't fire");
166    }
167
168    #[test]
169    fn git_tracked_only_advertises_dir_aware_mode() {
170        // v0.9.11: the silent-no-op-outside-git-repo guarantee
171        // moved from a per-rule runtime check to an engine-side
172        // pre-filtered FileIndex. Calling `evaluate` directly
173        // bypasses the engine's filtering, so this unit test
174        // can no longer assert the no-op behaviour at the rule
175        // level — instead it asserts the rule advertises the
176        // correct `GitTrackedMode`, which is what tells the
177        // engine to substitute an empty index when the
178        // tracked-set is `None`. The end-to-end no-op behaviour
179        // is asserted by
180        // `crates/alint-e2e/scenarios/check/git/git_tracked_only_outside_git_silently_passes_absent.yml`.
181        let spec = spec_yaml(
182            "id: t\n\
183             kind: dir_absent\n\
184             paths: \"target\"\n\
185             level: error\n\
186             git_tracked_only: true\n",
187        );
188        let rule = build(&spec).unwrap();
189        assert_eq!(
190            rule.git_tracked_mode(),
191            alint_core::GitTrackedMode::DirAware,
192            "git_tracked_only on dir_absent must advertise DirAware mode",
193        );
194    }
195
196    #[test]
197    fn rule_advertises_full_index_requirement() {
198        let spec = spec_yaml(
199            "id: t\n\
200             kind: dir_absent\n\
201             paths: \"target\"\n\
202             level: error\n",
203        );
204        let rule = build(&spec).unwrap();
205        assert!(rule.requires_full_index());
206    }
207
208    #[test]
209    fn build_accepts_scope_filter() {
210        // v0.9.18: dir_absent honours `scope_filter` so the
211        // ancestor-manifest gate that scopes per-file rules can
212        // also scope dir-iterating rules. The build path must
213        // accept the field and bundle it into the rule's `Scope`.
214        let yaml = r#"
215id: t
216kind: dir_absent
217paths: "**/dist"
218level: warning
219scope_filter:
220  has_ancestor: package.json
221"#;
222        let spec = spec_yaml(yaml);
223        let rule = build(&spec).expect("scope_filter must be accepted on dir_absent");
224        assert_eq!(rule.id(), "t");
225    }
226}