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