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