//! JUnit XML output format use crate::output::OutputFormatter; use crate::rule::LintWarning; /// JUnit XML formatter for CI systems pub struct JunitFormatter; impl Default for JunitFormatter { fn default() -> Self { Self } } impl JunitFormatter { pub fn new() -> Self { Self } } impl OutputFormatter for JunitFormatter { fn format_warnings(&self, warnings: &[LintWarning], file_path: &str) -> String { // A single file is one testcase that passes (no warnings) or fails. format_junit_report( &[(file_path.to_string(), warnings.to_vec())], &[file_path.to_string()], 0, ) } } /// Format a JUnit XML report covering every checked file. /// /// Each checked file is one `` (`Lint `): a clean file passes (no /// `` child), a file with warnings fails and carries one `` per /// warning. `all_files` lists every file that was checked (clean and dirty); /// `all_warnings` holds only the files that have warnings. Reporting all checked /// files means a clean run lists its passing files rather than emitting an empty /// report. Counts stay JUnit-consistent: `tests` is the number of checked files and /// `failures` the number of files with issues, so `failures <= tests` always holds. pub fn format_junit_report( all_warnings: &[(String, Vec)], all_files: &[String], duration_ms: u64, ) -> String { use std::collections::HashMap; use std::collections::HashSet; let warnings_by_file: HashMap<&str, &[LintWarning]> = all_warnings.iter().map(|(p, w)| (p.as_str(), w.as_slice())).collect(); // Report every checked file once, in order; defensively include any warning- // bearing file that is not in all_files so a warning is never dropped. let mut files: Vec<&str> = Vec::with_capacity(all_files.len()); let mut seen: HashSet<&str> = HashSet::new(); for path in all_files { if seen.insert(path.as_str()) { files.push(path.as_str()); } } for (path, _) in all_warnings { if seen.insert(path.as_str()) { files.push(path.as_str()); } } let warnings_for = |file: &str| -> &[LintWarning] { warnings_by_file.get(file).copied().unwrap_or(&[]) }; let total_tests = files.len(); let files_with_issues = files.iter().filter(|f| !warnings_for(f).is_empty()).count(); let duration_secs = duration_ms as f64 / 1000.0; let mut xml = String::new(); xml.push_str(r#""#); xml.push('\n'); xml.push_str(&format!( r#""# )); xml.push('\n'); for file in files { let warnings = warnings_for(file); let failed = usize::from(!warnings.is_empty()); let escaped_file = xml_escape(file); xml.push_str(&format!( r#" "# )); xml.push('\n'); xml.push_str(&format!( r#" "# )); xml.push('\n'); // A clean file's testcase has no children, so it passes. for warning in warnings { let rule_name = warning.rule_name.as_deref().unwrap_or("unknown"); let message = xml_escape(&warning.message); xml.push_str(&format!( r#" {} at line {}, column {}"#, rule_name, message, message, warning.line, warning.column )); xml.push('\n'); } xml.push_str(" \n"); xml.push_str(" \n"); } xml.push_str("\n"); xml } /// Escape special XML characters fn xml_escape(s: &str) -> String { let mut escaped = String::with_capacity(s.len()); for character in s.chars() { match character { '&' => escaped.push_str("&"), '<' => escaped.push_str("<"), '>' => escaped.push_str(">"), '"' => escaped.push_str("""), '\'' => escaped.push_str("'"), // XML 1.0 permits tab, LF, CR, U+0020..U+D7FF, // U+E000..U+FFFD, and supplementary Unicode characters. '\u{9}' | '\u{a}' | '\u{d}' | '\u{20}'..='\u{d7ff}' | '\u{e000}'..='\u{fffd}' | '\u{10000}'..='\u{10ffff}' => escaped.push(character), _ => escaped.push('\u{fffd}'), } } escaped } #[cfg(test)] mod tests { use super::*; use crate::rule::{Fix, Severity}; fn warning(line: usize, column: usize, rule: &str, message: &str) -> LintWarning { LintWarning { line, column, end_line: line, end_column: column, rule_name: Some(rule.to_string()), message: message.to_string(), severity: Severity::Warning, fix: None, } } /// Count `` elements in the report. fn count_failures(xml: &str) -> usize { xml.matches(", failures="0". let output = JunitFormatter::new().format_warnings(&[], "test.md"); assert!(output.starts_with("")); assert!(output.contains("")); assert!(output.contains("")); assert_eq!(count_failures(&output), 0); } #[test] fn test_format_single_warning() { let warnings = vec![warning( 10, 5, "MD001", "Heading levels should only increment by one level at a time", )]; let output = JunitFormatter::new().format_warnings(&warnings, "README.md"); assert!(output.contains("") ); assert!(output.contains( "" )); assert!(output.contains("at line 10, column 5")); } #[test] fn test_multiple_warnings_in_one_file_are_one_failed_testcase() { // One file with two warnings is ONE failed testcase (failures="1"), with two // children - not failures="2" (which would exceed tests="1"). let warnings = vec![ warning(5, 1, "MD001", "First warning"), warning(10, 3, "MD013", "Second warning"), ]; let output = JunitFormatter::new().format_warnings(&warnings, "test.md"); assert!(output.contains("")); assert_eq!(count_failures(&output), 2); assert!(output.contains("")); assert!(output.contains("")); } #[test] fn test_format_single_warning_with_fix_has_no_fixable_marker() { let mut w = warning(10, 5, "MD001", "Heading"); w.fix = Some(Fix::new(100..110, "## Heading".to_string())); let output = JunitFormatter::new().format_warnings(&[w], "README.md"); assert!(output.contains("")); } // ---- batch report (format_junit_report) ---------------------------------- #[test] fn test_report_no_files_is_empty() { let output = format_junit_report(&[], &[], 1234); assert!(output.starts_with("")); assert!(output.contains("")); assert!(output.ends_with("\n")); } #[test] fn test_report_all_clean_files_listed_as_passing() { // The core of issue #654: a clean run lists its passing files, not an empty report. let all_files = vec!["a.md".to_string(), "b.md".to_string()]; let output = format_junit_report(&[], &all_files, 500); assert!(output.contains("")); assert!(output.contains(" failures <= tests. assert!(output.contains(" = (1..=5).map(|i| warning(i, 1, "MD013", "long line")).collect(); let output = format_junit_report(&[("x.md".to_string(), warnings)], &all_files, 0); assert!(output.contains(""), "text with < and >"); assert_eq!(xml_escape("text with \" quotes"), "text with " quotes"); assert_eq!(xml_escape("text with ' apostrophe"), "text with ' apostrophe"); assert_eq!(xml_escape("all: < > & \" '"), "all: < > & " '"); } #[test] fn test_special_characters_in_message() { let warnings = vec![warning(1, 1, "MD001", "Warning with < > & \" ' special chars")]; let output = JunitFormatter::new().format_warnings(&warnings, "test.md"); assert!(output.contains("message=\"Warning with < > & " ' special chars\"")); assert!(output.contains(">Warning with < > & " ' special chars at line")); } #[test] fn test_special_characters_in_file_path() { let warnings = vec![warning(1, 1, "MD001", "Test")]; let output = JunitFormatter::new().format_warnings(&warnings, "path/with&chars.md"); assert!(output.contains(" = output.lines().collect(); assert_eq!(lines[0], ""); assert!(lines[1].starts_with(""); assert_eq!(lines[6], " "); assert_eq!(lines[7], ""); } }