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::from_entries(vec![FileEntry {
81            path: std::path::Path::new(path).into(),
82            is_dir: false,
83            size,
84        }])
85    }
86
87    #[test]
88    fn build_rejects_missing_paths_field() {
89        let spec = spec_yaml(
90            "id: t\n\
91             kind: file_max_size\n\
92             max_bytes: 1000\n\
93             level: warning\n",
94        );
95        assert!(build(&spec).is_err());
96    }
97
98    #[test]
99    fn build_rejects_missing_max_bytes() {
100        let spec = spec_yaml(
101            "id: t\n\
102             kind: file_max_size\n\
103             paths: \"**/*\"\n\
104             level: warning\n",
105        );
106        assert!(build(&spec).is_err());
107    }
108
109    #[test]
110    fn evaluate_passes_when_size_under_limit() {
111        let spec = spec_yaml(
112            "id: t\n\
113             kind: file_max_size\n\
114             paths: \"**/*\"\n\
115             max_bytes: 100\n\
116             level: warning\n",
117        );
118        let rule = build(&spec).unwrap();
119        let idx = idx_with_size("a.bin", 50);
120        let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
121        assert!(v.is_empty());
122    }
123
124    #[test]
125    fn evaluate_fires_when_size_over_limit() {
126        let spec = spec_yaml(
127            "id: t\n\
128             kind: file_max_size\n\
129             paths: \"**/*\"\n\
130             max_bytes: 100\n\
131             level: warning\n",
132        );
133        let rule = build(&spec).unwrap();
134        let idx = idx_with_size("big.bin", 1024);
135        let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
136        assert_eq!(v.len(), 1);
137    }
138
139    #[test]
140    fn evaluate_size_at_exact_limit_passes() {
141        // Boundary: `entry.size > max_bytes` is strict, so a
142        // file at exactly max_bytes is OK.
143        let spec = spec_yaml(
144            "id: t\n\
145             kind: file_max_size\n\
146             paths: \"**/*\"\n\
147             max_bytes: 100\n\
148             level: warning\n",
149        );
150        let rule = build(&spec).unwrap();
151        let idx = idx_with_size("a.bin", 100);
152        let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
153        assert!(v.is_empty(), "size == max should pass: {v:?}");
154    }
155}