alint_rules/
file_max_size.rs1use 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));
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}