Skip to main content

alint_rules/
file_max_lines.rs

1//! `file_max_lines` — files in scope must have AT MOST
2//! `max_lines` lines. Mirror of [`crate::file_min_lines`];
3//! shares the line-counting semantics so the two compose
4//! cleanly when both are applied to the same file.
5//!
6//! Catches the "everything-module" anti-pattern — a single
7//! `lib.rs` / `index.ts` / `helpers.py` that grew until it
8//! does the work of a half-dozen smaller files. The threshold
9//! is intentionally a soft signal rather than a hard limit;
10//! we ship it at `level: warning` in tutorials and rulesets,
11//! and leave the cap value to the team.
12
13use std::path::Path;
14
15use alint_core::{Context, Error, Level, PerFileRule, Result, Rule, RuleSpec, Scope, Violation};
16use serde::Deserialize;
17
18#[derive(Debug, Deserialize)]
19#[serde(deny_unknown_fields)]
20struct Options {
21    max_lines: u64,
22}
23
24#[derive(Debug)]
25pub struct FileMaxLinesRule {
26    id: String,
27    level: Level,
28    policy_url: Option<String>,
29    message: Option<String>,
30    scope: Scope,
31    max_lines: u64,
32}
33
34impl Rule for FileMaxLinesRule {
35    fn id(&self) -> &str {
36        &self.id
37    }
38    fn level(&self) -> Level {
39        self.level
40    }
41    fn policy_url(&self) -> Option<&str> {
42        self.policy_url.as_deref()
43    }
44
45    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
46        let mut violations = Vec::new();
47        for entry in ctx.index.files() {
48            if !self.scope.matches(&entry.path, ctx.index) {
49                continue;
50            }
51            let full = ctx.root.join(&entry.path);
52            let Ok(bytes) = std::fs::read(&full) else {
53                // Same silent-skip policy as the rest of the
54                // content family — a permission flake or race
55                // shouldn't blow up the whole check run.
56                continue;
57            };
58            violations.extend(self.evaluate_file(ctx, &entry.path, &bytes)?);
59        }
60        Ok(violations)
61    }
62
63    fn as_per_file(&self) -> Option<&dyn PerFileRule> {
64        Some(self)
65    }
66}
67
68impl PerFileRule for FileMaxLinesRule {
69    fn path_scope(&self) -> &Scope {
70        &self.scope
71    }
72
73    fn evaluate_file(
74        &self,
75        _ctx: &Context<'_>,
76        path: &Path,
77        bytes: &[u8],
78    ) -> Result<Vec<Violation>> {
79        let lines = count_lines(bytes);
80        if lines <= self.max_lines {
81            return Ok(Vec::new());
82        }
83        let msg = self.message.clone().unwrap_or_else(|| {
84            format!(
85                "file has {} line(s); at most {} allowed",
86                lines, self.max_lines,
87            )
88        });
89        Ok(vec![
90            Violation::new(msg).with_path(std::sync::Arc::<Path>::from(path)),
91        ])
92    }
93}
94
95/// Count lines with the same `wc -l`-style semantics as
96/// `file_min_lines::count_lines`. Kept as a private function
97/// here (rather than reused from `file_min_lines`) because
98/// inlining it makes the unit tests explicit about what this
99/// rule's threshold is being compared against — and the
100/// implementation is one line, not worth a cross-module dep.
101fn count_lines(bytes: &[u8]) -> u64 {
102    if bytes.is_empty() {
103        return 0;
104    }
105    #[allow(clippy::naive_bytecount)]
106    let newlines = bytes.iter().filter(|&&b| b == b'\n').count() as u64;
107    let trailing_unterminated = u64::from(!bytes.ends_with(b"\n"));
108    newlines + trailing_unterminated
109}
110
111pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
112    let Some(_paths) = &spec.paths else {
113        return Err(Error::rule_config(
114            &spec.id,
115            "file_max_lines requires a `paths` field",
116        ));
117    };
118    let opts: Options = spec
119        .deserialize_options()
120        .map_err(|e| Error::rule_config(&spec.id, format!("invalid options: {e}")))?;
121    Ok(Box::new(FileMaxLinesRule {
122        id: spec.id.clone(),
123        level: spec.level,
124        policy_url: spec.policy_url.clone(),
125        message: spec.message.clone(),
126        scope: Scope::from_spec(spec)?,
127        max_lines: opts.max_lines,
128    }))
129}
130
131#[cfg(test)]
132mod tests {
133    use super::count_lines;
134
135    #[test]
136    fn empty_file_is_zero_lines() {
137        assert_eq!(count_lines(b""), 0);
138    }
139
140    #[test]
141    fn matches_min_lines_semantics() {
142        // Identical accounting to file_min_lines so the two
143        // rules agree on what "this file has N lines" means.
144        assert_eq!(count_lines(b"a\n"), 1);
145        assert_eq!(count_lines(b"a\nb\n"), 2);
146        assert_eq!(count_lines(b"a\nb"), 2);
147        assert_eq!(count_lines(b"\n\n"), 2);
148        assert_eq!(count_lines(b"a\n\nb\n"), 3);
149    }
150}