alint_rules/
file_max_lines.rs1use 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 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
106fn 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 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}