Skip to main content

alint_rules/
file_max_size.rs

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