Skip to main content

alint_rules/
file_absent.rs

1//! `file_absent` — emit a violation for every file matching `paths`.
2
3use alint_core::{
4    Context, Error, FixSpec, Fixer, Level, PathsSpec, Result, Rule, RuleSpec, Scope, Violation,
5};
6
7use crate::fixers::FileRemoveFixer;
8
9#[derive(Debug)]
10pub struct FileAbsentRule {
11    id: String,
12    level: Level,
13    policy_url: Option<String>,
14    message: Option<String>,
15    scope: Scope,
16    patterns: Vec<String>,
17    /// When `true`, only fire on entries that are also tracked
18    /// in git's index. Outside a git repo or with no rules
19    /// opting in, the tracked-set is `None` and every entry
20    /// reads as "untracked," so the rule becomes a no-op —
21    /// which is the right default for "don't let X be
22    /// committed" semantics.
23    git_tracked_only: bool,
24    fixer: Option<FileRemoveFixer>,
25}
26
27impl Rule for FileAbsentRule {
28    fn id(&self) -> &str {
29        &self.id
30    }
31    fn level(&self) -> Level {
32        self.level
33    }
34    fn policy_url(&self) -> Option<&str> {
35        self.policy_url.as_deref()
36    }
37    fn wants_git_tracked(&self) -> bool {
38        self.git_tracked_only
39    }
40
41    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
42        let mut violations = Vec::new();
43        for entry in ctx.index.files() {
44            if !self.scope.matches(&entry.path) {
45                continue;
46            }
47            if self.git_tracked_only && !ctx.is_git_tracked(&entry.path) {
48                continue;
49            }
50            let msg = self.message.clone().unwrap_or_else(|| {
51                let tracked = if self.git_tracked_only {
52                    " and tracked in git"
53                } else {
54                    ""
55                };
56                format!(
57                    "file is forbidden (matches [{}]{tracked}): {}",
58                    self.patterns.join(", "),
59                    entry.path.display()
60                )
61            });
62            violations.push(Violation::new(msg).with_path(&entry.path));
63        }
64        Ok(violations)
65    }
66
67    fn fixer(&self) -> Option<&dyn Fixer> {
68        self.fixer.as_ref().map(|f| f as &dyn Fixer)
69    }
70}
71
72pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
73    let Some(paths) = &spec.paths else {
74        return Err(Error::rule_config(
75            &spec.id,
76            "file_absent requires a `paths` field",
77        ));
78    };
79    let fixer = match &spec.fix {
80        Some(FixSpec::FileRemove { .. }) => Some(FileRemoveFixer),
81        Some(other) => {
82            return Err(Error::rule_config(
83                &spec.id,
84                format!("fix.{} is not compatible with file_absent", other.op_name()),
85            ));
86        }
87        None => None,
88    };
89    Ok(Box::new(FileAbsentRule {
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_paths_spec(paths)?,
95        patterns: patterns_of(paths),
96        git_tracked_only: spec.git_tracked_only,
97        fixer,
98    }))
99}
100
101fn patterns_of(spec: &PathsSpec) -> Vec<String> {
102    match spec {
103        PathsSpec::Single(s) => vec![s.clone()],
104        PathsSpec::Many(v) => v.clone(),
105        PathsSpec::IncludeExclude { include, .. } => include.clone(),
106    }
107}