1use crate::rule::LintWarning;
7use std::io::{self, Write};
8use std::str::FromStr;
9
10pub mod formatters;
11
12pub use formatters::*;
14
15pub trait OutputFormatter {
17 fn format_warnings(&self, warnings: &[LintWarning], file_path: &str) -> String;
19
20 fn format_warnings_with_content(&self, warnings: &[LintWarning], file_path: &str, _content: &str) -> String {
24 self.format_warnings(warnings, file_path)
25 }
26
27 fn format_summary(&self, _files_processed: usize, _total_warnings: usize, _duration_ms: u64) -> Option<String> {
29 None
31 }
32
33 fn use_colors(&self) -> bool {
35 false
36 }
37}
38
39#[derive(Debug, Clone, Copy, PartialEq)]
41pub enum OutputFormat {
42 Text,
44 Full,
46 Concise,
48 Grouped,
50 Json,
52 JsonLines,
54 GitHub,
56 GitLab,
58 Pylint,
60 Azure,
62 Sarif,
64 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 pub fn is_machine_readable(&self) -> bool {
94 !matches!(
95 self,
96 OutputFormat::Text | OutputFormat::Full | OutputFormat::Concise | OutputFormat::Grouped
97 )
98 }
99
100 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
119pub 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 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 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 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 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 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 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 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 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 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 let writer = OutputWriter::new(false, false);
286
287 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 assert!(writer.write("stderr test").is_ok());
299 assert!(writer.writeln("stderr line").is_ok());
300
301 assert!(writer.write_error("error").is_ok());
303 }
304
305 #[test]
306 fn test_formatter_trait_default_summary() {
307 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 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 let empty_warnings: Vec<LintWarning> = vec![];
340 let formatter = TextFormatter::new();
341 let output = formatter.format_warnings(&empty_warnings, "test.md");
342 assert!(output.is_empty() || output.trim().is_empty());
344
345 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 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, 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 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 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}