rigsql_rules/layout/
lt12.rs1use crate::rule::{CrawlType, Rule, RuleContext, RuleGroup};
2use crate::violation::{LintViolation, SourceEdit};
3
4#[derive(Debug, Default)]
6pub struct RuleLT12;
7
8impl Rule for RuleLT12 {
9 fn code(&self) -> &'static str {
10 "LT12"
11 }
12 fn name(&self) -> &'static str {
13 "layout.end_of_file"
14 }
15 fn description(&self) -> &'static str {
16 "Files must end with a single trailing newline."
17 }
18 fn explanation(&self) -> &'static str {
19 "Files should end with exactly one newline character. Missing trailing newlines \
20 can cause issues with some tools, and multiple trailing newlines are untidy."
21 }
22 fn groups(&self) -> &[RuleGroup] {
23 &[RuleGroup::Layout]
24 }
25 fn is_fixable(&self) -> bool {
26 true
27 }
28
29 fn crawl_type(&self) -> CrawlType {
30 CrawlType::RootOnly
31 }
32
33 fn eval(&self, ctx: &RuleContext) -> Vec<LintViolation> {
34 let source = ctx.source;
35 if source.is_empty() {
36 return vec![];
37 }
38
39 let end = source.len() as u32;
40
41 if !source.ends_with('\n') {
42 return vec![LintViolation::with_fix(
43 self.code(),
44 "File does not end with a trailing newline.",
45 rigsql_core::Span::new(end, end),
46 vec![SourceEdit::insert(end, "\n")],
47 )];
48 }
49
50 let trimmed = source.trim_end_matches(&['\n', '\r'][..]);
52 let trailing_newlines = source[trimmed.len()..]
53 .bytes()
54 .filter(|&b| b == b'\n')
55 .count();
56 if trailing_newlines > 1 {
57 let span_start = trimmed.len() as u32;
58 return vec![LintViolation::with_fix(
59 self.code(),
60 format!(
61 "File ends with {} trailing newlines instead of 1.",
62 trailing_newlines
63 ),
64 rigsql_core::Span::new(span_start, end),
65 vec![SourceEdit::replace(
66 rigsql_core::Span::new(span_start, end),
67 "\n",
68 )],
69 )];
70 }
71
72 vec![]
73 }
74}