Skip to main content

alint_rules/
file_ends_with.rs

1//! `file_ends_with` — every file in scope must end with the
2//! configured suffix (byte-level).
3//!
4//! Useful for required trailing banners ("<!-- end-of-file -->"),
5//! closing magic bytes, or enforcing a generated-file sentinel.
6//! For the narrower "file must end with a newline" check, prefer
7//! `final_newline` — it has a dedicated fixer and integrates with
8//! the text-hygiene family.
9//!
10//! Check-only: the correct fix is `file_append` with matching
11//! content. Auto-appending implicitly could silently duplicate a
12//! near-matching tail.
13
14use std::path::Path;
15
16use alint_core::{Context, Error, Level, PerFileRule, Result, Rule, RuleSpec, Scope, Violation};
17use serde::Deserialize;
18
19use crate::io::read_suffix_n;
20
21#[derive(Debug, Deserialize)]
22#[serde(deny_unknown_fields)]
23struct Options {
24    /// The required suffix. Matched byte-for-byte.
25    suffix: String,
26}
27
28#[derive(Debug)]
29pub struct FileEndsWithRule {
30    id: String,
31    level: Level,
32    policy_url: Option<String>,
33    message: Option<String>,
34    scope: Scope,
35    suffix: Vec<u8>,
36}
37
38impl Rule for FileEndsWithRule {
39    alint_core::rule_common_impl!();
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, ctx.index) {
45                continue;
46            }
47            // Bounded read: only the trailing `suffix.len()`
48            // bytes matter. Solo runs (`alint fix --only`,
49            // tests) read just those bytes from the end.
50            let full = ctx.root.join(&entry.path);
51            let Ok(tail) = read_suffix_n(&full, self.suffix.len()) else {
52                continue;
53            };
54            violations.extend(self.evaluate_file(ctx, &entry.path, &tail)?);
55        }
56        Ok(violations)
57    }
58
59    fn as_per_file(&self) -> Option<&dyn PerFileRule> {
60        Some(self)
61    }
62}
63
64impl PerFileRule for FileEndsWithRule {
65    fn path_scope(&self) -> &Scope {
66        &self.scope
67    }
68
69    fn evaluate_file(
70        &self,
71        _ctx: &Context<'_>,
72        path: &Path,
73        bytes: &[u8],
74    ) -> Result<Vec<Violation>> {
75        if bytes.ends_with(&self.suffix) {
76            return Ok(Vec::new());
77        }
78        let msg = self
79            .message
80            .clone()
81            .unwrap_or_else(|| "file does not end with the required suffix".to_string());
82        Ok(vec![
83            Violation::new(msg).with_path(std::sync::Arc::<Path>::from(path)),
84        ])
85    }
86
87    fn max_bytes_needed(&self) -> Option<usize> {
88        Some(self.suffix.len())
89    }
90}
91
92pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
93    let _paths = spec
94        .paths
95        .as_ref()
96        .ok_or_else(|| Error::rule_config(&spec.id, "file_ends_with requires a `paths` field"))?;
97    let opts: Options = spec
98        .deserialize_options()
99        .map_err(|e| Error::rule_config(&spec.id, format!("invalid options: {e}")))?;
100    if opts.suffix.is_empty() {
101        return Err(Error::rule_config(
102            &spec.id,
103            "file_ends_with.suffix must not be empty",
104        ));
105    }
106    if spec.fix.is_some() {
107        return Err(Error::rule_config(
108            &spec.id,
109            "file_ends_with has no fix op — pair with an explicit `file_append` rule if you \
110             want auto-append (avoids silently duplicating near-matching suffixes).",
111        ));
112    }
113    Ok(Box::new(FileEndsWithRule {
114        id: spec.id.clone(),
115        level: spec.level,
116        policy_url: spec.policy_url.clone(),
117        message: spec.message.clone(),
118        scope: Scope::from_spec(spec)?,
119        suffix: opts.suffix.into_bytes(),
120    }))
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126    use crate::test_support::{ctx, spec_yaml, tempdir_with_files};
127
128    #[test]
129    fn build_rejects_missing_paths_field() {
130        let spec = spec_yaml(
131            "id: t\n\
132             kind: file_ends_with\n\
133             suffix: \"\\n\"\n\
134             level: error\n",
135        );
136        assert!(build(&spec).is_err());
137    }
138
139    #[test]
140    fn build_rejects_empty_suffix() {
141        let spec = spec_yaml(
142            "id: t\n\
143             kind: file_ends_with\n\
144             paths: \"**/*\"\n\
145             suffix: \"\"\n\
146             level: error\n",
147        );
148        let err = build(&spec).unwrap_err().to_string();
149        assert!(err.contains("empty"), "unexpected: {err}");
150    }
151
152    #[test]
153    fn build_rejects_fix_block() {
154        let spec = spec_yaml(
155            "id: t\n\
156             kind: file_ends_with\n\
157             paths: \"**/*\"\n\
158             suffix: \"\\n\"\n\
159             level: error\n\
160             fix:\n  \
161               file_append:\n    \
162                 content: \"x\"\n",
163        );
164        assert!(build(&spec).is_err());
165    }
166
167    #[test]
168    fn evaluate_passes_when_suffix_matches() {
169        let spec = spec_yaml(
170            "id: t\n\
171             kind: file_ends_with\n\
172             paths: \"**/*.txt\"\n\
173             suffix: \"END\\n\"\n\
174             level: error\n",
175        );
176        let rule = build(&spec).unwrap();
177        let (tmp, idx) = tempdir_with_files(&[("a.txt", b"hello\nEND\n")]);
178        let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
179        assert!(v.is_empty());
180    }
181
182    #[test]
183    fn evaluate_fires_when_suffix_missing() {
184        let spec = spec_yaml(
185            "id: t\n\
186             kind: file_ends_with\n\
187             paths: \"**/*.txt\"\n\
188             suffix: \"END\\n\"\n\
189             level: error\n",
190        );
191        let rule = build(&spec).unwrap();
192        let (tmp, idx) = tempdir_with_files(&[("a.txt", b"hello\n")]);
193        let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
194        assert_eq!(v.len(), 1);
195    }
196}