alint_rules/
file_ends_with.rs1use 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 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}