Skip to main content

alint_rules/
line_max_width.rs

1//! `line_max_width` — cap on characters per line.
2//!
3//! Counts Unicode scalar values (chars) per line, not bytes or
4//! display cells. CJK, combining marks, and emoji that occupy
5//! two terminal columns count as one char — if you want real
6//! display-width accounting, use a formatter (Biome, prettier);
7//! that's out of alint's byte/structure scope.
8//!
9//! Check-only: truncation isn't a safe auto-fix. Users either
10//! refactor the line or widen the limit.
11
12use alint_core::{Context, Error, Level, Result, Rule, RuleSpec, Scope, Violation};
13use serde::Deserialize;
14
15#[derive(Debug, Deserialize)]
16#[serde(deny_unknown_fields)]
17struct Options {
18    max_width: usize,
19}
20
21#[derive(Debug)]
22pub struct LineMaxWidthRule {
23    id: String,
24    level: Level,
25    policy_url: Option<String>,
26    message: Option<String>,
27    scope: Scope,
28    max_width: usize,
29}
30
31impl Rule for LineMaxWidthRule {
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                continue;
51            };
52            let Ok(text) = std::str::from_utf8(&bytes) else {
53                continue;
54            };
55            if let Some((line_no, width)) = first_overlong_line(text, self.max_width) {
56                let msg = self.message.clone().unwrap_or_else(|| {
57                    format!(
58                        "line {line_no} is {width} chars wide; max is {}",
59                        self.max_width
60                    )
61                });
62                violations.push(
63                    Violation::new(msg)
64                        .with_path(&entry.path)
65                        .with_location(line_no, self.max_width + 1),
66                );
67            }
68        }
69        Ok(violations)
70    }
71}
72
73fn first_overlong_line(text: &str, max_width: usize) -> Option<(usize, usize)> {
74    for (idx, line) in text.split('\n').enumerate() {
75        let trimmed = line.strip_suffix('\r').unwrap_or(line);
76        let width = trimmed.chars().count();
77        if width > max_width {
78            return Some((idx + 1, width));
79        }
80    }
81    None
82}
83
84pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
85    let paths = spec
86        .paths
87        .as_ref()
88        .ok_or_else(|| Error::rule_config(&spec.id, "line_max_width requires a `paths` field"))?;
89    let opts: Options = spec
90        .deserialize_options()
91        .map_err(|e| Error::rule_config(&spec.id, format!("invalid options: {e}")))?;
92    if opts.max_width == 0 {
93        return Err(Error::rule_config(
94            &spec.id,
95            "line_max_width `max_width` must be > 0",
96        ));
97    }
98    if spec.fix.is_some() {
99        return Err(Error::rule_config(
100            &spec.id,
101            "line_max_width has no fix op — truncation is unsafe",
102        ));
103    }
104    Ok(Box::new(LineMaxWidthRule {
105        id: spec.id.clone(),
106        level: spec.level,
107        policy_url: spec.policy_url.clone(),
108        message: spec.message.clone(),
109        scope: Scope::from_paths_spec(paths)?,
110        max_width: opts.max_width,
111    }))
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117
118    #[test]
119    fn short_file_is_ok() {
120        assert_eq!(first_overlong_line("hi\nthere\n", 10), None);
121    }
122
123    #[test]
124    fn flags_first_overlong_line() {
125        let txt = "short\nway too looooong for ten\nok\n";
126        // "way too looooong for ten" is 24 chars.
127        assert_eq!(first_overlong_line(txt, 10), Some((2, 24)));
128    }
129
130    #[test]
131    fn width_exactly_at_limit_is_ok() {
132        assert_eq!(first_overlong_line("0123456789\n", 10), None);
133    }
134
135    #[test]
136    fn crlf_is_stripped_before_counting() {
137        // "hi\r\n" should count as 2 chars ("hi"), not 3.
138        assert_eq!(first_overlong_line("hi\r\n", 2), None);
139    }
140
141    #[test]
142    fn counts_unicode_scalar_values_not_bytes() {
143        // "☃☃☃" is 3 scalars / 9 bytes. Under `max_width: 3` it's fine.
144        assert_eq!(first_overlong_line("☃☃☃\n", 3), None);
145        // Under max_width: 2 it's flagged.
146        assert_eq!(first_overlong_line("☃☃☃\n", 2), Some((1, 3)));
147    }
148}