supa_mdx_lint/output/
simple.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
use std::{collections::HashSet, io::Write};

use anyhow::Result;
use log::warn;

use crate::errors::LintLevel;

use super::LintOutput;

/// Outputs linter diagnostics in the simple format, for CLI display, which has
/// the structure:
///
/// ```text
/// <file path>:<line>:<column>: [<severity>] <msg>
/// ```
///
/// The diagnostics are followed by a summary of the number of linted files,
/// total errors, and total warnings.
#[derive(Debug, Clone)]
pub struct SimpleFormatter;

impl SimpleFormatter {
    pub(super) fn format<Writer: Write>(
        &self,
        output: &[LintOutput],
        io: &mut Writer,
    ) -> Result<()> {
        // Whether anything has been written to the output, used to determine
        // whether to write a newline before the summary.
        let mut written = false;

        for output in output.iter() {
            for error in output.errors.iter() {
                written |= true;

                match writeln!(
                    io,
                    "{}:{}:{}: [{}] {}",
                    output.file_path,
                    error.location.start.row + 1,
                    error.location.start.column + 1,
                    error.level,
                    error.message,
                ) {
                    Ok(_) => {}
                    Err(err) => {
                        warn!("Failed to write to output: {}", err);
                        return Err(err.into());
                    }
                }
            }
        }

        if written {
            writeln!(io)?;
        }
        SimpleFormatter::write_summary(output, io)?;

        Ok(())
    }

    pub(super) fn should_log_metadata(&self) -> bool {
        true
    }
}

impl SimpleFormatter {
    fn write_summary(output: &[LintOutput], io: &mut impl Write) -> Result<()> {
        let mut seen_files = HashSet::<&str>::new();
        let mut num_errors = 0;
        let mut num_warnings = 0;

        for o in output {
            seen_files.insert(&o.file_path);
            for error in &o.errors {
                match error.level {
                    LintLevel::Error => num_errors += 1,
                    LintLevel::Warning => num_warnings += 1,
                }
            }
        }

        let diagnostic_message = match (num_errors, num_warnings) {
            (0, 0) => "🟢 No errors or warnings found",
            (0, num_warnings) => &format!(
                "🟡 Found {} warning{}",
                num_warnings,
                if num_warnings != 1 { "s" } else { "" }
            ),
            (num_errors, 0) => &format!(
                "🔴 Found {} error{}",
                num_errors,
                if num_errors != 1 { "s" } else { "" }
            ),
            (num_errors, num_warnings) => &format!(
                "🔴 Found {} error{} and {} warning{}",
                num_errors,
                if num_errors != 1 { "s" } else { "" },
                num_warnings,
                if num_warnings != 1 { "s" } else { "" }
            ),
        };

        writeln!(
            io,
            "🔍 {} source{} linted",
            seen_files.len(),
            if seen_files.len() != 1 { "s" } else { "" }
        )?;
        writeln!(io, "{}", diagnostic_message)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        errors::{LintError, LintLevel},
        geometry::DenormalizedLocation,
    };

    #[test]
    fn test_simple_formatter() {
        let file_path = "test.md".to_string();
        let error = LintError::from_raw_location()
            .rule("MockRule")
            .level(LintLevel::Error)
            .message("This is an error")
            .location(DenormalizedLocation::dummy(0, 7, 0, 0, 1, 0))
            .call();

        let output = LintOutput {
            file_path,
            errors: vec![error],
        };
        let output = vec![output];

        let formatter = SimpleFormatter;
        let mut result = Vec::new();
        formatter.format(&output, &mut result).unwrap();
        assert_eq!(
            String::from_utf8(result).unwrap(),
            "test.md:1:1: [ERROR] This is an error\n\n🔍 1 source linted\n🔴 Found 1 error\n"
        );
    }

    #[test]
    fn test_simple_formatter_warning() {
        let file_path = "test.md".to_string();
        let error = LintError::from_raw_location()
            .rule("MockRule")
            .level(LintLevel::Warning)
            .message("This is a warning")
            .location(DenormalizedLocation::dummy(0, 7, 0, 0, 1, 0))
            .call();
        let output = LintOutput {
            file_path,
            errors: vec![error],
        };
        let output = vec![output];

        let formatter = SimpleFormatter;
        let mut result = Vec::new();
        formatter.format(&output, &mut result).unwrap();
        assert_eq!(
            String::from_utf8(result).unwrap(),
            "test.md:1:1: [WARN] This is a warning\n\n🔍 1 source linted\n🟡 Found 1 warning\n"
        );
    }

