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