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}
14
15impl Rule for DirExistsRule {
16    fn id(&self) -> &str {
17        &self.id
18    }
19    fn level(&self) -> Level {
20        self.level
21    }
22    fn policy_url(&self) -> Option<&str> {
23        self.policy_url.as_deref()
24    }
25
26    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
27        let found = ctx
28            .index
29            .dirs()
30            .any(|entry| self.scope.matches(&entry.path));
31        if found {
32            Ok(Vec::new())
33        } else {
34            let msg = self.message.clone().unwrap_or_else(|| {
35                format!(
36                    "expected a directory matching [{}]",
37                    self.patterns.join(", ")
38                )
39            });
40            Ok(vec![Violation::new(msg)])
41        }
42    }
43}
44
45pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
46    let Some(paths) = &spec.paths else {
47        return Err(Error::rule_config(
48            &spec.id,
49            "dir_exists requires a `paths` field",
50        ));
51    };
52    Ok(Box::new(DirExistsRule {
53        id: spec.id.clone(),
54        level: spec.level,
55        policy_url: spec.policy_url.clone(),
56        message: spec.message.clone(),
57        scope: Scope::from_paths_spec(paths)?,
58        patterns: patterns_of(paths),
59    }))
60}
61
62fn patterns_of(spec: &PathsSpec) -> Vec<String> {
63    match spec {
64        PathsSpec::Single(s) => vec![s.clone()],
65        PathsSpec::Many(v) => v.clone(),
66        PathsSpec::IncludeExclude { include, .. } => include.clone(),
67    }
68}