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