alint_rules/
file_max_lines.rs1use 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 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));
64 }
65 }
66 Ok(violations)
67 }
68}
69
70fn 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 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}