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 git_tracked_mode(&self) -> alint_core::GitTrackedMode {
38        if self.git_tracked_only {
39            alint_core::GitTrackedMode::FileOnly
40        } else {
41            alint_core::GitTrackedMode::Off
42        }
43    }
44
45    fn requires_full_index(&self) -> bool {
46        // The verdict on "is X forbidden?" is over the whole tree —
47        // an unchanged-but-already-committed `.env` should still
48        // be visible. The engine skips this rule entirely when its
49        // scope doesn't intersect the diff, which is the usual
50        // user expectation in `--changed` mode.
51        true
52    }
53
54    fn path_scope(&self) -> Option<&Scope> {
55        Some(&self.scope)
56    }
57
58    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
59        let mut violations = Vec::new();
60        // v0.9.11: when `git_tracked_only` is set the engine
61        // hands us a pre-filtered `ctx.index` (file_only mode);
62        // the per-entry `is_git_tracked` check that lived here
63        // is now subsumed by the engine-side narrowing.
64        for entry in ctx.index.files() {
65            if !self.scope.matches(&entry.path, ctx.index) {
66                continue;
67            }
68            let msg = self.message.clone().unwrap_or_else(|| {
69                let tracked = if self.git_tracked_only {
70                    " and tracked in git"
71                } else {
72                    ""
73                };
74                format!(
75                    "file is forbidden (matches [{}]{tracked}): {}",
76                    self.patterns.join(", "),
77                    entry.path.display()
78                )
79            });
80            violations.push(Violation::new(msg).with_path(entry.path.clone()));
81        }
82        Ok(violations)
83    }
84
85    fn fixer(&self) -> Option<&dyn Fixer> {
86        self.fixer.as_ref().map(|f| f as &dyn Fixer)
87    }
88}
89
90pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
91    alint_core::reject_scope_filter_on_cross_file(spec, "file_absent")?;
92    let Some(paths) = &spec.paths else {
93        return Err(Error::rule_config(
94            &spec.id,
95            "file_absent requires a `paths` field",
96        ));
97    };
98    let fixer = match &spec.fix {
99        Some(FixSpec::FileRemove { .. }) => Some(FileRemoveFixer),
100        Some(other) => {
101            return Err(Error::rule_config(
102                &spec.id,
103                format!("fix.{} is not compatible with file_absent", other.op_name()),
104            ));
105        }
106        None => None,
107    };
108    Ok(Box::new(FileAbsentRule {
109        id: spec.id.clone(),
110        level: spec.level,
111        policy_url: spec.policy_url.clone(),
112        message: spec.message.clone(),
113        scope: Scope::from_paths_spec(paths)?,
114        patterns: patterns_of(paths),
115        git_tracked_only: spec.git_tracked_only,
116        fixer,
117    }))
118}
119
120fn patterns_of(spec: &PathsSpec) -> Vec<String> {
121    match spec {
122        PathsSpec::Single(s) => vec![s.clone()],
123        PathsSpec::Many(v) => v.clone(),
124        PathsSpec::IncludeExclude { include, .. } => include.clone(),
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131    use crate::test_support::{ctx, index, spec_yaml};
132    use std::path::Path;
133
134    #[test]
135    fn build_rejects_missing_paths_field() {
136        let spec = spec_yaml(
137            "id: t\n\
138             kind: file_absent\n\
139             level: error\n",
140        );
141        let err = build(&spec).unwrap_err().to_string();
142        assert!(err.contains("paths"), "unexpected: {err}");
143    }
144
145    #[test]
146    fn build_rejects_incompatible_fix_op() {
147        // file_absent supports `file_remove` only; any other
148        // op surfaces a config error so a typo doesn't silently
149        // disable the fix path.
150        let spec = spec_yaml(
151            "id: t\n\
152             kind: file_absent\n\
153             paths: \"*.bak\"\n\
154             level: error\n\
155             fix:\n  \
156               file_create:\n    \
157                 content: \"\"\n",
158        );
159        let err = build(&spec).unwrap_err().to_string();
160        assert!(err.contains("file_create"), "unexpected: {err}");
161    }
162
163    #[test]
164    fn build_accepts_file_remove_fix() {
165        let spec = spec_yaml(
166            "id: t\n\
167             kind: file_absent\n\
168             paths: \"*.bak\"\n\
169             level: error\n\
170             fix:\n  \
171               file_remove: {}\n",
172        );
173        let rule = build(&spec).expect("valid file_remove fix");
174        assert!(rule.fixer().is_some(), "fixer should be present");
175    }
176
177    #[test]
178    fn evaluate_passes_when_no_match_present() {
179        let spec = spec_yaml(
180            "id: t\n\
181             kind: file_absent\n\
182             paths: \"*.bak\"\n\
183             level: error\n",
184        );
185        let rule = build(&spec).unwrap();
186        let idx = index(&["src/main.rs", "README.md"]);
187        let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
188        assert!(v.is_empty(), "unexpected: {v:?}");
189    }
190
191    #[test]
192    fn evaluate_fires_one_violation_per_match() {
193        let spec = spec_yaml(
194            "id: t\n\
195             kind: file_absent\n\
196             paths: \"**/*.bak\"\n\
197             level: error\n",
198        );
199        let rule = build(&spec).unwrap();
200        let idx = index(&["a.bak", "src/b.bak", "ok.txt"]);
201        let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
202        assert_eq!(v.len(), 2, "expected one violation per .bak: {v:?}");
203    }
204
205    #[test]
206    fn git_tracked_only_advertises_file_only_mode() {
207        // v0.9.11: the silent-no-op-outside-git-repo guarantee
208        // moved from a per-rule runtime check to an engine-side
209        // pre-filtered FileIndex. Calling `evaluate` directly
210        // bypasses the engine's filtering, so this unit test
211        // can no longer assert the no-op behaviour at the rule
212        // level — instead it asserts the rule advertises the
213        // correct `GitTrackedMode`, which is what tells the
214        // engine to substitute an empty index when the
215        // tracked-set is `None`. The end-to-end no-op behaviour
216        // is asserted by the e2e scenarios under
217        // `crates/alint-e2e/scenarios/check/git/`.
218        let spec = spec_yaml(
219            "id: t\n\
220             kind: file_absent\n\
221             paths: \"*.bak\"\n\
222             level: error\n\
223             git_tracked_only: true\n",
224        );
225        let rule = build(&spec).unwrap();
226        assert_eq!(
227            rule.git_tracked_mode(),
228            alint_core::GitTrackedMode::FileOnly,
229            "git_tracked_only on file_absent must advertise FileOnly mode",
230        );
231    }
232
233    #[test]
234    fn rule_advertises_full_index_requirement() {
235        // Existence-axis rules opt out of changed-mode
236        // filtering — an unchanged-but-already-committed `.env`
237        // should still fire.
238        let spec = spec_yaml(
239            "id: t\n\
240             kind: file_absent\n\
241             paths: \".env\"\n\
242             level: error\n",
243        );
244        let rule = build(&spec).unwrap();
245        assert!(rule.requires_full_index());
246    }
247
248    #[test]
249    fn build_rejects_scope_filter_on_cross_file_rule() {
250        // file_absent is a cross-file rule (requires_full_index =
251        // true); scope_filter is per-file-rules-only. The build
252        // path must reject it with a clear message pointing at
253        // the for_each_dir + when_iter: alternative.
254        let yaml = r#"
255id: t
256kind: file_absent
257paths: "*.bak"
258level: error
259scope_filter:
260  has_ancestor: Cargo.toml
261"#;
262        let spec = spec_yaml(yaml);
263        let err = build(&spec).unwrap_err().to_string();
264        assert!(
265            err.contains("scope_filter is supported on per-file rules only"),
266            "expected per-file-only message, got: {err}",
267        );
268        assert!(
269            err.contains("file_absent"),
270            "expected message to name the cross-file kind, got: {err}",
271        );
272    }
273}