Skip to main content

rumdl_lib/output/
mod.rs

1//! Output formatting module for rumdl
2//!
3//! This module provides different output formats for linting results,
4//! similar to how Ruff handles multiple output formats.
5
6use crate::rule::LintWarning;
7use std::io::{self, Write};
8use std::str::FromStr;
9
10pub mod formatters;
11
12// Re-export formatters
13pub use formatters::*;
14
15/// Trait for output formatters
16pub trait OutputFormatter {
17    /// Format a collection of warnings for output
18    fn format_warnings(&self, warnings: &[LintWarning], file_path: &str) -> String;
19
20    /// Format warnings with file content for source line display.
21    /// Formatters that show source context (e.g., Full) override this.
22    /// Default delegates to `format_warnings`.
23    fn format_warnings_with_content(&self, warnings: &[LintWarning], file_path: &str, _content: &str) -> String {
24        self.format_warnings(warnings, file_path)
25    }
26
27    /// Format a summary of results across multiple files
28    fn format_summary(&self, _files_processed: usize, _total_warnings: usize, _duration_ms: u64) -> Option<String> {
29        // Default: no summary
30        None
31    }
32
33    /// Whether this formatter should use colors
34    fn use_colors(&self) -> bool {
35        false
36    }
37}
38
39/// Available output formats
40#[derive(Debug, Clone, Copy, PartialEq)]
41pub enum OutputFormat {
42    /// Default human-readable format with colors and context
43    Text,
44    /// Full format with source line display (ruff-style)
45    Full,
46    /// Concise format: `file:line:col: [RULE] message`
47    Concise,
48    /// Grouped format: violations grouped by file
49    Grouped,
50    /// JSON format (existing)
51    Json,
52    /// JSON Lines format (one JSON object per line)
53    JsonLines,
54    /// GitHub Actions annotation format
55    GitHub,
56    /// GitLab Code Quality format
57    GitLab,
58    /// Pylint-compatible format: file:line:column: CODE message
59    Pylint,
60    /// Azure Pipeline logging format
61    Azure,
62    /// SARIF 2.1.0 format
63    Sarif,
64    /// JUnit XML format
65    Junit,
66}
67
68impl FromStr for OutputFormat {
69    type Err = String;
70
71    fn from_str(s: &str) -> Result<Self, Self::Err> {
72        match s.to_lowercase().as_str() {
73            "text" => Ok(OutputFormat::Text),
74            "full" => Ok(OutputFormat::Full),
75            "concise" => Ok(OutputFormat::Concise),
76            "grouped" => Ok(OutputFormat::Grouped),
77            "json" => Ok(OutputFormat::Json),
78            "json-lines" | "jsonlines" => Ok(OutputFormat::JsonLines),
79            "github" => Ok(OutputFormat::GitHub),
80            "gitlab" => Ok(OutputFormat::GitLab),
81            "pylint" => Ok(OutputFormat::Pylint),
82            "azure" => Ok(OutputFormat::Azure),
83            "sarif" => Ok(OutputFormat::Sarif),
84            "junit" => Ok(OutputFormat::Junit),
85            _ => Err(format!("Unknown output format: {s}")),
86        }
87    }
88}
89
90impl OutputFormat {
91    /// Whether this format produces machine-readable output that should not
92    /// be mixed with human-readable summary lines.
93    pub fn is_machine_readable(&self) -> bool {
94        !matches!(
95            self,
96            OutputFormat::Text | OutputFormat::Full | OutputFormat::Concise | OutputFormat::Grouped
97        )
98    }
99
100    /// Create a formatter instance for this format
101    pub fn create_formatter(&self) -> Box<dyn OutputFormatter> {
102        match self {
103            OutputFormat::Text => Box::new(TextFormatter::new()),
104            OutputFormat::Full => Box::new(FullFormatter::new()),
105            OutputFormat::Concise => Box::new(ConciseFormatter::new()),
106            OutputFormat::Grouped => Box::new(GroupedFormatter::new()),
107            OutputFormat::Json => Box::new(JsonFormatter::new()),
108            OutputFormat::JsonLines => Box::new(JsonLinesFormatter::new()),
109            OutputFormat::GitHub => Box::new(GitHubFormatter::new()),
110            OutputFormat::GitLab => Box::new(GitLabFormatter::new()),
111            OutputFormat::Pylint => Box::new(PylintFormatter::new()),
112            OutputFormat::Azure => Box::new(AzureFormatter::new()),
113            OutputFormat::Sarif => Box::new(SarifFormatter::new()),
114            OutputFormat::Junit => Box::new(JunitFormatter::new()),
115        }
116    }
117}
118
119/// Output writer that handles stdout/stderr routing
120pub struct OutputWriter {
121    use_stderr: bool,
122    silent: bool,
123}
124
125impl OutputWriter {
126    pub fn new(use_stderr: bool, silent: bool) -> Self {
127        Self { use_stderr, silent }
128    }
129
130    /// Write output to appropriate stream
131    pub fn write(&self, content: &str) -> io::Result<()> {
132        if self.silent {
133            return Ok(());
134        }
135
136        if self.use_stderr {
137            eprint!("{content}");
138            io::stderr().flush()?;
139        } else {
140            print!("{content}");
141            io::stdout().flush()?;
142        }
143        Ok(())
144    }
145
146    /// Write a line to appropriate stream
147    pub fn writeln(&self, content: &str) -> io::Result<()> {
148        if self.silent {
149            return Ok(());
150        }
151
152        if self.use_stderr {
153            eprintln!("{content}");
154        } else {
155            println!("{content}");
156        }
157        Ok(())
158    }
159
160    /// Write error/debug output (always to stderr unless silent)
161    pub fn write_error(&self, content: &str) -> io::Result<()> {
162        if self.silent {
163            return Ok(());
164        }
165
166        eprintln!("{content}");
167        Ok(())
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use crate::rule::{Fix, Severity};
175
176    fn create_test_warning(line: usize, message: &str) -> LintWarning {
177        LintWarning {
178            line,
179            column: 5,
180            end_line: line,
181            end_column: 10,
182            rule_name: Some("MD001".to_string()),
183            message: message.to_string(),
184            severity: Severity::Warning,
185            fix: None,
186        }
187    }
188
189    fn create_test_warning_with_fix(line: usize, message: &str, fix_text: &str) -> LintWarning {
190        LintWarning {
191            line,
192            column: 5,
193            end_line: line,
194            end_column: 10,
195            rule_name: Some("MD001".to_string()),
196            message: message.to_string(),
197            severity: Severity::Warning,
198            fix: Some(Fix::new(0..5, fix_text.to_string())),
199        }
200    }
201
202    #[test]
203    fn test_output_format_from_str() {
204        // Valid formats
205        assert_eq!(OutputFormat::from_str("text").unwrap(), OutputFormat::Text);
206        assert_eq!(OutputFormat::from_str("full").unwrap(), OutputFormat::Full);
207        assert_eq!(OutputFormat::from_str("concise").unwrap(), OutputFormat::Concise);
208        assert_eq!(OutputFormat::from_str("grouped").unwrap(), OutputFormat::Grouped);
209        assert_eq!(OutputFormat::from_str("json").unwrap(), OutputFormat::Json);
210        assert_eq!(OutputFormat::from_str("json-lines").unwrap(), OutputFormat::JsonLines);
211        assert_eq!(OutputFormat::from_str("jsonlines").unwrap(), OutputFormat::JsonLines);
212        assert_eq!(OutputFormat::from_str("github").unwrap(), OutputFormat::GitHub);
213        assert_eq!(OutputFormat::from_str("gitlab").unwrap(), OutputFormat::GitLab);
214        assert_eq!(OutputFormat::from_str("pylint").unwrap(), OutputFormat::Pylint);
215        assert_eq!(OutputFormat::from_str("azure").unwrap(), OutputFormat::Azure);
216        assert_eq!(OutputFormat::from_str("sarif").unwrap(), OutputFormat::Sarif);
217        assert_eq!(OutputFormat::from_str("junit").unwrap(), OutputFormat::Junit);
218
219        // Case insensitive
220        assert_eq!(OutputFormat::from_str("TEXT").unwrap(), OutputFormat::Text);
221        assert_eq!(OutputFormat::from_str("GitHub").unwrap(), OutputFormat::GitHub);
222        assert_eq!(OutputFormat::from_str("JSON-LINES").unwrap(), OutputFormat::JsonLines);
223
224        // Invalid format
225        assert!(OutputFormat::from_str("invalid").is_err());
226        assert!(OutputFormat::from_str("").is_err());
227        assert!(OutputFormat::from_str("xml").is_err());
228    }
229
230    #[test]
231    fn test_output_format_create_formatter() {
232        // Test that each format creates the correct formatter
233        let formats = [
234            OutputFormat::Text,
235            OutputFormat::Full,
236            OutputFormat::Concise,
237            OutputFormat::Grouped,
238            OutputFormat::Json,
239            OutputFormat::JsonLines,
240            OutputFormat::GitHub,
241            OutputFormat::GitLab,
242            OutputFormat::Pylint,
243            OutputFormat::Azure,
244            OutputFormat::Sarif,
245            OutputFormat::Junit,
246        ];
247
248        for format in &formats {
249            let formatter = format.create_formatter();
250            // Test that formatter can format warnings
251            let warnings = vec![create_test_warning(1, "Test warning")];
252            let output = formatter.format_warnings(&warnings, "test.md");
253            assert!(!output.is_empty(), "Formatter {format:?} should produce output");
254        }
255    }
256
257    #[test]
258    fn test_output_writer_new() {
259        let writer1 = OutputWriter::new(false, false);
260        assert!(!writer1.use_stderr);
261        assert!(!writer1.silent);
262
263        let writer2 = OutputWriter::new(true, false);
264        assert!(writer2.use_stderr);
265        assert!(!writer2.silent);
266
267        let writer3 = OutputWriter::new(false, true);
268        assert!(!writer3.use_stderr);
269        assert!(writer3.silent);
270    }
271
272    #[test]
273    fn test_output_writer_silent_mode() {
274        let writer = OutputWriter::new(false, true);
275
276        // All write methods should succeed but not produce output when silent
277        assert!(writer.write("test").is_ok());
278        assert!(writer.writeln("test").is_ok());
279        assert!(writer.write_error("test").is_ok());
280    }
281
282    #[test]
283    fn test_output_writer_write_methods() {
284        // Test non-silent mode
285        let writer = OutputWriter::new(false, false);
286
287        // These should succeed (we can't easily test the actual output)
288        assert!(writer.write("test").is_ok());
289        assert!(writer.writeln("test line").is_ok());
290        assert!(writer.write_error("error message").is_ok());
291    }
292
293    #[test]
294    fn test_output_writer_stderr_mode() {
295        let writer = OutputWriter::new(true, false);
296
297        // Should write to stderr instead of stdout
298        assert!(writer.write("stderr test").is_ok());
299        assert!(writer.writeln("stderr line").is_ok());
300
301        // write_error always goes to stderr
302        assert!(writer.write_error("error").is_ok());
303    }
304
305    #[test]
306    fn test_formatter_trait_default_summary() {
307        // Create a simple test formatter
308        struct TestFormatter;
309        impl OutputFormatter for TestFormatter {
310            fn format_warnings(&self, _warnings: &[LintWarning], _file_path: &str) -> String {
311                "test".to_string()
312            }
313        }
314
315        let formatter = TestFormatter;
316        assert_eq!(formatter.format_summary(10, 5, 1000), None);
317        assert!(!formatter.use_colors());
318    }
319
320    #[test]
321    fn test_formatter_with_multiple_warnings() {
322        let warnings = vec![
323            create_test_warning(1, "First warning"),
324            create_test_warning(5, "Second warning"),
325            create_test_warning_with_fix(10, "Third warning with fix", "fixed content"),
326        ];
327
328        // Test with different formatters
329        let text_formatter = TextFormatter::new();
330        let output = text_formatter.format_warnings(&warnings, "test.md");
331        assert!(output.contains("First warning"));
332        assert!(output.contains("Second warning"));
333        assert!(output.contains("Third warning with fix"));
334    }
335
336    #[test]
337    fn test_edge_cases() {
338        // Empty warnings
339        let empty_warnings: Vec<LintWarning> = vec![];
340        let formatter = TextFormatter::new();
341        let output = formatter.format_warnings(&empty_warnings, "test.md");
342        // Most formatters should handle empty warnings gracefully
343        assert!(output.is_empty() || output.trim().is_empty());
344
345        // Very long file path
346        let long_path = "a/".repeat(100) + "file.md";
347        let warnings = vec![create_test_warning(1, "Test")];
348        let output = formatter.format_warnings(&warnings, &long_path);
349        assert!(!output.is_empty());
350
351        // Unicode in messages
352        let unicode_warning = LintWarning {
353            line: 1,
354            column: 1,
355            end_line: 1,
356            end_column: 10,
357            rule_name: Some("MD001".to_string()),
358            message: "Unicode test: 你好 🌟 émphasis".to_string(),
359            severity: Severity::Warning,
360            fix: None,
361        };
362        let output = formatter.format_warnings(&[unicode_warning], "test.md");
363        assert!(output.contains("Unicode test"));
364    }
365
366    #[test]
367    fn test_severity_variations() {
368        let severities = [Severity::Error, Severity::Warning, Severity::Info];
369
370        for severity in &severities {
371            let warning = LintWarning {
372                line: 1,
373                column: 1,
374                end_line: 1,
375                end_column: 5,
376                rule_name: Some("MD001".to_string()),
377                message: format!(
378                    "Test {} message",
379                    match severity {
380                        Severity::Error => "error",
381                        Severity::Warning => "warning",
382                        Severity::Info => "info",
383                    }
384                ),
385                severity: *severity,
386                fix: None,
387            };
388
389            let formatter = TextFormatter::new();
390            let output = formatter.format_warnings(&[warning], "test.md");
391            assert!(!output.is_empty());
392        }
393    }
394
395    #[test]
396    fn test_output_format_equality() {
397        assert_eq!(OutputFormat::Text, OutputFormat::Text);
398        assert_ne!(OutputFormat::Text, OutputFormat::Json);
399        assert_ne!(OutputFormat::Concise, OutputFormat::Grouped);
400    }
401
402    #[test]
403    fn test_all_formats_handle_no_rule_name() {
404        let warning = LintWarning {
405            line: 1,
406            column: 1,
407            end_line: 1,
408            end_column: 5,
409            rule_name: None, // No rule name
410            message: "Generic warning".to_string(),
411            severity: Severity::Warning,
412            fix: None,
413        };
414
415        let formats = [
416            OutputFormat::Text,
417            OutputFormat::Full,
418            OutputFormat::Concise,
419            OutputFormat::Grouped,
420            OutputFormat::Json,
421            OutputFormat::JsonLines,
422            OutputFormat::GitHub,
423            OutputFormat::GitLab,
424            OutputFormat::Pylint,
425            OutputFormat::Azure,
426            OutputFormat::Sarif,
427            OutputFormat::Junit,
428        ];
429
430        for format in &formats {
431            let formatter = format.create_formatter();
432            let output = formatter.format_warnings(std::slice::from_ref(&warning), "test.md");
433            assert!(
434                !output.is_empty(),
435                "Format {format:?} should handle warnings without rule names"
436            );
437        }
438    }
439
440    #[test]
441    fn test_is_machine_readable() {
442        // Human-readable formats
443        assert!(!OutputFormat::Text.is_machine_readable());
444        assert!(!OutputFormat::Full.is_machine_readable());
445        assert!(!OutputFormat::Concise.is_machine_readable());
446        assert!(!OutputFormat::Grouped.is_machine_readable());
447
448        // Machine-readable formats
449        assert!(OutputFormat::Json.is_machine_readable());
450        assert!(OutputFormat::JsonLines.is_machine_readable());
451        assert!(OutputFormat::GitHub.is_machine_readable());
452        assert!(OutputFormat::GitLab.is_machine_readable());
453        assert!(OutputFormat::Pylint.is_machine_readable());
454        assert!(OutputFormat::Azure.is_machine_readable());
455        assert!(OutputFormat::Sarif.is_machine_readable());
456        assert!(OutputFormat::Junit.is_machine_readable());
457    }
458}