alint_rules/
file_max_size.rs1use alint_core::{Context, Error, Level, Result, Rule, RuleSpec, Scope, Violation};
4use serde::Deserialize;
5
6#[derive(Debug, Deserialize)]
7#[serde(deny_unknown_fields)]
8struct Options {
9 max_bytes: u64,
10}
11
12#[derive(Debug)]
13pub struct FileMaxSizeRule {
14 id: String,
15 level: Level,
16 policy_url: Option<String>,
17 message: Option<String>,
18 scope: Scope,
19 max_bytes: u64,
20}
21
22impl Rule for FileMaxSizeRule {
23 fn id(&self) -> &str {
24 &self.id
25 }
26 fn level(&self) -> Level {
27 self.level
28 }
29 fn policy_url(&self) -> Option<&str> {
30 self.policy_url.as_deref()
31 }
32
33 fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
34 let mut violations = Vec::new();
35 for entry in ctx.index.files() {
36 if !self.scope.matches(&entry.path, ctx.index) {
37 continue;
38 }
39 if entry.size > self.max_bytes {
40 let msg = self.message.clone().unwrap_or_else(|| {
41 format!(
42 "file exceeds {} byte(s) (actual: {})",
43 self.max_bytes, entry.size
44 )
45 });
46 violations.push(Violation::new(msg).with_path(entry.path.clone()));
47 }
48 }
49 Ok(violations)
50 }
51}
52
53pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
54 let Some(_paths) = &spec.paths else {
55 return Err(Error::rule_config(
56 &spec.id,
57 "file_max_size requires a `paths` field",
58 ));
59 };
60 let opts: Options = spec
61 .deserialize_options()
62 .map_err(|e| Error::rule_config(&spec.id, format!("invalid options: {e}")))?;
63 Ok(Box::new(FileMaxSizeRule {
64 id: spec.id.clone(),
65 level: spec.level,
66 policy_url: spec.policy_url.clone(),
67 message: spec.message.clone(),
68 scope: Scope::from_spec(spec)?,
69 max_bytes: opts.max_bytes,
70 }))
71}
72
73#[cfg(test)]
74mod tests {
75 use super::*;
76 use crate::test_support::{ctx, spec_yaml};
77 use alint_core::{FileEntry, FileIndex};
78 use std::path::Path;
79
80 fn idx_with_size(path: &str, size: u64) -> FileIndex {
81 FileIndex::from_entries(vec![FileEntry {
82 path: std::path::Path::new(path).into(),
83 is_dir: false,
84 size,
85 }])
86 }
87
88 #[test]
89 fn build_rejects_missing_paths_field() {
90 let spec = spec_yaml(
91 "id: t\n\
92 kind: file_max_size\n\
93 max_bytes: 1000\n\
94 level: warning\n",
95 );
96 assert!(build(&spec).is_err());
97 }
98
99 #[test]
100 fn build_rejects_missing_max_bytes() {
101 let spec = spec_yaml(
102 "id: t\n\
103 kind: file_max_size\n\
104 paths: \"**/*\"\n\
105 level: warning\n",
106 );
107 assert!(build(&spec).is_err());
108 }
109
110 #[test]
111 fn evaluate_passes_when_size_under_limit() {
112 let spec = spec_yaml(
113 "id: t\n\
114 kind: file_max_size\n\
115 paths: \"**/*\"\n\
116 max_bytes: 100\n\
117 level: warning\n",
118 );
119 let rule = build(&spec).unwrap();
120 let idx = idx_with_size("a.bin", 50);
121 let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
122 assert!(v.is_empty());
123 }
124
125 #[test]
126 fn evaluate_fires_when_size_over_limit() {
127 let spec = spec_yaml(
128 "id: t\n\
129 kind: file_max_size\n\
130 paths: \"**/*\"\n\
131 max_bytes: 100\n\
132 level: warning\n",
133 );
134 let rule = build(&spec).unwrap();
135 let idx = idx_with_size("big.bin", 1024);
136 let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
137 assert_eq!(v.len(), 1);
138 }
139
140 #[test]
141 fn evaluate_size_at_exact_limit_passes() {
142 let spec = spec_yaml(
145 "id: t\n\
146 kind: file_max_size\n\
147 paths: \"**/*\"\n\
148 max_bytes: 100\n\
149 level: warning\n",
150 );
151 let rule = build(&spec).unwrap();
152 let idx = idx_with_size("a.bin", 100);
153 let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
154 assert!(v.is_empty(), "size == max should pass: {v:?}");
155 }
156
157 #[test]
158 fn scope_filter_narrows() {
159 let spec = spec_yaml(
162 "id: t\n\
163 kind: file_max_size\n\
164 paths: \"**/*.bin\"\n\
165 max_bytes: 100\n\
166 scope_filter:\n \
167 has_ancestor: marker.lock\n\
168 level: warning\n",
169 );
170 let rule = build(&spec).unwrap();
171 let idx = FileIndex::from_entries(vec![
172 FileEntry {
173 path: std::path::Path::new("pkg/marker.lock").into(),
174 is_dir: false,
175 size: 1,
176 },
177 FileEntry {
178 path: std::path::Path::new("pkg/big.bin").into(),
179 is_dir: false,
180 size: 1024,
181 },
182 FileEntry {
183 path: std::path::Path::new("other/big.bin").into(),
184 is_dir: false,
185 size: 1024,
186 },
187 ]);
188 let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
189 assert_eq!(v.len(), 1, "only in-scope file should fire: {v:?}");
190 assert_eq!(v[0].path.as_deref(), Some(Path::new("pkg/big.bin")));
191 }
192}