    #[test]
    fn test_simple_formatter_warning_and_error() {
        let file_path = "test.md".to_string();
        let error1 = LintError::from_raw_location()
            .rule("MockRule")
            .level(LintLevel::Error)
            .message("This is an error")
            .location(DenormalizedLocation::dummy(0, 7, 0, 0, 1, 0))
            .call();
        let error2 = LintError::from_raw_location()
            .rule("MockRule")
            .level(LintLevel::Warning)
            .message("This is a warning")
            .location(DenormalizedLocation::dummy(14, 46, 3, 0, 4, 2))
            .call();
        let output = LintOutput {
            file_path,
            errors: vec![error1, error2],
        };
        let output = vec![output];

        let formatter = SimpleFormatter;
        let mut result = Vec::new();
        formatter.format(&output, &mut result).unwrap();
        assert_eq!(
            String::from_utf8(result).unwrap(),
            "test.md:1:1: [ERROR] This is an error\ntest.md:4:1: [WARN] This is a warning\n\n🔍 1 source linted\n🔴 Found 1 error and 1 warning\n"
        );
    }

    #[test]
    fn test_simple_formatter_no_errors() {
        let file_path = "test.md".to_string();
        let output = LintOutput {
            file_path,
            errors: vec![],
        };
        let output = vec![output];

        let formatter = SimpleFormatter;
        let mut result = Vec::new();
        formatter.format(&output, &mut result).unwrap();
        assert_eq!(
            String::from_utf8(result).unwrap(),
            "🔍 1 source linted\n🟢 No errors or warnings found\n"
        );
    }

    #[test]
    fn test_simple_formatter_multiple_errors() {
        let file_path = "test.md".to_string();
        let error_1 = LintError::from_raw_location()
            .rule("MockRule")
            .level(LintLevel::Error)
            .message("This is an error")
            .location(DenormalizedLocation::dummy(0, 7, 0, 0, 1, 0))
            .call();
        let error_2 = LintError::from_raw_location()
            .rule("MockRule")
            .level(LintLevel::Error)
            .message("This is another error")
            .location(DenormalizedLocation::dummy(14, 46, 3, 0, 4, 2))
            .call();

        let output = LintOutput {
            file_path,
            errors: vec![error_1, error_2],
        };
        let output = vec![output];

        let formatter = SimpleFormatter;
        let mut result = Vec::new();
        formatter.format(&output, &mut result).unwrap();
        assert_eq!(
            String::from_utf8(result).unwrap(),
            "test.md:1:1: [ERROR] This is an error\ntest.md:4:1: [ERROR] This is another error\n\n🔍 1 source linted\n🔴 Found 2 errors\n"
        );
    }

    #[test]
    fn test_simple_formatter_multiple_files() {
        let file_path_1 = "test.md".to_string();
        let error_1 = LintError::from_raw_location()
            .rule("MockRule")
            .level(LintLevel::Error)
            .message("This is an error")
            .location(DenormalizedLocation::dummy(0, 7, 0, 0, 1, 0))
            .call();
        let error_2 = LintError::from_raw_location()
            .rule("MockRule")
            .level(LintLevel::Error)
            .message("This is another error")
            .location(DenormalizedLocation::dummy(14, 46, 3, 0, 4, 2))
            .call();

        let output_1 = LintOutput {
            file_path: file_path_1,
            errors: vec![error_1, error_2],
        };

        let file_path_2 = "test2.md".to_string();
        let error_3 = LintError::from_raw_location()
            .rule("MockRule")
            .level(LintLevel::Error)
            .message("This is an error")
            .location(DenormalizedLocation::dummy(0, 7, 0, 0, 1, 0))
            .call();
        let error_4 = LintError::from_raw_location()
            .rule("MockRule")
            .level(LintLevel::Error)
            .message("This is another error")
            .location(DenormalizedLocation::dummy(14, 46, 3, 0, 4, 2))
            .call();

        let output_2 = LintOutput {
            file_path: file_path_2,
            errors: vec![error_3, error_4],
        };

        let output = vec![output_1, output_2];

        let formatter = SimpleFormatter;
        let mut result = Vec::new();
        formatter.format(&output, &mut result).unwrap();
        assert_eq!(
            String::from_utf8(result).unwrap(),
            "test.md:1:1: [ERROR] This is an error\ntest.md:4:1: [ERROR] This is another error\ntest2.md:1:1: [ERROR] This is an error\ntest2.md:4:1: [ERROR] This is another error\n\n🔍 2 sources linted\n🔴 Found 4 errors\n"
        );
    }
}