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 alint_core::{Context, Error, Level, Result, Rule, RuleSpec, Scope, Violation};
15use serde::Deserialize;
16
17#[derive(Debug, Deserialize)]
18#[serde(deny_unknown_fields)]
19struct Options {
20    /// The required suffix. Matched byte-for-byte.
21    suffix: String,
22}
23
24#[derive(Debug)]
25pub struct FileEndsWithRule {
26    id: String,
27    level: Level,
28    policy_url: Option<String>,
29    message: Option<String>,
30    scope: Scope,
31    suffix: Vec<u8>,
32}
33
34impl Rule for FileEndsWithRule {
35    fn id(&self) -> &str {
36        &self.id
37    }
38    fn level(&self) -> Level {
39        self.level
40    }
41    fn policy_url(&self) -> Option<&str> {
42        self.policy_url.as_deref()
43    }
44
45    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
46        let mut violations = Vec::new();
47        for entry in ctx.index.files() {
48            if !self.scope.matches(&entry.path) {
49                continue;
50            }
51            let full = ctx.root.join(&entry.path);
52            let Ok(bytes) = std::fs::read(&full) else {
53                continue;
54            };
55            if !bytes.ends_with(&self.suffix) {
56                let msg = self
57                    .message
58                    .clone()
59                    .unwrap_or_else(|| "file does not end with the required suffix".to_string());
60                violations.push(Violation::new(msg).with_path(&entry.path));
61            }
62        }
63        Ok(violations)
64    }
65}
66
67pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
68    let paths = spec
69        .paths
70        .as_ref()
71        .ok_or_else(|| Error::rule_config(&spec.id, "file_ends_with requires a `paths` field"))?;
72    let opts: Options = spec
73        .deserialize_options()
74        .map_err(|e| Error::rule_config(&spec.id, format!("invalid options: {e}")))?;
75    if opts.suffix.is_empty() {
76        return Err(Error::rule_config(
77            &spec.id,
78            "file_ends_with.suffix must not be empty",
79        ));
80    }
81    if spec.fix.is_some() {
82        return Err(Error::rule_config(
83            &spec.id,
84            "file_ends_with has no fix op — pair with an explicit `file_append` rule if you \
85             want auto-append (avoids silently duplicating near-matching suffixes).",
86        ));
87    }
88    Ok(Box::new(FileEndsWithRule {
89        id: spec.id.clone(),
90        level: spec.level,
91        policy_url: spec.policy_url.clone(),
92        message: spec.message.clone(),
93        scope: Scope::from_paths_spec(paths)?,
94        suffix: opts.suffix.into_bytes(),
95    }))
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::test_support::{ctx, spec_yaml, tempdir_with_files};
102
103    #[test]
104    fn build_rejects_missing_paths_field() {
105        let spec = spec_yaml(
106            "id: t\n\
107             kind: file_ends_with\n\
108             suffix: \"\\n\"\n\
109             level: error\n",
110        );
111        assert!(build(&spec).is_err());
112    }
113
114    #[test]
115    fn build_rejects_empty_suffix() {
116        let spec = spec_yaml(
117            "id: t\n\
118             kind: file_ends_with\n\
119             paths: \"**/*\"\n\
120             suffix: \"\"\n\
121             level: error\n",
122        );
123        let err = build(&spec).unwrap_err().to_string();
124        assert!(err.contains("empty"), "unexpected: {err}");
125    }
126
127    #[test]
128    fn build_rejects_fix_block() {
129        let spec = spec_yaml(
130            "id: t\n\
131             kind: file_ends_with\n\
132             paths: \"**/*\"\n\
133             suffix: \"\\n\"\n\
134             level: error\n\
135             fix:\n  \
136               file_append:\n    \
137                 content: \"x\"\n",
138        );
139        assert!(build(&spec).is_err());
140    }
141
142    #[test]
143    fn evaluate_passes_when_suffix_matches() {
144        let spec = spec_yaml(
145            "id: t\n\
146             kind: file_ends_with\n\
147             paths: \"**/*.txt\"\n\
148             suffix: \"END\\n\"\n\
149             level: error\n",
150        );
151        let rule = build(&spec).unwrap();
152        let (tmp, idx) = tempdir_with_files(&[("a.txt", b"hello\nEND\n")]);
153        let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
154        assert!(v.is_empty());
155    }
156
157    #[test]
158    fn evaluate_fires_when_suffix_missing() {
159        let spec = spec_yaml(
160            "id: t\n\
161             kind: file_ends_with\n\
162             paths: \"**/*.txt\"\n\
163             suffix: \"END\\n\"\n\
164             level: error\n",
165        );
166        let rule = build(&spec).unwrap();
167        let (tmp, idx) = tempdir_with_files(&[("a.txt", b"hello\n")]);
168        let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
169        assert_eq!(v.len(), 1);
170    }
171}