Skip to main content

alint_rules/
dir_exists.rs

1//! `dir_exists` — at least one directory matching `paths` must exist.
2
3use alint_core::{Context, Error, Level, PathsSpec, Result, Rule, RuleSpec, Scope, Violation};
4
5#[derive(Debug)]
6pub struct DirExistsRule {
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 consider directories that contain at
14    /// least one git-tracked file. Outside a git repo the
15    /// tracked set is empty, so the rule reports the "missing"
16    /// violation as if no matching directory existed.
17    git_tracked_only: bool,
18}
19
20impl Rule for DirExistsRule {
21    alint_core::rule_common_impl!();
22    fn git_tracked_mode(&self) -> alint_core::GitTrackedMode {
23        if self.git_tracked_only {
24            alint_core::GitTrackedMode::DirAware
25        } else {
26            alint_core::GitTrackedMode::Off
27        }
28    }
29
30    fn requires_full_index(&self) -> bool {
31        // Aggregate verdict over the whole tree. Note we
32        // deliberately don't expose `path_scope` here: directory
33        // scopes (e.g. `src/foo`) don't naturally intersect a
34        // changed-set built from file paths (`src/foo/main.rs`),
35        // so the engine evaluates dir-existence rules on every
36        // `--changed` run. Cheap (one O(N) scan) and correct.
37        true
38    }
39
40    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
41        // v0.9.11: when `git_tracked_only` is set the engine
42        // hands us a pre-filtered `ctx.index` (dir_aware mode);
43        // the per-entry `dir_has_tracked_files` check that lived
44        // here is now subsumed by the engine narrowing.
45        let found = ctx.index.dirs().any(|entry| {
46            if !self.scope.matches(&entry.path, ctx.index) {
47                return false;
48            }
49            true
50        });
51        if found {
52            Ok(Vec::new())
53        } else {
54            let msg = self.message.clone().unwrap_or_else(|| {
55                let tracked = if self.git_tracked_only {
56                    " (with tracked content)"
57                } else {
58                    ""
59                };
60                format!(
61                    "expected a directory matching [{}]{tracked}",
62                    self.patterns.join(", ")
63                )
64            });
65            Ok(vec![Violation::new(msg)])
66        }
67    }
68}
69
70pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
71    alint_core::reject_scope_filter_on_cross_file(spec, "dir_exists")?;
72    let Some(paths) = &spec.paths else {
73        return Err(Error::rule_config(
74            &spec.id,
75            "dir_exists requires a `paths` field",
76        ));
77    };
78    Ok(Box::new(DirExistsRule {
79        id: spec.id.clone(),
80        level: spec.level,
81        policy_url: spec.policy_url.clone(),
82        message: spec.message.clone(),
83        scope: Scope::from_paths_spec(paths)?,
84        patterns: patterns_of(paths),
85        git_tracked_only: spec.git_tracked_only,
86    }))
87}
88
89fn patterns_of(spec: &PathsSpec) -> Vec<String> {
90    match spec {
91        PathsSpec::Single(s) => vec![s.clone()],
92        PathsSpec::Many(v) => v.clone(),
93        PathsSpec::IncludeExclude { include, .. } => include.clone(),
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100    use crate::test_support::{ctx, index_with_dirs, spec_yaml};
101    use std::path::Path;
102
103    #[test]
104    fn build_rejects_missing_paths_field() {
105        let spec = spec_yaml(
106            "id: t\n\
107             kind: dir_exists\n\
108             level: error\n",
109        );
110        let err = build(&spec).unwrap_err().to_string();
111        assert!(err.contains("paths"), "unexpected: {err}");
112    }
113
114    #[test]
115    fn evaluate_passes_when_matching_dir_present() {
116        let spec = spec_yaml(
117            "id: t\n\
118             kind: dir_exists\n\
119             paths: \"docs\"\n\
120             level: error\n",
121        );
122        let rule = build(&spec).unwrap();
123        let idx = index_with_dirs(&[("docs", true), ("docs/README.md", false)]);
124        let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
125        assert!(v.is_empty(), "unexpected: {v:?}");
126    }
127
128    #[test]
129    fn evaluate_fires_when_directory_missing() {
130        let spec = spec_yaml(
131            "id: t\n\
132             kind: dir_exists\n\
133             paths: \"docs\"\n\
134             level: error\n",
135        );
136        let rule = build(&spec).unwrap();
137        let idx = index_with_dirs(&[("README.md", false), ("src", true)]);
138        let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
139        assert_eq!(v.len(), 1, "missing dir should fire one violation");
140    }
141
142    #[test]
143    fn evaluate_skips_files_when_dir_glob_only_matches_dirs() {
144        // A file named `docs` must not satisfy a `dir_exists`
145        // rule — only entries with `is_dir: true` count.
146        let spec = spec_yaml(
147            "id: t\n\
148             kind: dir_exists\n\
149             paths: \"docs\"\n\
150             level: error\n",
151        );
152        let rule = build(&spec).unwrap();
153        let idx = index_with_dirs(&[("docs", false)]); // a file named "docs"
154        let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
155        assert_eq!(v.len(), 1);
156    }
157
158    #[test]
159    fn rule_advertises_full_index_requirement() {
160        let spec = spec_yaml(
161            "id: t\n\
162             kind: dir_exists\n\
163             paths: \"docs\"\n\
164             level: error\n",
165        );
166        let rule = build(&spec).unwrap();
167        assert!(rule.requires_full_index());
168    }
169
170    #[test]
171    fn git_tracked_only_advertises_dir_aware_mode() {
172        let spec = spec_yaml(
173            "id: t\n\
174             kind: dir_exists\n\
175             paths: \"src\"\n\
176             level: error\n\
177             git_tracked_only: true\n",
178        );
179        let rule = build(&spec).unwrap();
180        assert_eq!(
181            rule.git_tracked_mode(),
182            alint_core::GitTrackedMode::DirAware,
183        );
184    }
185
186    #[test]
187    fn build_rejects_scope_filter_on_cross_file_rule() {
188        // dir_exists is a cross-file rule (requires_full_index =
189        // true); scope_filter is per-file-rules-only. The build
190        // path must reject it with a clear message pointing at
191        // the for_each_dir + when_iter: alternative.
192        let yaml = r#"
193id: t
194kind: dir_exists
195paths: "docs"
196level: error
197scope_filter:
198  has_ancestor: Cargo.toml
199"#;
200        let spec = spec_yaml(yaml);
201        let err = build(&spec).unwrap_err().to_string();
202        assert!(
203            err.contains("scope_filter is supported on per-file rules only"),
204            "expected per-file-only message, got: {err}",
205        );
206        assert!(
207            err.contains("dir_exists"),
208            "expected message to name the cross-file kind, got: {err}",
209        );
210    }
211}