solidhunter_lib/rules/best_practises/
max_line_length.rs1use crate::linter::SolidFile;
2use crate::rules::types::*;
3use crate::types::*;
4
5pub const RULE_ID: &str = "max-line-length";
7
8const DEFAULT_LENGTH: usize = 120;
10const DEFAULT_SEVERITY: Severity = Severity::ERROR;
11
12pub struct MaxLineLength {
13 max_len: usize,
14 data: RuleEntry,
15}
16
17impl MaxLineLength {
18 fn create_diag(&self, file: &SolidFile, line_idx: usize, line: &str) -> LintDiag {
19 LintDiag {
20 range: Range {
21 start: Position {
22 line: line_idx,
23 character: self.max_len,
24 },
25 end: Position {
26 line: line_idx,
27 character: line.len(),
28 },
29 },
30 id: RULE_ID.to_string(),
31 message: format!(
32 "Line length must be no more than {} but current length is {}",
33 self.max_len,
34 line.len()
35 ),
36 severity: self.data.severity,
37 code: None,
38 source: None,
39 uri: file.path.clone(),
40 }
41 }
42}
43
44impl RuleType for MaxLineLength {
45 fn diagnose(&self, file: &SolidFile, _files: &[SolidFile]) -> Vec<LintDiag> {
46 let mut res = Vec::new();
47 let mut line_idx = 1;
48
49 for line in file.content.lines() {
50 if line.len() > self.max_len {
51 res.push(self.create_diag(file, line_idx, line));
52 }
53 line_idx += 1;
54 }
55 res
56 }
57}
58
59impl MaxLineLength {
60 pub(crate) fn create(data: RuleEntry) -> Box<dyn RuleType> {
61 let mut max_line_length = DEFAULT_LENGTH;
62
63 if let Some(data) = &data.data {
64 let parsed: Result<usize, serde_json::Error> = serde_json::from_value(data.clone());
65 match parsed {
66 Ok(val) => max_line_length = val,
67 Err(_) => {
68 eprintln!("{} rule : bad config data", RULE_ID);
69 }
70 }
71 } else {
72 eprintln!("{} rule : bad config data", RULE_ID);
73 }
74 let rule = MaxLineLength {
75 max_len: max_line_length,
76 data,
77 };
78 Box::new(rule)
79 }
80
81 pub(crate) fn create_default() -> RuleEntry {
82 RuleEntry {
83 id: RULE_ID.to_string(),
84 severity: DEFAULT_SEVERITY,
85 data: Some(DEFAULT_LENGTH.into()),
86 }
87 }
88}