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