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    fn id(&self) -> &str {
22        &self.id
23    }
24    fn level(&self) -> Level {
25        self.level
26    }
27    fn policy_url(&self) -> Option<&str> {
28        self.policy_url.as_deref()
29    }
30    fn wants_git_tracked(&self) -> bool {
31        self.git_tracked_only
32    }
33
34    fn requires_full_index(&self) -> bool {
35        // Aggregate verdict over the whole tree. Note we
36        // deliberately don't expose `path_scope` here: directory
37        // scopes (e.g. `src/foo`) don't naturally intersect a
38        // changed-set built from file paths (`src/foo/main.rs`),
39        // so the engine evaluates dir-existence rules on every
40        // `--changed` run. Cheap (one O(N) scan) and correct.
41        true
42    }
43
44    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
45        let found = ctx.index.dirs().any(|entry| {
46            if !self.scope.matches(&entry.path) {
47                return false;
48            }
49            if self.git_tracked_only && !ctx.dir_has_tracked_files(&entry.path) {
50                return false;
51            }
52            true
53        });
54        if found {
55            Ok(Vec::new())
56        } else {
57            let msg = self.message.clone().unwrap_or_else(|| {
58                let tracked = if self.git_tracked_only {
59                    " (with tracked content)"
60                } else {
61                    ""
62                };
63                format!(
64                    "expected a directory matching [{}]{tracked}",
65                    self.patterns.join(", ")
66                )
67            });
68            Ok(vec![Violation::new(msg)])
69        }
70    }
71}
72
73pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
74    let Some(paths) = &spec.paths else {
75        return Err(Error::rule_config(
76            &spec.id,
77            "dir_exists requires a `paths` field",
78        ));
79    };
80    Ok(Box::new(DirExistsRule {
81        id: spec.id.clone(),
82        level: spec.level,
83        policy_url: spec.policy_url.clone(),
84        message: spec.message.clone(),
85        scope: Scope::from_paths_spec(paths)?,
86        patterns: patterns_of(paths),
87        git_tracked_only: spec.git_tracked_only,
88    }))
89}
90
91fn patterns_of(spec: &PathsSpec) -> Vec<String> {
92    match spec {
93        PathsSpec::Single(s) => vec![s.clone()],
94        PathsSpec::Many(v) => v.clone(),
95        PathsSpec::IncludeExclude { include, .. } => include.clone(),
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102    use crate::test_support::{ctx, index_with_dirs, spec_yaml};
103    use std::path::Path;
104
105    #[test]
106    fn build_rejects_missing_paths_field() {
107        let spec = spec_yaml(
108            "id: t\n\
109             kind: dir_exists\n\
110             level: error\n",
111        );
112        let err = build(&spec).unwrap_err().to_string();
113        assert!(err.contains("paths"), "unexpected: {err}");
114    }
115
116    #[test]
117    fn evaluate_passes_when_matching_dir_present() {
118        let spec = spec_yaml(
119            "id: t\n\
120             kind: dir_exists\n\
121             paths: \"docs\"\n\
122             level: error\n",
123        );
124        let rule = build(&spec).unwrap();
125        let idx = index_with_dirs(&[("docs", true), ("docs/README.md", false)]);
126        let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
127        assert!(v.is_empty(), "unexpected: {v:?}");
128    }
129
130    #[test]
131    fn evaluate_fires_when_directory_missing() {
132        let spec = spec_yaml(
133            "id: t\n\
134             kind: dir_exists\n\
135             paths: \"docs\"\n\
136             level: error\n",
137        );
138        let rule = build(&spec).unwrap();
139        let idx = index_with_dirs(&[("README.md", false), ("src", true)]);
140        let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
141        assert_eq!(v.len(), 1, "missing dir should fire one violation");
142    }
143
144    #[test]
145    fn evaluate_skips_files_when_dir_glob_only_matches_dirs() {
146        // A file named `docs` must not satisfy a `dir_exists`
147        // rule — only entries with `is_dir: true` count.
148        let spec = spec_yaml(
149            "id: t\n\
150             kind: dir_exists\n\
151             paths: \"docs\"\n\
152             level: error\n",
153        );
154        let rule = build(&spec).unwrap();
155        let idx = index_with_dirs(&[("docs", false)]); // a file named "docs"
156        let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
157        assert_eq!(v.len(), 1);
158    }
159
160    #[test]
161    fn rule_advertises_full_index_requirement() {
162        let spec = spec_yaml(
163            "id: t\n\
164             kind: dir_exists\n\
165             paths: \"docs\"\n\
166             level: error\n",
167        );
168        let rule = build(&spec).unwrap();
169        assert!(rule.requires_full_index());
170    }
171
172    #[test]
173    fn git_tracked_only_propagates_to_wants_git_tracked() {
174        let spec = spec_yaml(
175            "id: t\n\
176             kind: dir_exists\n\
177             paths: \"src\"\n\
178             level: error\n\
179             git_tracked_only: true\n",
180        );
181        let rule = build(&spec).unwrap();
182        assert!(rule.wants_git_tracked());
183    }
184}