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 evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
35        let found = ctx.index.dirs().any(|entry| {
36            if !self.scope.matches(&entry.path) {
37                return false;
38            }
39            if self.git_tracked_only && !ctx.dir_has_tracked_files(&entry.path) {
40                return false;
41            }
42            true
43        });
44        if found {
45            Ok(Vec::new())
46        } else {
47            let msg = self.message.clone().unwrap_or_else(|| {
48                let tracked = if self.git_tracked_only {
49                    " (with tracked content)"
50                } else {
51                    ""
52                };
53                format!(
54                    "expected a directory matching [{}]{tracked}",
55                    self.patterns.join(", ")
56                )
57            });
58            Ok(vec![Violation::new(msg)])
59        }
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_exists requires a `paths` field",
68        ));
69    };
70    Ok(Box::new(DirExistsRule {
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}