From 32f6b8c05257fdb7f16e58039148cb3c901ba610 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Tue, 24 Nov 2026 16:34:28 +0800 Subject: [PATCH 1/6] feat(metrics): add coverage readers, path matcher, applicator, and Test gap metric --- crates/metrics/src/coverage.rs | 136 ++++++ crates/metrics/src/coverage/apply.rs | 183 +++++++ crates/metrics/src/coverage/cobertura.rs | 592 +++++++++++++++++++++++ crates/metrics/src/coverage/lcov.rs | 151 ++++++ crates/metrics/src/coverage/matcher.rs | 198 ++++++++ crates/metrics/src/coverage/tests.rs | 559 +++++++++++++++++++++ crates/metrics/src/erosion.rs | 8 +- crates/metrics/src/lib.rs | 10 + crates/metrics/src/test_gap.rs | 198 ++++++++ crates/metrics/src/test_gap/tests.rs | 232 +++++++++ 10 files changed, 2265 insertions(+), 2 deletions(-) create mode 100644 crates/metrics/src/coverage.rs create mode 100644 crates/metrics/src/coverage/apply.rs create mode 100644 crates/metrics/src/coverage/cobertura.rs create mode 100644 crates/metrics/src/coverage/lcov.rs create mode 100644 crates/metrics/src/coverage/matcher.rs create mode 100644 crates/metrics/src/coverage/tests.rs create mode 100644 crates/metrics/src/test_gap.rs create mode 100644 crates/metrics/src/test_gap/tests.rs diff --git a/crates/metrics/src/coverage.rs b/crates/metrics/src/coverage.rs new file mode 100644 index 00000000..b8ecb43d --- /dev/null +++ b/crates/metrics/src/coverage.rs @@ -0,0 +1,136 @@ +use std::collections::BTreeMap; +use std::fmt; + +mod apply; +mod cobertura; +mod lcov; +mod matcher; +#[cfg(test)] +mod tests; + +pub use apply::{ + CoverageApplyError, CoverageApplyOutcome, NamedCoverageReport, apply_coverage_reports, +}; +pub use cobertura::{parse_cobertura, parse_cobertura_with_limits}; +pub use lcov::{parse_lcov, parse_lcov_with_limits}; +pub use matcher::{PathMatcher, match_coverage_path}; + +pub const MAX_COVERAGE_REPORT_BYTES: usize = 64 * 1024 * 1024; +pub const MAX_XML_NESTING_DEPTH: usize = 64; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CoverageLimits { + pub max_bytes: usize, + pub max_xml_depth: usize, +} + +impl Default for CoverageLimits { + fn default() -> CoverageLimits { + CoverageLimits { + max_bytes: MAX_COVERAGE_REPORT_BYTES, + max_xml_depth: MAX_XML_NESTING_DEPTH, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CoverageFormat { + Lcov, + Cobertura, +} + +impl fmt::Display for CoverageFormat { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + CoverageFormat::Lcov => formatter.write_str("LCOV"), + CoverageFormat::Cobertura => formatter.write_str("Cobertura XML"), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CoverageFileRecord { + pub path: String, + pub lines: BTreeMap, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ParsedCoverageReport { + pub format: CoverageFormat, + pub source_roots: Vec, + pub files: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum CoverageParseError { + #[error("Coverage report is {size_bytes} bytes, exceeding the {max_bytes}-byte limit")] + ReportTooLarge { size_bytes: usize, max_bytes: usize }, + #[error("Coverage report is not valid UTF-8")] + InvalidUtf8, + #[error( + "Coverage report format is not recognized; supported formats are LCOV and Cobertura XML" + )] + UnrecognizedFormat, + #[error("invalid LCOV record on line {line}: {content:?}")] + InvalidLcovRecord { line: usize, content: String }, + #[error("invalid LCOV record on line {line}: {reason}")] + InvalidLcovData { line: usize, reason: String }, + #[error("rejected unsafe Cobertura XML: {reason}")] + XmlSecurityViolation { reason: String }, + #[error("Cobertura XML exceeds maximum nesting depth of {max_depth}")] + XmlNestingTooDeep { max_depth: usize }, + #[error("invalid Cobertura XML: {reason}")] + InvalidCoberturaXml { reason: String }, +} + +pub fn parse_coverage_report(bytes: &[u8]) -> Result { + parse_coverage_report_with_limits(bytes, CoverageLimits::default()) +} + +pub fn parse_coverage_report_with_limits( + bytes: &[u8], + limits: CoverageLimits, +) -> Result { + let text = decode_report_utf8(bytes, limits.max_bytes)?; + let trimmed = text.trim_start(); + if trimmed.is_empty() { + return Err(CoverageParseError::UnrecognizedFormat); + } + if trimmed.starts_with('<') { + return cobertura::parse_cobertura_str(text, limits.max_xml_depth); + } + if lcov::is_lcov_start(trimmed) { + return lcov::parse_lcov_str(text); + } + Err(CoverageParseError::UnrecognizedFormat) +} + +pub(crate) fn decode_report_utf8( + bytes: &[u8], + max_bytes: usize, +) -> Result<&str, CoverageParseError> { + if bytes.len() > max_bytes { + return Err(CoverageParseError::ReportTooLarge { + size_bytes: bytes.len(), + max_bytes, + }); + } + let text = std::str::from_utf8(bytes).map_err(|_| CoverageParseError::InvalidUtf8)?; + Ok(text.strip_prefix('\u{feff}').unwrap_or(text)) +} + +pub(crate) fn merge_line_hit(lines: &mut BTreeMap, line: u32, hits: u64) { + lines + .entry(line) + .and_modify(|existing| *existing = existing.saturating_add(hits)) + .or_insert(hits); +} + +pub(crate) fn collect_file_records( + files: BTreeMap>, +) -> Vec { + files + .into_iter() + .map(|(path, lines)| CoverageFileRecord { path, lines }) + .collect() +} diff --git a/crates/metrics/src/coverage/apply.rs b/crates/metrics/src/coverage/apply.rs new file mode 100644 index 00000000..5a1ee841 --- /dev/null +++ b/crates/metrics/src/coverage/apply.rs @@ -0,0 +1,183 @@ +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +use codeint_model::{CodeModel, FileModel, FunctionCoverage, RepoPath}; + +use super::{ParsedCoverageReport, PathMatcher, merge_line_hit}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NamedCoverageReport { + pub path: String, + pub report: ParsedCoverageReport, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CoverageApplyOutcome { + pub unmatched_paths: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum CoverageApplyError { + #[error( + "Coverage report {report:?} lists line {line} for {file}, which is beyond the file's {line_count} lines" + )] + LineOutOfRange { + report: String, + file: RepoPath, + line: u32, + line_count: usize, + }, +} + +pub fn apply_coverage_reports( + reports: &[NamedCoverageReport], + models: &mut [CodeModel], + file_line_counts: &BTreeMap, +) -> Result { + if reports.is_empty() { + return Ok(CoverageApplyOutcome::default()); + } + let known_paths = collect_known_paths(models, file_line_counts); + let inferred_counts = collect_inferred_line_counts(models); + let matcher = PathMatcher::new(&known_paths); + let mut merged_lines: HashMap> = HashMap::new(); + let mut unmatched_paths: BTreeSet = BTreeSet::new(); + + for named in reports { + for record in &named.report.files { + let Some(matched_path) = matcher.match_path(&record.path, &named.report.source_roots) + else { + unmatched_paths.insert(record.path.clone()); + continue; + }; + let line_count = resolve_line_count(matched_path, file_line_counts, &inferred_counts); + let target = merged_lines.entry(matched_path.clone()).or_default(); + for (&line, &hits) in &record.lines { + let line_usize = usize::try_from(line).unwrap_or(usize::MAX); + if line == 0 || line_usize > line_count { + return Err(CoverageApplyError::LineOutOfRange { + report: named.path.clone(), + file: matched_path.clone(), + line, + line_count, + }); + } + merge_line_hit(target, line, hits); + } + } + } + + apply_merged_coverage(models, &merged_lines); + Ok(CoverageApplyOutcome { + unmatched_paths: unmatched_paths.into_iter().collect(), + }) +} + +fn collect_known_paths( + models: &[CodeModel], + file_line_counts: &BTreeMap, +) -> Vec { + let mut paths: BTreeSet = file_line_counts.keys().cloned().collect(); + for model in models { + for file in &model.files { + paths.insert(file.path.clone()); + } + for path in &model.declaration_only { + paths.insert(path.clone()); + } + for skipped in &model.skipped { + paths.insert(skipped.path.clone()); + } + } + paths.into_iter().collect() +} + +fn collect_inferred_line_counts(models: &[CodeModel]) -> HashMap { + let mut counts = HashMap::new(); + for model in models { + for file in &model.files { + counts.insert(file.path.clone(), inferred_line_count(&file.model)); + } + } + counts +} + +fn inferred_line_count(file: &FileModel) -> usize { + let max_function_line = file + .functions + .iter() + .map(|function| function.end_line) + .max() + .unwrap_or(0); + let max_token_line = file + .tokens + .iter() + .map(|token| token.line) + .max() + .unwrap_or(0); + let max_line = file.source_lines.max(max_function_line).max(max_token_line); + usize::try_from(max_line).unwrap_or(usize::MAX) +} + +fn resolve_line_count( + path: &RepoPath, + file_line_counts: &BTreeMap, + inferred_counts: &HashMap, +) -> usize { + file_line_counts + .get(path) + .copied() + .or_else(|| inferred_counts.get(path).copied()) + .unwrap_or(0) +} + +fn apply_merged_coverage( + models: &mut [CodeModel], + merged_lines: &HashMap>, +) { + for model in models { + let mut model_has_coverage = false; + for file in &mut model.files { + let Some(file_lines) = merged_lines.get(&file.path) else { + continue; + }; + model_has_coverage = true; + for function in &mut file.model.functions { + function.coverage = Some(summarize_function_coverage( + function.line, + function.end_line, + file_lines, + )); + } + } + if model_has_coverage { + for facts in &mut model.languages { + facts.has_coverage = true; + } + } + } +} + +fn summarize_function_coverage( + start_line: u32, + end_line: u32, + file_lines: &BTreeMap, +) -> FunctionCoverage { + if start_line > end_line { + return FunctionCoverage { + listed_lines: 0, + executed_lines: 0, + }; + } + let mut listed_lines: u32 = 0; + let mut executed_lines: u32 = 0; + for (_, &hits) in file_lines.range(start_line..=end_line) { + listed_lines = listed_lines.saturating_add(1); + if hits > 0 { + executed_lines = executed_lines.saturating_add(1); + } + } + FunctionCoverage { + listed_lines, + executed_lines, + } +} diff --git a/crates/metrics/src/coverage/cobertura.rs b/crates/metrics/src/coverage/cobertura.rs new file mode 100644 index 00000000..f4e8ce4c --- /dev/null +++ b/crates/metrics/src/coverage/cobertura.rs @@ -0,0 +1,592 @@ +use std::collections::BTreeMap; + +use super::{ + CoverageFormat, CoverageLimits, CoverageParseError, ParsedCoverageReport, collect_file_records, + decode_report_utf8, merge_line_hit, +}; + +pub fn parse_cobertura(bytes: &[u8]) -> Result { + parse_cobertura_with_limits(bytes, CoverageLimits::default()) +} + +pub fn parse_cobertura_with_limits( + bytes: &[u8], + limits: CoverageLimits, +) -> Result { + let text = decode_report_utf8(bytes, limits.max_bytes)?; + parse_cobertura_str(text, limits.max_xml_depth) +} + +pub(crate) fn parse_cobertura_str( + text: &str, + max_depth: usize, +) -> Result { + let mut scanner = XmlScanner::new(text); + let mut builder = CoberturaBuilder::new(max_depth); + while !scanner.is_eof() { + if scanner.peek() == Some(b'<') { + parse_markup(&mut scanner, &mut builder)?; + } else { + let text_chunk = scanner.read_text()?; + builder.handle_text(&text_chunk)?; + } + } + builder.finish() +} + +fn parse_markup( + scanner: &mut XmlScanner<'_>, + builder: &mut CoberturaBuilder, +) -> Result<(), CoverageParseError> { + if scanner.starts_with("") else { + return Err(invalid_xml("unclosed XML comment")); + }; + if self.remaining()[..end_offset].contains("--") { + return Err(invalid_xml("XML comment must not contain '--'")); + } + self.pos += end_offset + 3; + Ok(()) + } + + fn read_cdata(&mut self) -> Result<&'a str, CoverageParseError> { + self.pos += 9; + let Some(end_offset) = self.remaining().find("]]>") else { + return Err(invalid_xml("unclosed CDATA section")); + }; + let content = &self.remaining()[..end_offset]; + self.pos += end_offset + 3; + Ok(content) + } + + fn skip_processing_instruction( + &mut self, + saw_xml_decl: &mut bool, + saw_root: bool, + ) -> Result<(), CoverageParseError> { + self.pos += 2; + let target = self.read_name()?; + if target != "xml" { + return Err(CoverageParseError::XmlSecurityViolation { + reason: format!("processing instruction is not allowed"), + }); + } + if *saw_xml_decl || saw_root { + return Err(invalid_xml( + "XML declaration is only allowed once before the root element", + )); + } + let Some(end_offset) = self.remaining().find("?>") else { + return Err(invalid_xml("unclosed XML declaration")); + }; + let body = &self.remaining()[..end_offset]; + if !body.is_empty() + && !body + .as_bytes() + .first() + .copied() + .is_some_and(is_xml_whitespace) + { + return Err(CoverageParseError::XmlSecurityViolation { + reason: "processing instructions other than are not allowed".to_owned(), + }); + } + if body.contains('<') || body.contains('&') { + return Err(invalid_xml("invalid XML declaration")); + } + self.pos += end_offset + 2; + *saw_xml_decl = true; + Ok(()) + } + + fn read_start_tag(&mut self) -> Result, CoverageParseError> { + self.pos += 1; + let name = self.read_name()?; + let (attrs, self_closing) = self.read_attributes()?; + Ok(StartTag { + name, + attrs, + self_closing, + }) + } + + fn read_end_tag(&mut self) -> Result<&'a str, CoverageParseError> { + self.pos += 2; + let name = self.read_name()?; + self.skip_whitespace(); + if self.peek() != Some(b'>') { + return Err(invalid_xml("expected '>' at end of closing tag")); + } + self.pos += 1; + Ok(name) + } + + fn read_name(&mut self) -> Result<&'a str, CoverageParseError> { + let start = self.pos; + let mut chars = self.remaining().char_indices(); + let Some((_, first)) = chars.next() else { + return Err(invalid_xml("unexpected end of XML while reading name")); + }; + if !is_xml_name_start(first) { + return Err(invalid_xml("invalid XML name")); + } + let mut end = first.len_utf8(); + for (offset, ch) in chars { + if is_xml_name_char(ch) { + end = offset + ch.len_utf8(); + } else { + break; + } + } + self.pos = start + end; + Ok(&self.text[start..self.pos]) + } + + fn read_attributes(&mut self) -> Result<(Vec<(String, String)>, bool), CoverageParseError> { + let mut attrs: Vec<(String, String)> = Vec::new(); + loop { + let had_ws = self.skip_whitespace(); + if self.starts_with("/>") { + self.pos += 2; + return Ok((attrs, true)); + } + if self.peek() == Some(b'>') { + self.pos += 1; + return Ok((attrs, false)); + } + if self.is_eof() { + return Err(invalid_xml("unclosed XML start tag")); + } + if !had_ws { + return Err(invalid_xml("expected whitespace before XML attribute")); + } + let attr_name = self.read_name()?; + if attrs.iter().any(|(existing, _)| existing == attr_name) { + return Err(invalid_xml(&format!( + "duplicate XML attribute {attr_name:?}" + ))); + } + self.skip_whitespace(); + if self.peek() != Some(b'=') { + return Err(invalid_xml("expected '=' after XML attribute name")); + } + self.pos += 1; + self.skip_whitespace(); + let value = self.read_quoted_value()?; + attrs.push((attr_name.to_owned(), value)); + } + } + + fn read_quoted_value(&mut self) -> Result { + let quote = match self.peek() { + Some(b'"') => b'"', + Some(b'\'') => b'\'', + _ => return Err(invalid_xml("expected quoted XML attribute value")), + }; + self.pos += 1; + let start = self.pos; + while let Some(byte) = self.peek() { + if byte == quote { + let raw = &self.text[start..self.pos]; + self.pos += 1; + return decode_xml_text(raw); + } + if byte == b'<' { + return Err(invalid_xml("'<' is not allowed inside XML attribute value")); + } + self.pos += 1; + } + Err(invalid_xml("unclosed XML attribute value")) + } + + fn read_text(&mut self) -> Result { + let start = self.pos; + while let Some(byte) = self.peek() { + if byte == b'<' { + break; + } + self.pos += 1; + } + let raw = &self.text[start..self.pos]; + if raw.contains("]]>") { + return Err(invalid_xml("']]>' is not allowed in XML text content")); + } + decode_xml_text(raw) + } +} + +fn find_attr<'a>(attrs: &'a [(String, String)], name: &str) -> Option<&'a str> { + attrs + .iter() + .find(|(key, _)| key == name) + .map(|(_, value)| value.as_str()) +} + +fn decode_xml_text(raw: &str) -> Result { + if !raw.contains('&') { + return Ok(raw.to_owned()); + } + let mut decoded = String::with_capacity(raw.len()); + let mut rest = raw; + while let Some(amp_index) = rest.find('&') { + decoded.push_str(&rest[..amp_index]); + let after_amp = &rest[amp_index + 1..]; + let Some(semi_index) = after_amp.find(';') else { + return Err(invalid_xml("unterminated XML entity reference")); + }; + let entity = &after_amp[..semi_index]; + if entity.is_empty() || entity.contains('&') { + return Err(invalid_xml("malformed XML entity reference")); + } + decoded.push(decode_xml_entity(entity)?); + rest = &after_amp[semi_index + 1..]; + } + decoded.push_str(rest); + Ok(decoded) +} + +fn decode_xml_entity(entity: &str) -> Result { + match entity { + "lt" => Ok('<'), + "gt" => Ok('>'), + "amp" => Ok('&'), + "quot" => Ok('"'), + "apos" => Ok('\''), + _ if entity.starts_with('#') => parse_numeric_entity(&entity[1..]), + _ => Err(CoverageParseError::XmlSecurityViolation { + reason: format!("disallowed XML entity reference &{entity};"), + }), + } +} + +fn parse_numeric_entity(spec: &str) -> Result { + let code = if let Some(hex) = spec.strip_prefix('x').or_else(|| spec.strip_prefix('X')) { + u32::from_str_radix(hex, 16) + } else { + spec.parse::() + } + .map_err(|_| invalid_xml(&format!("invalid numeric character reference &#{spec};")))?; + if !is_valid_xml_char_code(code) { + return Err(invalid_xml(&format!( + "character reference &#{spec}; is not a valid XML character" + ))); + } + char::from_u32(code).ok_or_else(|| { + invalid_xml(&format!( + "character reference &#{spec}; is not a valid Unicode scalar" + )) + }) +} + +fn is_valid_xml_char_code(code: u32) -> bool { + matches!( + code, + 0x09 | 0x0A | 0x0D | 0x20..=0xD7FF | 0xE000..=0xFFFD | 0x10000..=0x10FFFF + ) +} + +fn is_xml_whitespace(byte: u8) -> bool { + matches!(byte, b' ' | b'\t' | b'\r' | b'\n') +} + +fn is_xml_name_start(ch: char) -> bool { + ch == ':' || ch == '_' || ch.is_alphabetic() +} + +fn is_xml_name_char(ch: char) -> bool { + is_xml_name_start(ch) || ch == '-' || ch == '.' || ch.is_numeric() +} + +fn invalid_xml(reason: &str) -> CoverageParseError { + CoverageParseError::InvalidCoberturaXml { + reason: reason.to_owned(), + } +} diff --git a/crates/metrics/src/coverage/lcov.rs b/crates/metrics/src/coverage/lcov.rs new file mode 100644 index 00000000..97fed2ff --- /dev/null +++ b/crates/metrics/src/coverage/lcov.rs @@ -0,0 +1,151 @@ +use std::collections::BTreeMap; + +use super::{ + CoverageFormat, CoverageParseError, MAX_COVERAGE_REPORT_BYTES, ParsedCoverageReport, + collect_file_records, decode_report_utf8, merge_line_hit, +}; + +const IGNORED_LCOV_TAGS: [&str; 10] = [ + "TN", "FN", "FNDA", "FNF", "FNH", "BRDA", "BRF", "BRH", "LF", "LH", +]; + +pub fn parse_lcov(bytes: &[u8]) -> Result { + parse_lcov_with_limits(bytes, MAX_COVERAGE_REPORT_BYTES) +} + +pub fn parse_lcov_with_limits( + bytes: &[u8], + max_bytes: usize, +) -> Result { + let text = decode_report_utf8(bytes, max_bytes)?; + parse_lcov_str(text) +} + +pub(crate) fn is_lcov_start(trimmed: &str) -> bool { + let first_line = trimmed + .lines() + .map(|line| line.strip_suffix('\r').unwrap_or(line)) + .find(|line| !line.is_empty()); + let Some(line) = first_line else { + return false; + }; + if line == "end_of_record" { + return true; + } + let Some((tag, _)) = line.split_once(':') else { + return false; + }; + tag == "SF" || tag == "DA" || IGNORED_LCOV_TAGS.contains(&tag) +} + +pub(crate) fn parse_lcov_str(text: &str) -> Result { + let mut files: BTreeMap> = BTreeMap::new(); + let mut current_file: Option = None; + let mut saw_any_record = false; + for (index, raw_line) in text.lines().enumerate() { + let line_number = index + 1; + let line = raw_line.strip_suffix('\r').unwrap_or(raw_line); + if line.is_empty() { + continue; + } + saw_any_record = true; + parse_lcov_line(line, line_number, &mut current_file, &mut files)?; + } + if !saw_any_record { + return Err(CoverageParseError::UnrecognizedFormat); + } + Ok(ParsedCoverageReport { + format: CoverageFormat::Lcov, + source_roots: Vec::new(), + files: collect_file_records(files), + }) +} + +fn parse_lcov_line( + line: &str, + line_number: usize, + current_file: &mut Option, + files: &mut BTreeMap>, +) -> Result<(), CoverageParseError> { + if line == "end_of_record" { + *current_file = None; + return Ok(()); + } + let Some((tag, value)) = line.split_once(':') else { + return Err(CoverageParseError::InvalidLcovRecord { + line: line_number, + content: line.to_owned(), + }); + }; + match tag { + "SF" => { + let path = value.trim(); + if path.is_empty() { + return Err(CoverageParseError::InvalidLcovData { + line: line_number, + reason: "SF record has an empty file path".to_owned(), + }); + } + files.entry(path.to_owned()).or_default(); + *current_file = Some(path.to_owned()); + Ok(()) + } + "DA" => { + let Some(path) = current_file.as_deref() else { + return Err(CoverageParseError::InvalidLcovData { + line: line_number, + reason: "DA record appears outside an SF section".to_owned(), + }); + }; + let (target_line, hits) = parse_da_fields(value, line_number)?; + let lines = files.entry(path.to_owned()).or_default(); + merge_line_hit(lines, target_line, hits); + Ok(()) + } + _ if IGNORED_LCOV_TAGS.contains(&tag) => Ok(()), + _ => Err(CoverageParseError::InvalidLcovRecord { + line: line_number, + content: line.to_owned(), + }), + } +} + +fn parse_da_fields(value: &str, line_number: usize) -> Result<(u32, u64), CoverageParseError> { + let mut parts = value.split(','); + let line_part = parts.next().unwrap_or(""); + let hits_part = parts + .next() + .ok_or_else(|| CoverageParseError::InvalidLcovData { + line: line_number, + reason: "DA record must contain line number and hit count".to_owned(), + })?; + let _checksum = parts.next(); + if parts.next().is_some() { + return Err(CoverageParseError::InvalidLcovData { + line: line_number, + reason: "DA record has too many comma-separated fields".to_owned(), + }); + } + let target_line: u32 = + line_part + .trim() + .parse() + .map_err(|_| CoverageParseError::InvalidLcovData { + line: line_number, + reason: format!("invalid DA line number {line_part:?}"), + })?; + if target_line == 0 { + return Err(CoverageParseError::InvalidLcovData { + line: line_number, + reason: "DA line number must be positive".to_owned(), + }); + } + let hits: u64 = hits_part + .trim() + .parse() + .map_err(|_| CoverageParseError::InvalidLcovData { + line: line_number, + reason: format!("invalid DA hit count {hits_part:?}"), + })?; + Ok((target_line, hits)) +} diff --git a/crates/metrics/src/coverage/matcher.rs b/crates/metrics/src/coverage/matcher.rs new file mode 100644 index 00000000..f64dcd29 --- /dev/null +++ b/crates/metrics/src/coverage/matcher.rs @@ -0,0 +1,198 @@ +use std::collections::{BTreeSet, HashMap}; + +use codeint_model::RepoPath; + +pub struct PathMatcher<'a> { + by_file_name: HashMap<&'a str, Vec>>, +} + +struct IndexedRepoPath<'a> { + path: &'a RepoPath, + segments: Vec<&'a str>, +} + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +struct MatchScore { + exact: bool, + common_segments: usize, +} + +enum MatchCandidateResult<'a> { + None, + Matched { + score: MatchScore, + paths: Vec<&'a RepoPath>, + }, +} + +impl<'a> PathMatcher<'a> { + pub fn new(repository_paths: &'a [RepoPath]) -> PathMatcher<'a> { + let mut by_file_name: HashMap<&'a str, Vec>> = HashMap::new(); + for path in repository_paths { + let segments: Vec<&'a str> = path.as_str().split('/').collect(); + by_file_name + .entry(path.file_name()) + .or_default() + .push(IndexedRepoPath { path, segments }); + } + PathMatcher { by_file_name } + } + + pub fn match_path(&self, report_path: &str, source_roots: &[String]) -> Option<&'a RepoPath> { + if !source_roots.is_empty() + && !is_absolute_path(report_path) + && let Some(resolved) = self.match_with_source_roots(report_path, source_roots) + { + return resolved; + } + let segments = normalize_segments(report_path); + self.unique_match_for_segments(&segments) + } + + fn match_with_source_roots( + &self, + report_path: &str, + source_roots: &[String], + ) -> Option> { + let mut best_score: Option = None; + let mut winners: BTreeSet<&'a RepoPath> = BTreeSet::new(); + for root in source_roots { + let trimmed_root = root.trim(); + if trimmed_root.is_empty() { + continue; + } + let combined = format!("{trimmed_root}/{report_path}"); + let segments = normalize_segments(&combined); + let MatchCandidateResult::Matched { score, paths } = + self.best_matches_for_segments(&segments) + else { + continue; + }; + match best_score { + Some(current) if score < current => {} + Some(current) if score == current => { + winners.extend(paths); + } + _ => { + best_score = Some(score); + winners.clear(); + winners.extend(paths); + } + } + } + if winners.is_empty() { + return None; + } + if winners.len() == 1 { + return Some(winners.into_iter().next()); + } + Some(None) + } + + fn unique_match_for_segments(&self, segments: &[String]) -> Option<&'a RepoPath> { + match self.best_matches_for_segments(segments) { + MatchCandidateResult::Matched { paths, .. } if paths.len() == 1 => Some(paths[0]), + _ => None, + } + } + + fn best_matches_for_segments(&self, segments: &[String]) -> MatchCandidateResult<'a> { + let Some(file_name) = segments.last().map(String::as_str) else { + return MatchCandidateResult::None; + }; + if file_name == ".." { + return MatchCandidateResult::None; + } + let Some(candidates) = self.by_file_name.get(file_name) else { + return MatchCandidateResult::None; + }; + let mut best_score: Option = None; + let mut winners: Vec<&'a RepoPath> = Vec::new(); + for candidate in candidates { + let Some(score) = score_match(segments, &candidate.segments) else { + continue; + }; + match best_score { + Some(current) if score < current => {} + Some(current) if score == current => { + winners.push(candidate.path); + } + _ => { + best_score = Some(score); + winners.clear(); + winners.push(candidate.path); + } + } + } + match best_score { + Some(score) => MatchCandidateResult::Matched { + score, + paths: winners, + }, + None => MatchCandidateResult::None, + } + } +} + +pub fn match_coverage_path<'a>( + report_path: &str, + source_roots: &[String], + repository_paths: &'a [RepoPath], +) -> Option<&'a RepoPath> { + PathMatcher::new(repository_paths).match_path(report_path, source_roots) +} + +fn score_match(report_segments: &[String], repo_segments: &[&str]) -> Option { + let common = common_trailing_segments(report_segments, repo_segments); + let required = report_segments.len().min(repo_segments.len()); + if common == 0 || common < required { + return None; + } + Some(MatchScore { + exact: report_segments.len() == repo_segments.len() && common == repo_segments.len(), + common_segments: common, + }) +} + +fn common_trailing_segments(report_segments: &[String], repo_segments: &[&str]) -> usize { + report_segments + .iter() + .rev() + .zip(repo_segments.iter().rev()) + .take_while(|(left, right)| left.as_str() == **right) + .count() +} + +fn is_absolute_path(raw: &str) -> bool { + let trimmed = raw.trim(); + trimmed.starts_with('/') || trimmed.starts_with('\\') || has_windows_drive_prefix(trimmed) +} + +fn has_windows_drive_prefix(path: &str) -> bool { + let bytes = path.as_bytes(); + bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' +} + +fn normalize_segments(raw: &str) -> Vec { + let replaced = raw.trim().replace('\\', "/"); + let without_drive = if has_windows_drive_prefix(&replaced) { + &replaced[2..] + } else { + replaced.as_str() + }; + let mut stack: Vec = Vec::new(); + for segment in without_drive.split('/') { + match segment { + "" | "." => {} + ".." => { + if stack.last().is_some_and(|prev| prev != "..") { + stack.pop(); + } else { + stack.push("..".to_owned()); + } + } + other => stack.push(other.to_owned()), + } + } + stack +} diff --git a/crates/metrics/src/coverage/tests.rs b/crates/metrics/src/coverage/tests.rs new file mode 100644 index 00000000..1678568f --- /dev/null +++ b/crates/metrics/src/coverage/tests.rs @@ -0,0 +1,559 @@ +use std::collections::BTreeMap; + +use codeint_model::language::Function; +use codeint_model::{CodeModel, FunctionCoverage, LanguageFacts, RepoPath, SourceFile, SourceSet}; + +use super::{ + CoverageApplyError, CoverageFormat, CoverageLimits, CoverageParseError, NamedCoverageReport, + PathMatcher, apply_coverage_reports, match_coverage_path, parse_cobertura, + parse_cobertura_with_limits, parse_coverage_report, parse_coverage_report_with_limits, + parse_lcov, parse_lcov_with_limits, +}; +use crate::test_support::{empty_source_file, repo_path}; + +fn make_function(name: &str, line: u32, end_line: u32) -> Function { + Function { + line, + end_line, + decision_points: 0, + source_lines: end_line.saturating_sub(line).saturating_add(1), + name: Some(name.to_owned()), + cognitive_complexity: 0, + coverage: None, + } +} + +fn source_file_with_functions( + path: &str, + source_set: SourceSet, + source_lines: u32, + functions: Vec, +) -> SourceFile { + let mut file = empty_source_file(path, source_set, source_lines); + file.model.functions = functions; + file +} + +fn language_model(language: &str, files: Vec) -> CodeModel { + CodeModel { + files, + languages: vec![LanguageFacts { + language: language.to_owned(), + has_coverage: false, + has_hazard_rules: false, + has_imports: true, + }], + ..CodeModel::default() + } +} + +#[test] +fn lcov_reads_documented_records_ignores_branch_and_function_records_and_merges_duplicates() { + let input = concat!( + "\u{feff}", + "TN:unit\r\n", + "SF:src/app.ts\r\n", + "FN:1,alpha\r\n", + "FNDA:2,alpha\r\n", + "FNF:1\r\n", + "FNH:1\r\n", + "BRDA:2,0,0,1\r\n", + "BRF:1\r\n", + "BRH:1\r\n", + "DA:1,0\r\n", + "DA:1,3,abcdef1234\r\n", + "DA:2,0\r\n", + "LF:2\r\n", + "LH:1\r\n", + "end_of_record\r\n", + "\r\n", + "SF:src/app.ts\r\n", + "DA:2,1\r\n", + "DA:3,0\r\n", + "end_of_record\r\n", + "SF:src/empty.ts\r\n", + "end_of_record\r\n", + ); + + let parsed = parse_lcov(input.as_bytes()).expect("valid LCOV"); + assert_eq!(parsed.format, CoverageFormat::Lcov); + assert!(parsed.source_roots.is_empty()); + assert_eq!(parsed.files.len(), 2); + + let app = &parsed.files[0]; + assert_eq!(app.path, "src/app.ts"); + assert_eq!(app.lines.get(&1), Some(&3)); + assert_eq!(app.lines.get(&2), Some(&1)); + assert_eq!(app.lines.get(&3), Some(&0)); + + let empty = &parsed.files[1]; + assert_eq!(empty.path, "src/empty.ts"); + assert!(empty.lines.is_empty()); +} + +#[test] +fn lcov_rejects_undocumented_records_and_invalid_data_with_first_offending_line() { + let unknown = "SF:src/app.ts\nDA:1,1\nUNKNOWN:value\nBOGUS:later\nend_of_record\n"; + let error = parse_lcov(unknown.as_bytes()).expect_err("unknown record must fail"); + assert_eq!( + error, + CoverageParseError::InvalidLcovRecord { + line: 3, + content: "UNKNOWN:value".to_owned(), + } + ); + + let da_outside = "DA:1,1\n"; + assert!(matches!( + parse_lcov(da_outside.as_bytes()), + Err(CoverageParseError::InvalidLcovData { line: 1, .. }) + )); + + let zero_line = "SF:src/app.ts\nDA:0,1\nend_of_record\n"; + assert!(matches!( + parse_lcov(zero_line.as_bytes()), + Err(CoverageParseError::InvalidLcovData { line: 2, .. }) + )); + + let negative_hits = "SF:src/app.ts\nDA:2,-1\nend_of_record\n"; + assert!(matches!( + parse_lcov(negative_hits.as_bytes()), + Err(CoverageParseError::InvalidLcovData { line: 2, .. }) + )); + + let too_many_fields = "SF:src/app.ts\nDA:2,1,sum,extra\nend_of_record\n"; + assert!(matches!( + parse_lcov(too_many_fields.as_bytes()), + Err(CoverageParseError::InvalidLcovData { line: 2, .. }) + )); +} + +#[test] +fn lcov_enforces_byte_size_limit() { + let input = b"SF:src/app.ts\nDA:1,1\nend_of_record\n"; + let error = parse_lcov_with_limits(input, 10).expect_err("oversized LCOV must fail"); + assert_eq!( + error, + CoverageParseError::ReportTooLarge { + size_bytes: input.len(), + max_bytes: 10, + } + ); +} + +#[test] +fn cobertura_reads_sources_classes_and_lines_ignores_methods_and_merges_duplicate_classes() { + let xml = concat!( + "\n", + "\n", + "\n", + " \n", + " /repo/packages/a & b\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "\n", + ); + + let parsed = parse_cobertura(xml.as_bytes()).expect("valid Cobertura XML"); + assert_eq!(parsed.format, CoverageFormat::Cobertura); + assert_eq!( + parsed.source_roots, + vec![ + "/repo/packages/a & b".to_owned(), + "/repo/packages/c".to_owned() + ] + ); + assert_eq!(parsed.files.len(), 2); + assert_eq!(parsed.files[0].path, "src/empty.php"); + assert!(parsed.files[0].lines.is_empty()); + + let worker = &parsed.files[1]; + assert_eq!(worker.path, "src/worker.php"); + assert_eq!(worker.lines.get(&5), Some(&1)); + assert_eq!(worker.lines.get(&6), Some(&2)); + assert_eq!(worker.lines.get(&7), Some(&0)); + assert!(!worker.lines.contains_key(&99)); +} + +#[test] +fn cobertura_decodes_predefined_and_numeric_entities_in_attributes_and_sources() { + let xml = concat!( + "", + "/dir/<a>"'AB", + "", + "", + "", + "", + ); + let parsed = parse_cobertura(xml.as_bytes()).expect("valid entities"); + assert_eq!(parsed.source_roots, vec!["/dir/\"'AB".to_owned()]); + assert_eq!(parsed.files[0].path, "src/file-1.py"); +} + +#[test] +fn cobertura_rejects_broken_xml() { + let cases = [ + "", + "", + "", + "", + "", + "", + "", + "