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 requires_full_index(&self) -> bool {
42        // The verdict on "is X forbidden?" is over the whole tree —
43        // an unchanged-but-already-committed `.env` should still
44        // be visible. The engine skips this rule entirely when its
45        // scope doesn't intersect the diff, which is the usual
46        // user expectation in `--changed` mode.
47        true
48    }
49
50    fn path_scope(&self) -> Option<&Scope> {
51        Some(&self.scope)
52    }
53
54    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
55        let mut violations = Vec::new();
56        for entry in ctx.index.files() {
57            if !self.scope.matches(&entry.path) {
58                continue;
59            }
60            if self.git_tracked_only && !ctx.is_git_tracked(&entry.path) {
61                continue;
62            }
63            let msg = self.message.clone().unwrap_or_else(|| {
64                let tracked = if self.git_tracked_only {
65                    " and tracked in git"
66                } else {
67                    ""
68                };
69                format!(
70                    "file is forbidden (matches [{}]{tracked}): {}",
71                    self.patterns.join(", "),
72                    entry.path.display()
73                )
74            });
75            violations.push(Violation::new(msg).with_path(entry.path.clone()));
76        }
77        Ok(violations)
78    }
79
80    fn fixer(&self) -> Option<&dyn Fixer> {
81        self.fixer.as_ref().map(|f| f as &dyn Fixer)
82    }
83}
84
85pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
86    let Some(paths) = &spec.paths else {
87        return Err(Error::rule_config(
88            &spec.id,
89            "file_absent requires a `paths` field",
90        ));
91    };
92    let fixer = match &spec.fix {
93        Some(FixSpec::FileRemove { .. }) => Some(FileRemoveFixer),
94        Some(other) => {
95            return Err(Error::rule_config(
96                &spec.id,
97                format!("fix.{} is not compatible with file_absent", other.op_name()),
98            ));
99        }
100        None => None,
101    };
102    Ok(Box::new(FileAbsentRule {
103        id: spec.id.clone(),
104        level: spec.level,
105        policy_url: spec.policy_url.clone(),
106        message: spec.message.clone(),
107        scope: Scope::from_paths_spec(paths)?,
108        patterns: patterns_of(paths),
109        git_tracked_only: spec.git_tracked_only,
110        fixer,
111    }))
112}
113
114fn patterns_of(spec: &PathsSpec) -> Vec<String> {
115    match spec {
116        PathsSpec::Single(s) => vec![s.clone()],
117        PathsSpec::Many(v) => v.clone(),
118        PathsSpec::IncludeExclude { include, .. } => include.clone(),
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125    use crate::test_support::{ctx, index, spec_yaml};
126    use std::path::Path;
127
128    #[test]
129    fn build_rejects_missing_paths_field() {
130        let spec = spec_yaml(
131            "id: t\n\
132             kind: file_absent\n\
133             level: error\n",
134        );
135        let err = build(&spec).unwrap_err().to_string();
136        assert!(err.contains("paths"), "unexpected: {err}");
137    }
138
139    #[test]
140    fn build_rejects_incompatible_fix_op() {
141        // file_absent supports `file_remove` only; any other
142        // op surfaces a config error so a typo doesn't silently
143        // disable the fix path.
144        let spec = spec_yaml(
145            "id: t\n\
146             kind: file_absent\n\
147             paths: \"*.bak\"\n\
148             level: error\n\
149             fix:\n  \
150               file_create:\n    \
151                 content: \"\"\n",
152        );
153        let err = build(&spec).unwrap_err().to_string();
154        assert!(err.contains("file_create"), "unexpected: {err}");
155    }
156
157    #[test]
158    fn build_accepts_file_remove_fix() {
159        let spec = spec_yaml(
160            "id: t\n\
161             kind: file_absent\n\
162             paths: \"*.bak\"\n\
163             level: error\n\
164             fix:\n  \
165               file_remove: {}\n",
166        );
167        let rule = build(&spec).expect("valid file_remove fix");
168        assert!(rule.fixer().is_some(), "fixer should be present");
169    }
170
171    #[test]
172    fn evaluate_passes_when_no_match_present() {
173        let spec = spec_yaml(
174            "id: t\n\
175             kind: file_absent\n\
176             paths: \"*.bak\"\n\
177             level: error\n",
178        );
179        let rule = build(&spec).unwrap();
180        let idx = index(&["src/main.rs", "README.md"]);
181        let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
182        assert!(v.is_empty(), "unexpected: {v:?}");
183    }
184
185    #[test]
186    fn evaluate_fires_one_violation_per_match() {
187        let spec = spec_yaml(
188            "id: t\n\
189             kind: file_absent\n\
190             paths: \"**/*.bak\"\n\
191             level: error\n",
192        );
193        let rule = build(&spec).unwrap();
194        let idx = index(&["a.bak", "src/b.bak", "ok.txt"]);
195        let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
196        assert_eq!(v.len(), 2, "expected one violation per .bak: {v:?}");
197    }
198
199    #[test]
200    fn evaluate_silent_when_git_tracked_only_outside_repo() {
201        // git_tracked_only requires `ctx.git_tracked` to be
202        // populated; when it's None (no rule asked for it / no
203        // git repo), every path reads as "untracked" and the
204        // rule no-ops — the right default for "don't let X be
205        // committed" semantics.
206        let spec = spec_yaml(
207            "id: t\n\
208             kind: file_absent\n\
209             paths: \"*.bak\"\n\
210             level: error\n\
211             git_tracked_only: true\n",
212        );
213        let rule = build(&spec).unwrap();
214        let idx = index(&["a.bak"]);
215        let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
216        assert!(
217            v.is_empty(),
218            "git_tracked_only without ctx.git_tracked must no-op: {v:?}",
219        );
220    }
221
222    #[test]
223    fn rule_advertises_full_index_requirement() {
224        // Existence-axis rules opt out of changed-mode
225        // filtering — an unchanged-but-already-committed `.env`
226        // should still fire.
227        let spec = spec_yaml(
228            "id: t\n\
229             kind: file_absent\n\
230             paths: \".env\"\n\
231             level: error\n",
232        );
233        let rule = build(&spec).unwrap();
234        assert!(rule.requires_full_index());
235    }
236}