rumdl 0.1.51

A fast Markdown linter written in Rust (Ru(st) MarkDown Linter)
Documentation
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! Output formatting module for rumdl
//!
//! This module provides different output formats for linting results,
//! similar to how Ruff handles multiple output formats.

use crate::rule::LintWarning;
use std::io::{self, Write};
use std::str::FromStr;

pub mod formatters;

// Re-export formatters
pub use formatters::*;

/// Trait for output formatters
pub trait OutputFormatter {
    /// Format a collection of warnings for output
    fn format_warnings(&self, warnings: &[LintWarning], file_path: &str) -> String;

    /// Format warnings with file content for source line display.
    /// Formatters that show source context (e.g., Full) override this.
    /// Default delegates to `format_warnings`.
    fn format_warnings_with_content(&self, warnings: &[LintWarning], file_path: &str, _content: &str) -> String {
        self.format_warnings(warnings, file_path)
    }

    /// Format a summary of results across multiple files
    fn format_summary(&self, _files_processed: usize, _total_warnings: usize, _duration_ms: u64) -> Option<String> {
        // Default: no summary
        None
    }

    /// Whether this formatter should use colors
    fn use_colors(&self) -> bool {
        false
    }
}

/// Available output formats
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum OutputFormat {
    /// Default human-readable format with colors and context
    Text,
    /// Full format with source line display (ruff-style)
    Full,
    /// Concise format: `file:line:col: [RULE] message`
    Concise,
    /// Grouped format: violations grouped by file
    Grouped,
    /// JSON format (existing)
    Json,
    /// JSON Lines format (one JSON object per line)
    JsonLines,
    /// GitHub Actions annotation format
    GitHub,
    /// GitLab Code Quality format
    GitLab,
    /// Pylint-compatible format: file:line:column: CODE message
    Pylint,
    /// Azure Pipeline logging format
    Azure,
    /// SARIF 2.1.0 format
    Sarif,
    /// JUnit XML format
    Junit,
}

impl FromStr for OutputFormat {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "text" => Ok(OutputFormat::Text),
            "full" => Ok(OutputFormat::Full),
            "concise" => Ok(OutputFormat::Concise),
            "grouped" => Ok(OutputFormat::Grouped),
            "json" => Ok(OutputFormat::Json),
            "json-lines" | "jsonlines" => Ok(OutputFormat::JsonLines),
            "github" => Ok(OutputFormat::GitHub),
            "gitlab" => Ok(OutputFormat::GitLab),
            "pylint" => Ok(OutputFormat::Pylint),
            "azure" => Ok(OutputFormat::Azure),
            "sarif" => Ok(OutputFormat::Sarif),
            "junit" => Ok(OutputFormat::Junit),
            _ => Err(format!("Unknown output format: {s}")),
        }
    }
}

impl OutputFormat {
    /// Create a formatter instance for this format
    pub fn create_formatter(&self) -> Box<dyn OutputFormatter> {
        match self {
            OutputFormat::Text => Box::new(TextFormatter::new()),
            OutputFormat::Full => Box::new(FullFormatter::new()),
            OutputFormat::Concise => Box::new(ConciseFormatter::new()),
            OutputFormat::Grouped => Box::new(GroupedFormatter::new()),
            OutputFormat::Json => Box::new(JsonFormatter::new()),
            OutputFormat::JsonLines => Box::new(JsonLinesFormatter::new()),
            OutputFormat::GitHub => Box::new(GitHubFormatter::new()),
            OutputFormat::GitLab => Box::new(GitLabFormatter::new()),
            OutputFormat::Pylint => Box::new(PylintFormatter::new()),
            OutputFormat::Azure => Box::new(AzureFormatter::new()),
            OutputFormat::Sarif => Box::new(SarifFormatter::new()),
            OutputFormat::Junit => Box::new(JunitFormatter::new()),
        }
    }
}

/// Output writer that handles stdout/stderr routing
pub struct OutputWriter {
    use_stderr: bool,
    _quiet: bool,
    silent: bool,
}

impl OutputWriter {
    pub fn new(use_stderr: bool, quiet: bool, silent: bool) -> Self {
        Self {
            use_stderr,
            _quiet: quiet,
            silent,
        }
    }

    /// Write output to appropriate stream
    pub fn write(&self, content: &str) -> io::Result<()> {
        if self.silent {
            return Ok(());
        }

        if self.use_stderr {
            eprint!("{content}");
            io::stderr().flush()?;
        } else {
            print!("{content}");
            io::stdout().flush()?;
        }
        Ok(())
    }

    /// Write a line to appropriate stream
    pub fn writeln(&self, content: &str) -> io::Result<()> {
        if self.silent {
            return Ok(());
        }

        if self.use_stderr {
            eprintln!("{content}");
        } else {
            println!("{content}");
        }
        Ok(())
    }

