alint_rules/
file_max_lines.rs1use 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) {
48 continue;
49 }
50 let full = ctx.root.join(&entry.path);
51 let Ok(bytes) = std::fs::read(&full) else {
52 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
94fn 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_paths_spec(paths)?,
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 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}