friendly_errors/
header.rs1use crate::{ErrorKind, FriendlyError};
2use colored::*;
3
4const HEADER_LENGTH: usize = 80;
5
6fn get_label(kind: &ErrorKind) -> String {
7 match kind {
8 ErrorKind::Error => "Error".to_string(),
9 ErrorKind::Warning => "Warning".to_string(),
10 ErrorKind::Improvement => "Improvement".to_string(),
11 ErrorKind::CodeStyle => "Code style".to_string(),
12 }
13}
14
15fn colorize_label(string: String, kind: &ErrorKind) -> String {
16 match kind {
17 ErrorKind::Error => string.red().bold().to_string(),
18 ErrorKind::Warning => string.yellow().bold().to_string(),
19 ErrorKind::Improvement => string.cyan().bold().to_string(),
20 ErrorKind::CodeStyle => string.cyan().bold().to_string(),
21 }
22}
23
24impl FriendlyError {
25 fn append_label(&mut self) -> usize {
26 let mut output = String::new();
27 output.push_str("--- ");
28 output.push_str(&get_label(&self.data.kind));
29 if let Some(code) = &self.data.error_code {
30 output.push('(');
31 output.push_str(code);
32 output.push(')');
33 }
34 let length = output.len();
35 self.output
36 .push_str(&colorize_label(output, &self.data.kind));
37 length
38 }
39
40 fn append_title(&mut self) -> usize {
41 if let Some(title) = &self.data.title {
42 self.output.push_str(": ");
43 self.output.push_str(title);
44 return title.len() + 2;
45 }
46 0
47 }
48
49 pub fn print_header(&mut self) {
50 let mut header_length = HEADER_LENGTH;
51 header_length -= self.append_label();
52 header_length -= self.append_title();
53 self.output.push(' ');
54 header_length -= 1;
55 for _ in 0..header_length {
56 self.output.push('-');
57 }
58 }
59}
60
61#[cfg(test)]
62mod test {
63 use super::*;
64
65 #[test]
66 fn header_base_case() {
67 colored::control::set_override(false);
68 let mut error = FriendlyError::new();
69 error.print_header();
70 assert_eq!(
71 error.output,
72 "--- Error ----------------------------------------------------------------------"
73 );
74 }
75
76 #[test]
77 fn header_with_title() {
78 colored::control::set_override(false);
79 let mut error = FriendlyError::new().title("Error message");
80 error.print_header();
81 assert_eq!(
82 error.output,
83 "--- Error: Error message -------------------------------------------------------"
84 );
85 }
86
87 #[test]
88 fn header_with_code() {
89 colored::control::set_override(false);
90 let mut error = FriendlyError::new().error_code("E123");
91 error.print_header();
92 assert_eq!(
93 error.output,
94 "--- Error(E123) ----------------------------------------------------------------"
95 );
96 }
97
98 #[test]
99 fn header_with_title_and_code() {
100 colored::control::set_override(false);
101 let mut error = FriendlyError::new()
102 .title("Error message")
103 .error_code("E123");
104 error.print_header();
105 assert_eq!(
106 error.output,
107 "--- Error(E123): Error message -------------------------------------------------"
108 );
109 }
110}