    /// Write error/debug output (always to stderr unless silent)
    pub fn write_error(&self, content: &str) -> io::Result<()> {
        if self.silent {
            return Ok(());
        }

        eprintln!("{content}");
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rule::{Fix, Severity};

    fn create_test_warning(line: usize, message: &str) -> LintWarning {
        LintWarning {
            line,
            column: 5,
            end_line: line,
            end_column: 10,
            rule_name: Some("MD001".to_string()),
            message: message.to_string(),
            severity: Severity::Warning,
            fix: None,
        }
    }

    fn create_test_warning_with_fix(line: usize, message: &str, fix_text: &str) -> LintWarning {
        LintWarning {
            line,
            column: 5,
            end_line: line,
            end_column: 10,
            rule_name: Some("MD001".to_string()),
            message: message.to_string(),
            severity: Severity::Warning,
            fix: Some(Fix {
                range: 0..5,
                replacement: fix_text.to_string(),
            }),
        }
    }

    #[test]
    fn test_output_format_from_str() {
        // Valid formats
        assert_eq!(OutputFormat::from_str("text").unwrap(), OutputFormat::Text);
        assert_eq!(OutputFormat::from_str("full").unwrap(), OutputFormat::Full);
        assert_eq!(OutputFormat::from_str("concise").unwrap(), OutputFormat::Concise);
        assert_eq!(OutputFormat::from_str("grouped").unwrap(), OutputFormat::Grouped);
        assert_eq!(OutputFormat::from_str("json").unwrap(), OutputFormat::Json);
        assert_eq!(OutputFormat::from_str("json-lines").unwrap(), OutputFormat::JsonLines);
        assert_eq!(OutputFormat::from_str("jsonlines").unwrap(), OutputFormat::JsonLines);
        assert_eq!(OutputFormat::from_str("github").unwrap(), OutputFormat::GitHub);
        assert_eq!(OutputFormat::from_str("gitlab").unwrap(), OutputFormat::GitLab);
        assert_eq!(OutputFormat::from_str("pylint").unwrap(), OutputFormat::Pylint);
        assert_eq!(OutputFormat::from_str("azure").unwrap(), OutputFormat::Azure);
        assert_eq!(OutputFormat::from_str("sarif").unwrap(), OutputFormat::Sarif);
        assert_eq!(OutputFormat::from_str("junit").unwrap(), OutputFormat::Junit);

        // Case insensitive
        assert_eq!(OutputFormat::from_str("TEXT").unwrap(), OutputFormat::Text);
        assert_eq!(OutputFormat::from_str("GitHub").unwrap(), OutputFormat::GitHub);
        assert_eq!(OutputFormat::from_str("JSON-LINES").unwrap(), OutputFormat::JsonLines);

        // Invalid format
        assert!(OutputFormat::from_str("invalid").is_err());
        assert!(OutputFormat::from_str("").is_err());
        assert!(OutputFormat::from_str("xml").is_err());
    }

    #[test]
    fn test_output_format_create_formatter() {
        // Test that each format creates the correct formatter
        let formats = [
            OutputFormat::Text,
            OutputFormat::Full,
            OutputFormat::Concise,
            OutputFormat::Grouped,
            OutputFormat::Json,
            OutputFormat::JsonLines,
            OutputFormat::GitHub,
            OutputFormat::GitLab,
            OutputFormat::Pylint,
            OutputFormat::Azure,
            OutputFormat::Sarif,
            OutputFormat::Junit,
        ];

        for format in &formats {
            let formatter = format.create_formatter();
            // Test that formatter can format warnings
            let warnings = vec![create_test_warning(1, "Test warning")];
            let output = formatter.format_warnings(&warnings, "test.md");
            assert!(!output.is_empty(), "Formatter {format:?} should produce output");
        }
    }

    #[test]
    fn test_output_writer_new() {
        let writer1 = OutputWriter::new(false, false, false);
        assert!(!writer1.use_stderr);
        assert!(!writer1._quiet);
        assert!(!writer1.silent);

        let writer2 = OutputWriter::new(true, true, false);
        assert!(writer2.use_stderr);
        assert!(writer2._quiet);
        assert!(!writer2.silent);

        let writer3 = OutputWriter::new(false, false, true);
        assert!(!writer3.use_stderr);
        assert!(!writer3._quiet);
        assert!(writer3.silent);
    }

    #[test]
    fn test_output_writer_silent_mode() {
        let writer = OutputWriter::new(false, false, true);

        // All write methods should succeed but not produce output when silent
        assert!(writer.write("test").is_ok());
        assert!(writer.writeln("test").is_ok());
        assert!(writer.write_error("test").is_ok());
    }

    #[test]
    fn test_output_writer_write_methods() {
        // Test non-silent mode
        let writer = OutputWriter::new(false, false, false);

        // These should succeed (we can't easily test the actual output)
        assert!(writer.write("test").is_ok());
        assert!(writer.writeln("test line").is_ok());
        assert!(writer.write_error("error message").is_ok());
    }

    #[test]
    fn test_output_writer_stderr_mode() {
        let writer = OutputWriter::new(true, false, false);

        // Should write to stderr instead of stdout
        assert!(writer.write("stderr test").is_ok());
        assert!(writer.writeln("stderr line").is_ok());

        // write_error always goes to stderr
        assert!(writer.write_error("error").is_ok());
    }

    #[test]
    fn test_formatter_trait_default_summary() {
        // Create a simple test formatter
        struct TestFormatter;
        impl OutputFormatter for TestFormatter {
            fn format_warnings(&self, _warnings: &[LintWarning], _file_path: &str) -> String {
                "test".to_string()
            }
        }

        let formatter = TestFormatter;
        assert_eq!(formatter.format_summary(10, 5, 1000), None);
        assert!(!formatter.use_colors());
    }

    #[test]
    fn test_formatter_with_multiple_warnings() {
        let warnings = vec![
            create_test_warning(1, "First warning"),
            create_test_warning(5, "Second warning"),
            create_test_warning_with_fix(10, "Third warning with fix", "fixed content"),
        ];

        // Test with different formatters
        let text_formatter = TextFormatter::new();
        let output = text_formatter.format_warnings(&warnings, "test.md");
        assert!(output.contains("First warning"));
        assert!(output.contains("Second warning"));
        assert!(output.contains("Third warning with fix"));
    }

    #[test]
    fn test_edge_cases() {
        // Empty warnings
        let empty_warnings: Vec<LintWarning> = vec![];
        let formatter = TextFormatter::new();
        let output = formatter.format_warnings(&empty_warnings, "test.md");
        // Most formatters should handle empty warnings gracefully
        assert!(output.is_empty() || output.trim().is_empty());

        // Very long file path
        let long_path = "a/".repeat(100) + "file.md";
        let warnings = vec![create_test_warning(1, "Test")];
        let output = formatter.format_warnings(&warnings, &long_path);
        assert!(!output.is_empty());

        // Unicode in messages
        let unicode_warning = LintWarning {
            line: 1,
            column: 1,
            end_line: 1,
            end_column: 10,
            rule_name: Some("MD001".to_string()),
            message: "Unicode test: 你好 🌟 émphasis".to_string(),
            severity: Severity::Warning,
            fix: None,
        };
        let output = formatter.format_warnings(&[unicode_warning], "test.md");
        assert!(output.contains("Unicode test"));
    }

    #[test]
    fn test_severity_variations() {
        let severities = [Severity::Error, Severity::Warning, Severity::Info];

        for severity in &severities {
            let warning = LintWarning {
                line: 1,
                column: 1,
                end_line: 1,
                end_column: 5,
                rule_name: Some("MD001".to_string()),
                message: format!(
                    "Test {} message",
                    match severity {
                        Severity::Error => "error",
                        Severity::Warning => "warning",
                        Severity::Info => "info",
                    }
                ),
                severity: *severity,
                fix: None,
            };

            let formatter = TextFormatter::new();
            let output = formatter.format_warnings(&[warning], "test.md");
            assert!(!output.is_empty());
        }
    }

    #[test]
    fn test_output_format_equality() {
        assert_eq!(OutputFormat::Text, OutputFormat::Text);
        assert_ne!(OutputFormat::Text, OutputFormat::Json);
        assert_ne!(OutputFormat::Concise, OutputFormat::Grouped);
    }

    #[test]
    fn test_all_formats_handle_no_rule_name() {
        let warning = LintWarning {
            line: 1,
            column: 1,
            end_line: 1,
            end_column: 5,
            rule_name: None, // No rule name
            message: "Generic warning".to_string(),
            severity: Severity::Warning,
            fix: None,
        };

        let formats = [
            OutputFormat::Text,
            OutputFormat::Full,
            OutputFormat::Concise,
            OutputFormat::Grouped,
            OutputFormat::Json,
            OutputFormat::JsonLines,
            OutputFormat::GitHub,
            OutputFormat::GitLab,
            OutputFormat::Pylint,
            OutputFormat::Azure,
            OutputFormat::Sarif,
            OutputFormat::Junit,
        ];

        for format in &formats {
            let formatter = format.create_formatter();
            let output = formatter.format_warnings(std::slice::from_ref(&warning), "test.md");
            assert!(
                !output.is_empty(),
                "Format {format:?} should handle warnings without rule names"
            );
        }
    }
}