Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / infra / agents / agentd / src / parsers.rs
parsers.rs1348 lines · 48.5 KiBRaw
| 1 | #![allow(dead_code)] |
| 2 | //! Parsers for build/test output. |
| 3 | //! |
| 4 | //! The harness runs `./gradlew ...` / `./check <module>` in a sandbox and |
| 5 | //! must return compact structured results to the model. This module turns raw |
| 6 | //! stdout/stderr into [`BuildSummary`] / [`TestSummary`] and renders both in |
| 7 | //! a compact model-friendly form (see [`render_build_for_model`] and |
| 8 | //! [`render_tests_for_model`]). |
| 9 | //! |
| 10 | //! Supported inputs (see `src/testdata/parsers/` for real captured samples): |
| 11 | //! - Kotlin compiler `e:` / `w:` lines and detekt console findings (same shape |
| 12 | //! plus a trailing `[RuleId]`). |
| 13 | //! - javac `path:line: error: msg` lines. |
| 14 | //! - rustc/cargo `error[..]: msg` headers with a following ` --> path:line:col` |
| 15 | //! location, and `warning:` headers with locations. |
| 16 | //! - Gradle `> Task :x:y FAILED` lines and the `* What went wrong:` block. |
| 17 | //! - Android lint text output (`path:line: Error|Warning: msg [IssueId]`). |
| 18 | //! - The repo's custom `./check` wrapper echoes (module/task lines plus |
| 19 | //! `Warning: ... reported failures` footers). |
| 20 | |
| 21 | use std::collections::HashSet; |
| 22 | |
| 23 | // --------------------------------------------------------------------------- |
| 24 | // Diagnostics |
| 25 | // --------------------------------------------------------------------------- |
| 26 | |
| 27 | /// Severity of a single diagnostic. |
| 28 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 29 | pub enum Severity { |
| 30 | Error, |
| 31 | Warning, |
| 32 | } |
| 33 | |
| 34 | /// Tool that produced a diagnostic. |
| 35 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 36 | pub enum Tool { |
| 37 | Kotlin, |
| 38 | Java, |
| 39 | Rust, |
| 40 | Gradle, |
| 41 | Detekt, |
| 42 | Lint, |
| 43 | Other, |
| 44 | } |
| 45 | |
| 46 | /// A single compiler / linter / task diagnostic. |
| 47 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 48 | pub struct Diagnostic { |
| 49 | /// Error or warning. |
| 50 | pub severity: Severity, |
| 51 | /// Tool that produced this diagnostic. |
| 52 | pub tool: Tool, |
| 53 | /// Repo-relative path when one could be recovered, else `None`. |
| 54 | pub file: Option<String>, |
| 55 | /// 1-based line number, when known. |
| 56 | pub line: Option<u32>, |
| 57 | /// 1-based column number, when known. |
| 58 | pub col: Option<u32>, |
| 59 | /// Human-readable message. |
| 60 | pub message: String, |
| 61 | /// Machine-readable code (`E0308`, `MagicNumber`, `ToastUsage`, ...). |
| 62 | pub code: Option<String>, |
| 63 | } |
| 64 | |
| 65 | /// Summary of one `./gradlew ...` / `./check ...` invocation. |
| 66 | #[derive(Debug, Clone)] |
| 67 | pub struct BuildSummary { |
| 68 | /// True when the invocation succeeded (exit code 0 and no `FAILED` task). |
| 69 | pub success: bool, |
| 70 | /// Gradle task paths that reported `FAILED`, in encounter order. |
| 71 | pub failed_tasks: Vec<String>, |
| 72 | /// Text of the `* What went wrong:` block, when present. |
| 73 | pub what_went_wrong: Option<String>, |
| 74 | /// Deduplicated diagnostics, errors before warnings, capped. |
| 75 | pub diagnostics: Vec<Diagnostic>, |
| 76 | /// Last ~60 lines of combined output. |
| 77 | pub log_tail: String, |
| 78 | } |
| 79 | |
| 80 | /// Maximum diagnostics kept on a [`BuildSummary`]. |
| 81 | pub const MAX_DIAGNOSTICS: usize = 50; |
| 82 | /// Maximum failures kept on a [`TestSummary`]. |
| 83 | pub const MAX_FAILURES: usize = 20; |
| 84 | /// Lines of combined output kept in [`BuildSummary::log_tail`]. |
| 85 | pub const LOG_TAIL_LINES: usize = 60; |
| 86 | /// Lines of a test trace kept in [`TestFailure::trace`]. |
| 87 | pub const TRACE_LINES: usize = 15; |
| 88 | /// Rendering budget for [`render_build_for_model`] / [`render_tests_for_model`]. |
| 89 | pub const RENDER_BUDGET_BYTES: usize = 6 * 1024; |
| 90 | |
| 91 | // --------------------------------------------------------------------------- |
| 92 | // Path handling |
| 93 | // --------------------------------------------------------------------------- |
| 94 | |
| 95 | /// Strip everything up to and including a `/builds/slots/slot-N/` marker or |
| 96 | /// the given repo-root prefix, so absolute sandbox paths become repo-relative. |
| 97 | /// |
| 98 | /// Returns `None` when `path` is empty; otherwise returns the relativized |
| 99 | /// path (or the original when neither marker matches). |
| 100 | pub fn relativize(path: &str, repo_root: &str) -> Option<String> { |
| 101 | let path = path.trim(); |
| 102 | if path.is_empty() { |
| 103 | return None; |
| 104 | } |
| 105 | // Sandbox slot marker: /builds/slots/slot-3/<repo-path...>. |
| 106 | if let Some(idx) = path.find("/builds/slots/slot-") { |
| 107 | let rest = &path[idx + "/builds/slots/".len()..]; |
| 108 | if let Some(slash) = rest.find('/') { |
| 109 | let rel = rest[slash + 1..].trim_start_matches('/'); |
| 110 | if !rel.is_empty() { |
| 111 | return Some(rel.to_string()); |
| 112 | } |
| 113 | } |
| 114 | } |
| 115 | let root = repo_root.trim_end_matches('/'); |
| 116 | if !root.is_empty() { |
| 117 | if let Some(stripped) = path.strip_prefix(root) { |
| 118 | let rel = stripped.trim_start_matches('/'); |
| 119 | if !rel.is_empty() { |
| 120 | return Some(rel.to_string()); |
| 121 | } |
| 122 | } |
| 123 | // `file://` URIs embed the absolute path; compare without the scheme. |
| 124 | if let Some(without_scheme) = path.strip_prefix("file://") { |
| 125 | if let Some(stripped) = without_scheme.strip_prefix(root) { |
| 126 | let rel = stripped.trim_start_matches('/'); |
| 127 | if !rel.is_empty() { |
| 128 | return Some(rel.to_string()); |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | Some(path.to_string()) |
| 134 | } |
| 135 | |
| 136 | /// Split `path:line:col` / `path:line` suffixes off a location string. |
| 137 | /// |
| 138 | /// Returns the path part plus optional line/column. Only trailing numeric |
| 139 | /// components are consumed, so Windows drive prefixes and ports are safe. |
| 140 | fn split_location(s: &str) -> (&str, Option<u32>, Option<u32>) { |
| 141 | let s = s.trim(); |
| 142 | let mut parts: Vec<&str> = s.rsplitn(3, ':').collect(); |
| 143 | // rsplitn yields tail-first; reverse for head-first handling below. |
| 144 | parts.reverse(); |
| 145 | match parts.as_slice() { |
| 146 | [path, line, col] => { |
| 147 | if let (Ok(line), Ok(col)) = (line.parse::<u32>(), col.parse::<u32>()) { |
| 148 | return (path, Some(line), Some(col)); |
| 149 | } |
| 150 | if let Ok(line) = line.parse::<u32>() { |
| 151 | // `path:line:non-numeric` — keep col absent, path keeps suffix. |
| 152 | let path = &s[..s.len() - col.len() - 1]; |
| 153 | return (path, Some(line), None); |
| 154 | } |
| 155 | (s, None, None) |
| 156 | } |
| 157 | [path, line] => { |
| 158 | if let Ok(line) = line.parse::<u32>() { |
| 159 | return (path, Some(line), None); |
| 160 | } |
| 161 | (s, None, None) |
| 162 | } |
| 163 | _ => (s, None, None), |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | fn parse_u32(s: &str) -> Option<u32> { |
| 168 | s.trim().parse::<u32>().ok() |
| 169 | } |
| 170 | |
| 171 | // --------------------------------------------------------------------------- |
| 172 | // Build output parsing |
| 173 | // --------------------------------------------------------------------------- |
| 174 | |
| 175 | /// Parse one Gradle/Kotlin/Java/Rust/detekt/lint/`check` invocation. |
| 176 | /// |
| 177 | /// `stdout` and `stderr` are the captured streams, `exit_code` the process |
| 178 | /// exit code (`None` when unknown, e.g. killed), and `repo_root` the repo |
| 179 | /// checkout prefix used to relativize absolute file paths. |
| 180 | pub fn parse_build_output( |
| 181 | stdout: &str, |
| 182 | stderr: &str, |
| 183 | exit_code: Option<i32>, |
| 184 | repo_root: &str, |
| 185 | ) -> BuildSummary { |
| 186 | let mut failed_tasks: Vec<String> = Vec::new(); |
| 187 | let mut diagnostics: Vec<Diagnostic> = Vec::new(); |
| 188 | |
| 189 | let combined = format!("{stdout}\n{stderr}"); |
| 190 | let lines: Vec<&str> = combined.lines().collect(); |
| 191 | |
| 192 | // Pass 1: line-oriented diagnostics (kotlinc/detekt, javac, lint, rustc |
| 193 | // headers) plus `> Task ... FAILED` markers. |
| 194 | let mut i = 0; |
| 195 | while i < lines.len() { |
| 196 | let line = lines[i]; |
| 197 | let trimmed = line.trim(); |
| 198 | if let Some(task) = parse_failed_task(trimmed) { |
| 199 | if !failed_tasks.contains(&task) { |
| 200 | failed_tasks.push(task); |
| 201 | } |
| 202 | } else if let Some(d) = parse_kotlin_or_detekt(trimmed, repo_root) { |
| 203 | diagnostics.push(d); |
| 204 | } else if let Some(d) = parse_javac(trimmed, repo_root) { |
| 205 | diagnostics.push(d); |
| 206 | } else if let Some(d) = parse_lint_text(trimmed, repo_root) { |
| 207 | diagnostics.push(d); |
| 208 | } else if let Some((severity, code, message)) = parse_rustc_header(trimmed) { |
| 209 | // rustc location follows on a ` --> path:line:col` line; scan a |
| 210 | // few lines ahead so multi-line headers still attach. |
| 211 | let mut location: Option<(String, Option<u32>, Option<u32>)> = None; |
| 212 | for ahead in lines.iter().skip(i + 1).take(6) { |
| 213 | let t = ahead.trim(); |
| 214 | if let Some(rest) = t.strip_prefix("--> ") { |
| 215 | let (path, line_no, col) = split_location(rest); |
| 216 | location = Some((path.to_string(), line_no, col)); |
| 217 | break; |
| 218 | } |
| 219 | // A new diagnostic header ends the search. |
| 220 | if parse_rustc_header(t).is_some() |
| 221 | || parse_kotlin_or_detekt(t, "").is_some() |
| 222 | || t.starts_with("error: could not compile") |
| 223 | { |
| 224 | break; |
| 225 | } |
| 226 | } |
| 227 | let (file, line_no, col) = match location { |
| 228 | Some((p, l, c)) => (relativize(&p, repo_root), l, c), |
| 229 | None => (None, None, None), |
| 230 | }; |
| 231 | diagnostics.push(Diagnostic { |
| 232 | severity, |
| 233 | tool: Tool::Rust, |
| 234 | file, |
| 235 | line: line_no, |
| 236 | col, |
| 237 | message, |
| 238 | code, |
| 239 | }); |
| 240 | } else if trimmed.starts_with("error: could not compile") { |
| 241 | diagnostics.push(Diagnostic { |
| 242 | severity: Severity::Error, |
| 243 | tool: Tool::Rust, |
| 244 | file: None, |
| 245 | line: None, |
| 246 | col: None, |
| 247 | message: trimmed.to_string(), |
| 248 | code: None, |
| 249 | }); |
| 250 | } |
| 251 | i += 1; |
| 252 | } |
| 253 | |
| 254 | // Pass 2: the `* What went wrong:` block (ends at `* Try:` or blank-adjacent header). |
| 255 | let what_went_wrong = extract_what_went_wrong(&lines); |
| 256 | |
| 257 | // Success: exit code 0 (or unknown-but-no-failure-signal) with no FAILED task. |
| 258 | let mut success = failed_tasks.is_empty() && what_went_wrong.is_none(); |
| 259 | if let Some(code) = exit_code { |
| 260 | success = code == 0 && failed_tasks.is_empty(); |
| 261 | } |
| 262 | |
| 263 | // If the build failed but no diagnostic was recovered, surface the |
| 264 | // `* What went wrong:` text (or the tail) as a Gradle diagnostic so the |
| 265 | // model still gets something actionable. |
| 266 | if !success && diagnostics.is_empty() { |
| 267 | if let Some(block) = what_went_wrong.clone() { |
| 268 | let first = block.lines().next().unwrap_or(&block).trim().to_string(); |
| 269 | if !first.is_empty() { |
| 270 | diagnostics.push(Diagnostic { |
| 271 | severity: Severity::Error, |
| 272 | tool: Tool::Gradle, |
| 273 | file: None, |
| 274 | line: None, |
| 275 | col: None, |
| 276 | message: first, |
| 277 | code: None, |
| 278 | }); |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | diagnostics = dedup_sort_cap(diagnostics); |
| 284 | |
| 285 | let tail: Vec<&str> = combined.lines().rev().take(LOG_TAIL_LINES).collect(); |
| 286 | let tail: Vec<&str> = tail.into_iter().rev().collect(); |
| 287 | let log_tail = tail.join("\n"); |
| 288 | |
| 289 | BuildSummary { |
| 290 | success, |
| 291 | failed_tasks, |
| 292 | what_went_wrong, |
| 293 | diagnostics, |
| 294 | log_tail, |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | /// `> Task :calculator:compileDevKotlin FAILED` -> `Some(":calculator:compileDevKotlin")`. |
| 299 | fn parse_failed_task(trimmed: &str) -> Option<String> { |
| 300 | let rest = trimmed.strip_prefix("> Task ")?; |
| 301 | let task = rest.strip_suffix(" FAILED")?; |
| 302 | if task.is_empty() || task.contains(' ') { |
| 303 | return None; |
| 304 | } |
| 305 | Some(task.to_string()) |
| 306 | } |
| 307 | |
| 308 | /// kotlinc (`e:`/`w:`) and detekt console lines. |
| 309 | /// |
| 310 | /// kotlinc: `e: file:///abs/File.kt:12:5 message` |
| 311 | /// detekt: `w: /abs/File.kt:27:5 message. [RuleId]` |
| 312 | fn parse_kotlin_or_detekt(trimmed: &str, repo_root: &str) -> Option<Diagnostic> { |
| 313 | let (severity, rest) = if let Some(rest) = trimmed.strip_prefix("e: ") { |
| 314 | (Severity::Error, rest) |
| 315 | } else if let Some(rest) = trimmed.strip_prefix("w: ") { |
| 316 | (Severity::Warning, rest) |
| 317 | } else { |
| 318 | return None; |
| 319 | }; |
| 320 | // detekt appends ` [RuleId]`; kotlinc messages never end with that shape |
| 321 | // (bracketed single token, no spaces) — treat it as the code. |
| 322 | let (rest, detekt_code) = match rest.rfind(" [") { |
| 323 | Some(idx) if rest.ends_with(']') => { |
| 324 | let candidate = &rest[idx + 2..rest.len() - 1]; |
| 325 | if !candidate.is_empty() && !candidate.contains([' ', '\t', ':']) { |
| 326 | (rest[..idx].trim_end(), Some(candidate.to_string())) |
| 327 | } else { |
| 328 | (rest, None) |
| 329 | } |
| 330 | } |
| 331 | _ => (rest, None), |
| 332 | }; |
| 333 | // Location is `path:line:col message...`; the path itself may contain |
| 334 | // colons (URI scheme), so scan for the first `:line:col ` numeric pair. |
| 335 | let (path, line_no, col, message) = split_prefixed_location(rest)?; |
| 336 | let tool = if detekt_code.is_some() { |
| 337 | Tool::Detekt |
| 338 | } else { |
| 339 | Tool::Kotlin |
| 340 | }; |
| 341 | Some(Diagnostic { |
| 342 | severity, |
| 343 | tool, |
| 344 | file: relativize(path, repo_root), |
| 345 | line: line_no, |
| 346 | col, |
| 347 | message: message.to_string(), |
| 348 | code: detekt_code, |
| 349 | }) |
| 350 | } |
| 351 | |
| 352 | /// Scan `path:line:col message` / `path:line message` where path may contain |
| 353 | /// colons (e.g. `file:///...`). Returns path, line, col, message. |
| 354 | fn split_prefixed_location(s: &str) -> Option<(&str, Option<u32>, Option<u32>, &str)> { |
| 355 | // Try line+col first, then line only; the message follows a space. |
| 356 | let bytes = s.as_bytes(); |
| 357 | let mut colon_positions: Vec<usize> = Vec::new(); |
| 358 | for (idx, b) in bytes.iter().enumerate() { |
| 359 | if *b == b':' { |
| 360 | colon_positions.push(idx); |
| 361 | } |
| 362 | } |
| 363 | for &first in &colon_positions { |
| 364 | let after_first = &s[first + 1..]; |
| 365 | // line digits up to next colon or space. |
| 366 | let mut line_end = after_first.len(); |
| 367 | for (idx, b) in after_first.bytes().enumerate() { |
| 368 | if !b.is_ascii_digit() { |
| 369 | line_end = idx; |
| 370 | break; |
| 371 | } |
| 372 | } |
| 373 | if line_end == 0 { |
| 374 | continue; |
| 375 | } |
| 376 | let line_no = parse_u32(&after_first[..line_end])?; |
| 377 | let rest = &after_first[line_end..]; |
| 378 | if let Some(after_colon) = rest.strip_prefix(':') { |
| 379 | let mut col_end = after_colon.len(); |
| 380 | for (idx, b) in after_colon.bytes().enumerate() { |
| 381 | if !b.is_ascii_digit() { |
| 382 | col_end = idx; |
| 383 | break; |
| 384 | } |
| 385 | } |
| 386 | if col_end > 0 && after_colon[col_end..].starts_with(' ') { |
| 387 | let col = parse_u32(&after_colon[..col_end])?; |
| 388 | let message = after_colon[col_end..].trim_start(); |
| 389 | if message.is_empty() { |
| 390 | continue; |
| 391 | } |
| 392 | return Some((s[..first].trim(), Some(line_no), Some(col), message)); |
| 393 | } |
| 394 | } |
| 395 | if rest.starts_with(' ') { |
| 396 | let message = rest.trim_start(); |
| 397 | if message.is_empty() { |
| 398 | continue; |
| 399 | } |
| 400 | return Some((s[..first].trim(), Some(line_no), None, message)); |
| 401 | } |
| 402 | } |
| 403 | None |
| 404 | } |
| 405 | |
| 406 | /// javac: `/abs/File.java:12: error: message` (also `warning:`). |
| 407 | fn parse_javac(trimmed: &str, repo_root: &str) -> Option<Diagnostic> { |
| 408 | // Find `: error: ` / `: warning: ` separator; the head must end with a line number. |
| 409 | for marker in [": error: ", ": warning: "] { |
| 410 | if let Some(idx) = trimmed.find(marker) { |
| 411 | let (head, message) = trimmed.split_at(idx); |
| 412 | let message = message[marker.len() - 1..].trim_start_matches(": ").trim(); |
| 413 | let severity = if marker.contains("error") { |
| 414 | Severity::Error |
| 415 | } else { |
| 416 | Severity::Warning |
| 417 | }; |
| 418 | // Head is `path:line` possibly with `path:line:col`? javac prints |
| 419 | // `path:line: error:` — head ends `:line`. |
| 420 | if let Some(colon) = head.rfind(':') { |
| 421 | let (path, line_s) = head.split_at(colon); |
| 422 | if let Some(line_no) = parse_u32(&line_s[1..]) { |
| 423 | return Some(Diagnostic { |
| 424 | severity, |
| 425 | tool: Tool::Java, |
| 426 | file: relativize(path.trim(), repo_root), |
| 427 | line: Some(line_no), |
| 428 | col: None, |
| 429 | message: message.to_string(), |
| 430 | code: None, |
| 431 | }); |
| 432 | } |
| 433 | } |
| 434 | } |
| 435 | } |
| 436 | None |
| 437 | } |
| 438 | |
| 439 | /// Android lint text output: `path:line: Error: msg [IssueId]` |
| 440 | /// (also `Warning:`, optional `:col`, optional `[Id]`, optional |
| 441 | /// ` from vendor` suffix on the id). |
| 442 | fn parse_lint_text(trimmed: &str, repo_root: &str) -> Option<Diagnostic> { |
| 443 | for marker in [": Error: ", ": Warning: "] { |
| 444 | if let Some(idx) = trimmed.find(marker) { |
| 445 | let (head, message) = trimmed.split_at(idx); |
| 446 | let mut message = message[marker.len() - 1..].trim_start_matches(": ").trim(); |
| 447 | let severity = if marker.contains("Error") { |
| 448 | Severity::Error |
| 449 | } else { |
| 450 | Severity::Warning |
| 451 | }; |
| 452 | // Trailing `[IssueId]` or `[IssueId from vendor]`. |
| 453 | let mut code: Option<String> = None; |
| 454 | if message.ends_with(']') { |
| 455 | if let Some(open) = message.rfind(" [") { |
| 456 | let id_part = &message[open + 2..message.len() - 1]; |
| 457 | let id = id_part.split_whitespace().next().unwrap_or(""); |
| 458 | if !id.is_empty() && !id.contains(':') { |
| 459 | code = Some(id.to_string()); |
| 460 | } |
| 461 | message = message[..open].trim_end(); |
| 462 | } |
| 463 | } |
| 464 | let (path, line_no, col) = split_location(head); |
| 465 | if line_no.is_none() { |
| 466 | continue; |
| 467 | } |
| 468 | // Guard: lint lines are bare paths, not `e:`/`w:` prefixed and not |
| 469 | // rustc headers — callers try lint after those, so just check the |
| 470 | // head looks like a file path. |
| 471 | if path.is_empty() || path.contains("://") && !path.starts_with('/') && !path.starts_with("file:") { |
| 472 | return None; |
| 473 | } |
| 474 | return Some(Diagnostic { |
| 475 | severity, |
| 476 | tool: Tool::Lint, |
| 477 | file: relativize(path, repo_root), |
| 478 | line: line_no, |
| 479 | col, |
| 480 | message: message.to_string(), |
| 481 | code, |
| 482 | }); |
| 483 | } |
| 484 | } |
| 485 | None |
| 486 | } |
| 487 | |
| 488 | /// rustc/cargo header: `error[E0308]: msg`, `error: msg`, `warning: msg`. |
| 489 | /// Returns severity, optional code, message. |
| 490 | fn parse_rustc_header(trimmed: &str) -> Option<(Severity, Option<String>, String)> { |
| 491 | let (severity, rest) = if let Some(rest) = trimmed.strip_prefix("error") { |
| 492 | (Severity::Error, rest) |
| 493 | } else if let Some(rest) = trimmed.strip_prefix("warning") { |
| 494 | (Severity::Warning, rest) |
| 495 | } else { |
| 496 | return None; |
| 497 | }; |
| 498 | // rustc emits both `error: msg` and `error[E0308]: msg`; reject words |
| 499 | // like `errorLine1=`. |
| 500 | let (e_code, rest) = if let Some(after_bracket) = rest.strip_prefix('[') { |
| 501 | // `error[E0308]: msg` — skip to the closing bracket, require `:` after. |
| 502 | let end = after_bracket.find(']')?; |
| 503 | let code = after_bracket[..end].trim().to_string(); |
| 504 | let tail = after_bracket[end + 1..].strip_prefix(':')?; |
| 505 | let code = if code.is_empty() { None } else { Some(code) }; |
| 506 | (code, tail) |
| 507 | } else { |
| 508 | (None, rest.strip_prefix(':')?) |
| 509 | }; |
| 510 | let rest = rest.trim_start(); |
| 511 | // Optional `[unused_imports]`-style code prefix (E-codes consumed above). |
| 512 | let (code, message) = if let Some(after_bracket) = rest.strip_prefix('[') { |
| 513 | if let Some(end) = after_bracket.find(']') { |
| 514 | let code = after_bracket[..end].trim(); |
| 515 | let msg = after_bracket[end + 1..].trim_start_matches(':').trim(); |
| 516 | let code = if code.is_empty() { |
| 517 | None |
| 518 | } else { |
| 519 | Some(code.to_string()) |
| 520 | }; |
| 521 | (code, msg.to_string()) |
| 522 | } else { |
| 523 | (None, rest.to_string()) |
| 524 | } |
| 525 | } else { |
| 526 | (None, rest.to_string()) |
| 527 | }; |
| 528 | let code = e_code.or(code); |
| 529 | if message.is_empty() { |
| 530 | return None; |
| 531 | } |
| 532 | Some((severity, code, message)) |
| 533 | } |
| 534 | |
| 535 | /// Extract the `* What went wrong:` block (up to `* Try:` or the next |
| 536 | /// `* `-header / blank-line-then-header). |
| 537 | fn extract_what_went_wrong(lines: &[&str]) -> Option<String> { |
| 538 | let start = lines |
| 539 | .iter() |
| 540 | .position(|l| l.trim() == "* What went wrong:")?; |
| 541 | let mut block: Vec<&str> = Vec::new(); |
| 542 | for line in lines.iter().skip(start + 1) { |
| 543 | let trimmed = line.trim(); |
| 544 | if trimmed == "* Try:" { |
| 545 | break; |
| 546 | } |
| 547 | // A new `* Header:` ends the block (but `> ...` detail lines belong). |
| 548 | if trimmed.starts_with("* ") && trimmed.ends_with(':') { |
| 549 | break; |
| 550 | } |
| 551 | block.push(line); |
| 552 | } |
| 553 | // Trim leading/trailing blank lines. |
| 554 | while block.first().is_some_and(|l| l.trim().is_empty()) { |
| 555 | block.remove(0); |
| 556 | } |
| 557 | while block.last().is_some_and(|l| l.trim().is_empty()) { |
| 558 | block.pop(); |
| 559 | } |
| 560 | // De-indent the common `> ` / two-space Gradle continuation prefix. |
| 561 | let cleaned: Vec<String> = block |
| 562 | .iter() |
| 563 | .map(|l| { |
| 564 | let t = l.trim_start(); |
| 565 | t.strip_prefix("> ").unwrap_or(t).to_string() |
| 566 | }) |
| 567 | .collect(); |
| 568 | let text = cleaned.join("\n").trim().to_string(); |
| 569 | if text.is_empty() { |
| 570 | None |
| 571 | } else { |
| 572 | Some(text) |
| 573 | } |
| 574 | } |
| 575 | |
| 576 | /// Dedup (exact), errors before warnings, stable, capped at [`MAX_DIAGNOSTICS`]. |
| 577 | fn dedup_sort_cap(mut diagnostics: Vec<Diagnostic>) -> Vec<Diagnostic> { |
| 578 | let mut seen: HashSet<Diagnostic> = HashSet::new(); |
| 579 | diagnostics.retain(|d| seen.insert(d.clone())); |
| 580 | diagnostics.sort_by_key(|d| match d.severity { |
| 581 | Severity::Error => 0, |
| 582 | Severity::Warning => 1, |
| 583 | }); |
| 584 | diagnostics.truncate(MAX_DIAGNOSTICS); |
| 585 | diagnostics |
| 586 | } |
| 587 | |
| 588 | // --------------------------------------------------------------------------- |
| 589 | // JUnit XML |
| 590 | // --------------------------------------------------------------------------- |
| 591 | |
| 592 | /// A single failed or errored test case. |
| 593 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 594 | pub struct TestFailure { |
| 595 | /// Fully-qualified class name. |
| 596 | pub class: String, |
| 597 | /// Test method name. |
| 598 | pub name: String, |
| 599 | /// Short failure message (`message` attribute or first line). |
| 600 | pub message: String, |
| 601 | /// First ~15 lines of the stack trace / failure body. |
| 602 | pub trace: String, |
| 603 | } |
| 604 | |
| 605 | /// Summary across one or more JUnit XML reports. |
| 606 | #[derive(Debug, Clone, Default)] |
| 607 | pub struct TestSummary { |
| 608 | /// Passed test cases. |
| 609 | pub passed: u32, |
| 610 | /// Failed test cases (`<failure>`). |
| 611 | pub failed: u32, |
| 612 | /// Skipped test cases. |
| 613 | pub skipped: u32, |
| 614 | /// Errored test cases (`<error>`). |
| 615 | pub errors: u32, |
| 616 | /// Failure details, capped at [`MAX_FAILURES`]. |
| 617 | pub failures: Vec<TestFailure>, |
| 618 | } |
| 619 | |
| 620 | /// Parse one JUnit XML report (Gradle `TEST-*.xml` shape). |
| 621 | /// |
| 622 | /// Hand-rolled attribute scanner over `testsuite` / `testcase` / `failure` / |
| 623 | /// `error` / `skipped` tags — no XML dependency, tolerant of entity escapes |
| 624 | /// (`<` etc.) and CDATA-ish bodies. Returns `Err` with a message when the |
| 625 | /// document has no parseable `testsuite`. |
| 626 | pub fn parse_junit_xml(xml: &str) -> Result<TestSummary, String> { |
| 627 | let mut summary = TestSummary::default(); |
| 628 | |
| 629 | if find_open_tag(xml, "testsuite").is_none() { |
| 630 | return Err("no <testsuite> element found".to_string()); |
| 631 | } |
| 632 | |
| 633 | let mut rest = xml; |
| 634 | // Walk each <testcase ...>...</testcase> or self-closed <testcase .../>. |
| 635 | while let Some(case_start) = rest.find("<testcase") { |
| 636 | let after = &rest[case_start..]; |
| 637 | let tag_end = after.find('>').ok_or("malformed <testcase> tag")?; |
| 638 | let open_tag = &after[..tag_end]; |
| 639 | let self_closed = open_tag.trim_end().ends_with('/'); |
| 640 | let attrs = parse_attrs(open_tag); |
| 641 | let name = attrs.get("name").cloned().unwrap_or_default(); |
| 642 | let class = attrs |
| 643 | .get("classname") |
| 644 | .cloned() |
| 645 | .or_else(|| attrs.get("class").cloned()) |
| 646 | .unwrap_or_default(); |
| 647 | |
| 648 | let (body, consumed) = if self_closed { |
| 649 | ("", tag_end + 1) |
| 650 | } else if let Some(close) = after.find("</testcase>") { |
| 651 | (&after[tag_end + 1..close], close + "</testcase>".len()) |
| 652 | } else { |
| 653 | return Err(format!("unclosed <testcase> for {name:?}")); |
| 654 | }; |
| 655 | |
| 656 | if body.contains("<skipped") { |
| 657 | summary.skipped += 1; |
| 658 | } else if let Some((kind, failure)) = parse_failure_body(body, &class, &name) { |
| 659 | match kind { |
| 660 | FailureKind::Failure => summary.failed += 1, |
| 661 | FailureKind::Error => summary.errors += 1, |
| 662 | } |
| 663 | if summary.failures.len() < MAX_FAILURES { |
| 664 | summary.failures.push(failure); |
| 665 | } |
| 666 | } else { |
| 667 | summary.passed += 1; |
| 668 | } |
| 669 | rest = &after[consumed..]; |
| 670 | } |
| 671 | |
| 672 | // Adopt suite-level totals when the report enumerates no cases but |
| 673 | // carries counters (e.g. aggregated reports). |
| 674 | if summary.passed + summary.failed + summary.skipped + summary.errors == 0 { |
| 675 | if let Some(tag) = find_open_tag(xml, "testsuite") { |
| 676 | let attrs = parse_attrs(&tag); |
| 677 | let tests = attrs.get("tests").and_then(|s| s.parse::<u32>().ok()); |
| 678 | let failures = attrs.get("failures").and_then(|s| s.parse::<u32>().ok()); |
| 679 | let errors = attrs.get("errors").and_then(|s| s.parse::<u32>().ok()); |
| 680 | let skipped = attrs.get("skipped").and_then(|s| s.parse::<u32>().ok()); |
| 681 | if tests.is_some() || failures.is_some() || errors.is_some() || skipped.is_some() { |
| 682 | summary.failed = failures.unwrap_or(0); |
| 683 | summary.errors = errors.unwrap_or(0); |
| 684 | summary.skipped = skipped.unwrap_or(0); |
| 685 | summary.passed = tests |
| 686 | .unwrap_or(0) |
| 687 | .saturating_sub(summary.failed + summary.errors + summary.skipped); |
| 688 | } |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | Ok(summary) |
| 693 | } |
| 694 | |
| 695 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 696 | enum FailureKind { |
| 697 | Failure, |
| 698 | Error, |
| 699 | } |
| 700 | |
| 701 | /// Extract `<failure>` / `<error>` from a testcase body. |
| 702 | fn parse_failure_body(body: &str, class: &str, name: &str) -> Option<(FailureKind, TestFailure)> { |
| 703 | for (tag, kind) in [("failure", FailureKind::Failure), ("error", FailureKind::Error)] { |
| 704 | if let Some(start) = body.find(&format!("<{tag}")) { |
| 705 | let after = &body[start..]; |
| 706 | let tag_end = after.find('>')?; |
| 707 | let open_tag = &after[..tag_end]; |
| 708 | let self_closed = open_tag.trim_end().ends_with('/'); |
| 709 | let attrs = parse_attrs(open_tag); |
| 710 | let close_tag = format!("</{tag}>"); |
| 711 | let inner = if self_closed { |
| 712 | String::new() |
| 713 | } else if let Some(close) = after.find(&close_tag) { |
| 714 | after[tag_end + 1..close].to_string() |
| 715 | } else { |
| 716 | String::new() |
| 717 | }; |
| 718 | let inner = xml_unescape(&inner); |
| 719 | let message = attrs |
| 720 | .get("message") |
| 721 | .map(|m| xml_unescape(m)) |
| 722 | .filter(|m| !m.trim().is_empty()) |
| 723 | .unwrap_or_else(|| inner.lines().next().unwrap_or("").trim().to_string()); |
| 724 | let trace: Vec<&str> = inner.lines().take(TRACE_LINES).collect(); |
| 725 | return Some(( |
| 726 | kind, |
| 727 | TestFailure { |
| 728 | class: class.to_string(), |
| 729 | name: name.to_string(), |
| 730 | message, |
| 731 | trace: trace.join("\n"), |
| 732 | }, |
| 733 | )); |
| 734 | } |
| 735 | } |
| 736 | None |
| 737 | } |
| 738 | |
| 739 | /// Merge several [`TestSummary`] values (one per XML file) into one. |
| 740 | /// Counters add up; failure lists concatenate, capped at [`MAX_FAILURES`]. |
| 741 | pub fn merge_test_summaries(summaries: &[TestSummary]) -> TestSummary { |
| 742 | let mut merged = TestSummary::default(); |
| 743 | for s in summaries { |
| 744 | merged.passed += s.passed; |
| 745 | merged.failed += s.failed; |
| 746 | merged.skipped += s.skipped; |
| 747 | merged.errors += s.errors; |
| 748 | for f in &s.failures { |
| 749 | if merged.failures.len() >= MAX_FAILURES { |
| 750 | break; |
| 751 | } |
| 752 | merged.failures.push(f.clone()); |
| 753 | } |
| 754 | } |
| 755 | merged |
| 756 | } |
| 757 | |
| 758 | // --- minimal XML helpers (attribute/tag scanning, entity unescaping) --- |
| 759 | |
| 760 | /// Find the first opening `<name ...>` tag text (without closing `>`). |
| 761 | fn find_open_tag(xml: &str, name: &str) -> Option<String> { |
| 762 | let open = format!("<{name}"); |
| 763 | let start = xml.find(&open)?; |
| 764 | let after = &xml[start..]; |
| 765 | // Reject `<testsuites>` when looking for `<testsuite`. |
| 766 | let next = after[open.len()..].chars().next()?; |
| 767 | if !(next == ' ' || next == '\t' || next == '\n' || next == '\r' || next == '/' || next == '>') |
| 768 | { |
| 769 | // Search past this false hit. |
| 770 | return find_open_tag(&after[open.len()..], name); |
| 771 | } |
| 772 | let end = after.find('>')?; |
| 773 | Some(after[..end].to_string()) |
| 774 | } |
| 775 | |
| 776 | /// Parse `key="value"` (double or single quotes) pairs from a tag string. |
| 777 | fn parse_attrs(tag: &str) -> std::collections::HashMap<String, String> { |
| 778 | let mut attrs = std::collections::HashMap::new(); |
| 779 | let bytes = tag.as_bytes(); |
| 780 | let mut i = 0; |
| 781 | while i < bytes.len() { |
| 782 | // Skip to attribute name start. |
| 783 | while i < bytes.len() && !(bytes[i].is_ascii_alphabetic() || bytes[i] == b'_') { |
| 784 | i += 1; |
| 785 | } |
| 786 | let name_start = i; |
| 787 | while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_' || bytes[i] == b'-' || bytes[i] == b':' || bytes[i] == b'.') { |
| 788 | i += 1; |
| 789 | } |
| 790 | if i == name_start { |
| 791 | break; |
| 792 | } |
| 793 | let name = &tag[name_start..i]; |
| 794 | while i < bytes.len() && bytes[i].is_ascii_whitespace() { |
| 795 | i += 1; |
| 796 | } |
| 797 | if i >= bytes.len() || bytes[i] != b'=' { |
| 798 | continue; |
| 799 | } |
| 800 | i += 1; |
| 801 | while i < bytes.len() && bytes[i].is_ascii_whitespace() { |
| 802 | i += 1; |
| 803 | } |
| 804 | if i >= bytes.len() { |
| 805 | break; |
| 806 | } |
| 807 | let quote = bytes[i]; |
| 808 | if quote != b'"' && quote != b'\'' { |
| 809 | continue; |
| 810 | } |
| 811 | i += 1; |
| 812 | let value_start = i; |
| 813 | while i < bytes.len() && bytes[i] != quote { |
| 814 | i += 1; |
| 815 | } |
| 816 | let value = tag[value_start..i.min(bytes.len())].to_string(); |
| 817 | if i < bytes.len() { |
| 818 | i += 1; |
| 819 | } |
| 820 | if name != "testcase" |
| 821 | && name != "testsuite" |
| 822 | && name != "failure" |
| 823 | && name != "error" |
| 824 | && name != "skipped" |
| 825 | && name != "system-out" |
| 826 | && name != "system-err" |
| 827 | && name != "properties" |
| 828 | { |
| 829 | attrs.insert(name.to_string(), value); |
| 830 | } |
| 831 | } |
| 832 | attrs |
| 833 | } |
| 834 | |
| 835 | /// Unescape the five predefined XML entities plus numeric character refs. |
| 836 | fn xml_unescape(s: &str) -> String { |
| 837 | let mut out = String::with_capacity(s.len()); |
| 838 | let mut rest = s; |
| 839 | while let Some(amp) = rest.find('&') { |
| 840 | out.push_str(&rest[..amp]); |
| 841 | let tail = &rest[amp..]; |
| 842 | let semi = tail.find(';'); |
| 843 | match semi { |
| 844 | Some(end) if end < 12 => { |
| 845 | let entity = &tail[..end + 1]; |
| 846 | match entity { |
| 847 | "<" => out.push('<'), |
| 848 | ">" => out.push('>'), |
| 849 | "&" => out.push('&'), |
| 850 | """ => out.push('"'), |
| 851 | "'" => out.push('\''), |
| 852 | _ if entity.starts_with("&#") => { |
| 853 | let num = &entity[2..entity.len() - 1]; |
| 854 | let code = if let Some(hex) = num.strip_prefix('x').or_else(|| num.strip_prefix('X')) { |
| 855 | u32::from_str_radix(hex, 16).ok() |
| 856 | } else { |
| 857 | num.parse::<u32>().ok() |
| 858 | }; |
| 859 | match code.and_then(char::from_u32) { |
| 860 | Some(ch) => out.push(ch), |
| 861 | None => out.push_str(entity), |
| 862 | } |
| 863 | } |
| 864 | _ => out.push_str(entity), |
| 865 | } |
| 866 | rest = &tail[end + 1..]; |
| 867 | } |
| 868 | _ => { |
| 869 | out.push('&'); |
| 870 | rest = &tail[1..]; |
| 871 | } |
| 872 | } |
| 873 | } |
| 874 | out.push_str(rest); |
| 875 | out |
| 876 | } |
| 877 | |
| 878 | // --------------------------------------------------------------------------- |
| 879 | // Model rendering |
| 880 | // --------------------------------------------------------------------------- |
| 881 | |
| 882 | fn tool_label(tool: Tool) -> &'static str { |
| 883 | match tool { |
| 884 | Tool::Kotlin => "kotlinc", |
| 885 | Tool::Java => "javac", |
| 886 | Tool::Rust => "rustc", |
| 887 | Tool::Gradle => "gradle", |
| 888 | Tool::Detekt => "detekt", |
| 889 | Tool::Lint => "lint", |
| 890 | Tool::Other => "other", |
| 891 | } |
| 892 | } |
| 893 | |
| 894 | fn format_diagnostic(d: &Diagnostic) -> String { |
| 895 | let sev = match d.severity { |
| 896 | Severity::Error => "error", |
| 897 | Severity::Warning => "warning", |
| 898 | }; |
| 899 | let loc = match (&d.file, d.line, d.col) { |
| 900 | (Some(f), Some(l), Some(c)) => format!("{f}:{l}:{c}"), |
| 901 | (Some(f), Some(l), None) => format!("{f}:{l}"), |
| 902 | (Some(f), None, _) => f.clone(), |
| 903 | (None, _, _) => tool_label(d.tool).to_string(), |
| 904 | }; |
| 905 | let code = d |
| 906 | .code |
| 907 | .as_ref() |
| 908 | .map(|c| format!(" [{c}]")) |
| 909 | .unwrap_or_default(); |
| 910 | // Keep one-line: collapse internal newlines in the message. |
| 911 | let message: Vec<&str> = d.message.split_whitespace().collect(); |
| 912 | format!("{loc}: {sev}{code}: {}", message.join(" ")) |
| 913 | } |
| 914 | |
| 915 | fn truncate_to_budget(s: &str, budget: usize) -> String { |
| 916 | if s.len() <= budget { |
| 917 | return s.to_string(); |
| 918 | } |
| 919 | // Cut at a line boundary below the budget when possible. |
| 920 | let mut end = budget; |
| 921 | while end > 0 && !s.is_char_boundary(end) { |
| 922 | end -= 1; |
| 923 | } |
| 924 | let cut = s[..end].rfind('\n').unwrap_or(end).min(s.len()); |
| 925 | let mut out = s[..cut].to_string(); |
| 926 | out.push_str("\n…(truncated)"); |
| 927 | out |
| 928 | } |
| 929 | |
| 930 | /// Compact model-friendly rendering of a [`BuildSummary`]. |
| 931 | /// |
| 932 | /// Status line, failed tasks, diagnostics (`file:line:col: error: msg`), |
| 933 | /// what-went-wrong, then the tail only when no diagnostics were found. |
| 934 | /// Kept under ~6 KB. |
| 935 | pub fn render_build_for_model(summary: &BuildSummary) -> String { |
| 936 | let mut out = String::new(); |
| 937 | out.push_str(if summary.success { |
| 938 | "build: OK\n" |
| 939 | } else { |
| 940 | "build: FAILED\n" |
| 941 | }); |
| 942 | if !summary.failed_tasks.is_empty() { |
| 943 | out.push_str("failed tasks:\n"); |
| 944 | for task in &summary.failed_tasks { |
| 945 | out.push_str(&format!(" {task}\n")); |
| 946 | } |
| 947 | } |
| 948 | let mut errors = 0; |
| 949 | let mut warnings = 0; |
| 950 | for d in &summary.diagnostics { |
| 951 | match d.severity { |
| 952 | Severity::Error => errors += 1, |
| 953 | Severity::Warning => warnings += 1, |
| 954 | } |
| 955 | } |
| 956 | if errors + warnings > 0 { |
| 957 | out.push_str(&format!("diagnostics ({errors} errors, {warnings} warnings):\n")); |
| 958 | for d in &summary.diagnostics { |
| 959 | out.push_str(&format!(" {}\n", format_diagnostic(d))); |
| 960 | } |
| 961 | } |
| 962 | if let Some(block) = &summary.what_went_wrong { |
| 963 | out.push_str("what went wrong:\n"); |
| 964 | for line in block.lines().take(10) { |
| 965 | out.push_str(&format!(" {line}\n")); |
| 966 | } |
| 967 | } |
| 968 | if summary.diagnostics.is_empty() && !summary.log_tail.trim().is_empty() { |
| 969 | out.push_str("tail:\n"); |
| 970 | let lines: Vec<&str> = summary.log_tail.lines().collect(); |
| 971 | let start = lines.len().saturating_sub(20); |
| 972 | for line in &lines[start..] { |
| 973 | out.push_str(&format!(" {line}\n")); |
| 974 | } |
| 975 | } |
| 976 | truncate_to_budget(&out, RENDER_BUDGET_BYTES) |
| 977 | } |
| 978 | |
| 979 | /// Compact model-friendly rendering of a [`TestSummary`]. Kept under ~6 KB. |
| 980 | pub fn render_tests_for_model(summary: &TestSummary) -> String { |
| 981 | let mut out = String::new(); |
| 982 | let total = summary.passed + summary.failed + summary.skipped + summary.errors; |
| 983 | if summary.failed == 0 && summary.errors == 0 { |
| 984 | out.push_str(&format!( |
| 985 | "tests: OK ({total} passed, {} skipped)\n", |
| 986 | summary.skipped |
| 987 | )); |
| 988 | } else { |
| 989 | out.push_str(&format!( |
| 990 | "tests: FAILED ({} passed, {} failed, {} errors, {} skipped, {} total)\n", |
| 991 | summary.passed, summary.failed, summary.errors, summary.skipped, total |
| 992 | )); |
| 993 | out.push_str("failures:\n"); |
| 994 | for f in &summary.failures { |
| 995 | out.push_str(&format!(" {}.{}: {}\n", f.class, f.name, single_line(&f.message, 300))); |
| 996 | for line in f.trace.lines().skip(1).take(5) { |
| 997 | let line = line.trim(); |
| 998 | if !line.is_empty() { |
| 999 | out.push_str(&format!(" {line}\n")); |
| 1000 | } |
| 1001 | } |
| 1002 | } |
| 1003 | } |
| 1004 | truncate_to_budget(&out, RENDER_BUDGET_BYTES) |
| 1005 | } |
| 1006 | |
| 1007 | fn single_line(s: &str, max: usize) -> String { |
| 1008 | let joined: Vec<&str> = s.split_whitespace().collect(); |
| 1009 | let joined = joined.join(" "); |
| 1010 | if joined.len() <= max { |
| 1011 | joined |
| 1012 | } else { |
| 1013 | let mut end = max; |
| 1014 | while end > 0 && !joined.is_char_boundary(end) { |
| 1015 | end -= 1; |
| 1016 | } |
| 1017 | format!("{}…", &joined[..end]) |
| 1018 | } |
| 1019 | } |
| 1020 | |
| 1021 | #[cfg(test)] |
| 1022 | mod tests { |
| 1023 | use super::*; |
| 1024 | use std::path::PathBuf; |
| 1025 | |
| 1026 | fn testdata(name: &str) -> (String, String) { |
| 1027 | let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); |
| 1028 | dir.push("src"); |
| 1029 | dir.push("testdata"); |
| 1030 | dir.push("parsers"); |
| 1031 | let read_opt = |suffix: &str| { |
| 1032 | let mut p = dir.clone(); |
| 1033 | p.push(format!("{name}.{suffix}")); |
| 1034 | std::fs::read_to_string(&p).unwrap_or_default() |
| 1035 | }; |
| 1036 | (read_opt("stdout.txt"), read_opt("stderr.txt")) |
| 1037 | } |
| 1038 | |
| 1039 | fn xml_fixture(name: &str) -> String { |
| 1040 | let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR")); |
| 1041 | p.push("src"); |
| 1042 | p.push("testdata"); |
| 1043 | p.push("parsers"); |
| 1044 | p.push(name); |
| 1045 | std::fs::read_to_string(&p).unwrap_or_else(|e| panic!("missing fixture {name}: {e}")) |
| 1046 | } |
| 1047 | |
| 1048 | const ROOT: &str = "/Users/vayun/Documents/Modern-Apps-wt/isess-parsers"; |
| 1049 | |
| 1050 | #[test] |
| 1051 | fn kotlin_error_is_parsed() { |
| 1052 | let (out, err) = testdata("kotlin_error"); |
| 1053 | let summary = parse_build_output(&out, &err, Some(1), ROOT); |
| 1054 | assert!(!summary.success); |
| 1055 | assert_eq!(summary.failed_tasks, vec![":calculator:compileDevKotlin"]); |
| 1056 | assert!(summary.what_went_wrong.is_some()); |
| 1057 | let diag = summary |
| 1058 | .diagnostics |
| 1059 | .iter() |
| 1060 | .find(|d| d.tool == Tool::Kotlin && d.severity == Severity::Error) |
| 1061 | .expect("kotlin error diagnostic"); |
| 1062 | assert_eq!( |
| 1063 | diag.file.as_deref(), |
| 1064 | Some("calculator/src/main/java/com/vayunmathur/calculator/util/Units.kt") |
| 1065 | ); |
| 1066 | assert_eq!(diag.line, Some(801)); |
| 1067 | assert_eq!(diag.col, Some(30)); |
| 1068 | assert!(diag.message.contains("Initializer type mismatch")); |
| 1069 | } |
| 1070 | |
| 1071 | #[test] |
| 1072 | fn kotlin_success_has_no_errors() { |
| 1073 | let (out, err) = testdata("kotlin_success"); |
| 1074 | let summary = parse_build_output(&out, &err, Some(0), ROOT); |
| 1075 | assert!(summary.success); |
| 1076 | assert!(summary.failed_tasks.is_empty()); |
| 1077 | // A clean build still carries kotlinc deprecation warnings from |
| 1078 | // upstream modules — success means no *errors*, not no diagnostics. |
| 1079 | assert!(summary |
| 1080 | .diagnostics |
| 1081 | .iter() |
| 1082 | .all(|d| d.severity == Severity::Warning)); |
| 1083 | let deprecation = summary |
| 1084 | .diagnostics |
| 1085 | .iter() |
| 1086 | .find(|d| d.tool == Tool::Kotlin && d.message.contains("deprecated")) |
| 1087 | .expect("deprecation warning"); |
| 1088 | assert_eq!( |
| 1089 | deprecation.file.as_deref(), |
| 1090 | Some("sdk/games/src/main/java/com/vayunmathur/sdk/games/GameHubClient.kt") |
| 1091 | ); |
| 1092 | assert_eq!(deprecation.line, Some(197)); |
| 1093 | assert!(summary.what_went_wrong.is_none()); |
| 1094 | assert!(summary.log_tail.contains("BUILD SUCCESSFUL")); |
| 1095 | } |
| 1096 | |
| 1097 | #[test] |
| 1098 | fn unittest_failure_console_is_parsed() { |
| 1099 | let (out, err) = testdata("unittest_failure"); |
| 1100 | let summary = parse_build_output(&out, &err, Some(1), ROOT); |
| 1101 | assert!(!summary.success); |
| 1102 | assert_eq!(summary.failed_tasks, vec![":calculator:testDevUnitTest"]); |
| 1103 | let block = summary.what_went_wrong.expect("what went wrong"); |
| 1104 | assert!(block.contains("There were failing tests")); |
| 1105 | } |
| 1106 | |
| 1107 | #[test] |
| 1108 | fn rustc_error_and_warning_are_parsed() { |
| 1109 | let (out, err) = testdata("rustc_error"); |
| 1110 | let summary = parse_build_output(&out, &err, Some(101), ROOT); |
| 1111 | assert!(!summary.success); |
| 1112 | assert_eq!( |
| 1113 | summary.failed_tasks, |
| 1114 | vec![":euicc:cargoBuild_euicc_arm64_v8a"] |
| 1115 | ); |
| 1116 | let error = summary |
| 1117 | .diagnostics |
| 1118 | .iter() |
| 1119 | .find(|d| d.tool == Tool::Rust && d.severity == Severity::Error) |
| 1120 | .expect("rustc error"); |
| 1121 | assert_eq!(error.code.as_deref(), Some("E0308")); |
| 1122 | assert_eq!(error.file.as_deref(), Some("euicc/src/main/rust/src/base64.rs")); |
| 1123 | assert_eq!(error.line, Some(96)); |
| 1124 | assert_eq!(error.col, Some(37)); |
| 1125 | let warning = summary |
| 1126 | .diagnostics |
| 1127 | .iter() |
| 1128 | .find(|d| { |
| 1129 | d.tool == Tool::Rust |
| 1130 | && d.severity == Severity::Warning |
| 1131 | && d.message.contains("unused imports") |
| 1132 | }) |
| 1133 | .expect("rustc warning"); |
| 1134 | assert_eq!( |
| 1135 | warning.file.as_deref(), |
| 1136 | Some("euicc/src/main/rust/src/download.rs") |
| 1137 | ); |
| 1138 | assert_eq!(warning.line, Some(14)); |
| 1139 | assert_eq!(warning.col, Some(16)); |
| 1140 | // Errors sort before warnings. |
| 1141 | let first_error = summary |
| 1142 | .diagnostics |
| 1143 | .iter() |
| 1144 | .position(|d| d.severity == Severity::Error) |
| 1145 | .unwrap(); |
| 1146 | let first_warning = summary |
| 1147 | .diagnostics |
| 1148 | .iter() |
| 1149 | .position(|d| d.severity == Severity::Warning) |
| 1150 | .unwrap(); |
| 1151 | assert!(first_error < first_warning); |
| 1152 | } |
| 1153 | |
| 1154 | #[test] |
| 1155 | fn detekt_findings_are_parsed() { |
| 1156 | let (out, err) = testdata("detekt"); |
| 1157 | let summary = parse_build_output(&out, &err, Some(1), ROOT); |
| 1158 | assert!(!summary.success); |
| 1159 | assert_eq!(summary.failed_tasks, vec![":calculator:detekt"]); |
| 1160 | let magic = summary |
| 1161 | .diagnostics |
| 1162 | .iter() |
| 1163 | .find(|d| d.code.as_deref() == Some("MagicNumber")) |
| 1164 | .expect("MagicNumber finding"); |
| 1165 | assert_eq!(magic.tool, Tool::Detekt); |
| 1166 | assert_eq!(magic.severity, Severity::Error); |
| 1167 | assert_eq!( |
| 1168 | magic.file.as_deref(), |
| 1169 | Some("calculator/src/main/java/com/vayunmathur/calculator/widget/CalculatorKeyAction.kt") |
| 1170 | ); |
| 1171 | assert_eq!(magic.line, Some(132)); |
| 1172 | assert!(summary.diagnostics.iter().any(|d| d.tool == Tool::Detekt |
| 1173 | && d.code.as_deref() == Some("UndocumentedPublicClass"))); |
| 1174 | } |
| 1175 | |
| 1176 | #[test] |
| 1177 | fn lint_error_is_parsed() { |
| 1178 | let (out, err) = testdata("lint_error"); |
| 1179 | let summary = parse_build_output(&out, &err, Some(1), ROOT); |
| 1180 | assert!(!summary.success); |
| 1181 | assert!(summary.failed_tasks.contains(&":calculator:lintDev".to_string())); |
| 1182 | let toast = summary |
| 1183 | .diagnostics |
| 1184 | .iter() |
| 1185 | .find(|d| d.code.as_deref() == Some("ToastUsage")) |
| 1186 | .expect("ToastUsage finding"); |
| 1187 | assert_eq!(toast.tool, Tool::Lint); |
| 1188 | assert_eq!(toast.severity, Severity::Error); |
| 1189 | assert_eq!( |
| 1190 | toast.file.as_deref(), |
| 1191 | Some("calculator/src/main/java/com/vayunmathur/calculator/util/UnitsModel.kt") |
| 1192 | ); |
| 1193 | assert_eq!(toast.line, Some(26)); |
| 1194 | } |
| 1195 | |
| 1196 | #[test] |
| 1197 | fn check_wrapper_output_is_parsed() { |
| 1198 | let (out, err) = testdata("check_calculator"); |
| 1199 | let summary = parse_build_output(&out, &err, Some(1), ROOT); |
| 1200 | assert!(!summary.success); |
| 1201 | assert!(summary.failed_tasks.iter().any(|t| t.contains("detekt"))); |
| 1202 | assert!(!summary.diagnostics.is_empty()); |
| 1203 | } |
| 1204 | |
| 1205 | #[test] |
| 1206 | fn synthetic_javac_shapes_are_parsed() { |
| 1207 | // SYNTHETIC: repo is all-Kotlin; javac errors do not occur naturally. |
| 1208 | let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR")); |
| 1209 | p.push("src"); |
| 1210 | p.push("testdata"); |
| 1211 | p.push("parsers"); |
| 1212 | p.push("javac_error.synthetic.txt"); |
| 1213 | let combined = std::fs::read_to_string(&p).expect("synthetic javac fixture"); |
| 1214 | // Fixture file carries a `#` header; parse body after it. |
| 1215 | let body: Vec<&str> = combined |
| 1216 | .lines() |
| 1217 | .filter(|l| !l.starts_with('#')) |
| 1218 | .collect(); |
| 1219 | let body = body.join("\n"); |
| 1220 | let summary = parse_build_output(&body, "", Some(1), ROOT); |
| 1221 | assert!(!summary.success); |
| 1222 | let error = summary |
| 1223 | .diagnostics |
| 1224 | .iter() |
| 1225 | .find(|d| d.tool == Tool::Java && d.severity == Severity::Error) |
| 1226 | .expect("javac error"); |
| 1227 | assert_eq!( |
| 1228 | error.file.as_deref(), |
| 1229 | Some("library/src/main/java/com/vayunmathur/library/util/LegacyBridge.java") |
| 1230 | ); |
| 1231 | assert_eq!(error.line, Some(42)); |
| 1232 | assert!(summary |
| 1233 | .diagnostics |
| 1234 | .iter() |
| 1235 | .any(|d| d.tool == Tool::Java && d.severity == Severity::Warning)); |
| 1236 | } |
| 1237 | |
| 1238 | #[test] |
| 1239 | fn slot_marker_paths_relativize() { |
| 1240 | let file = "/builds/slots/slot-3/Modern-Apps/calculator/src/main/java/App.kt"; |
| 1241 | assert_eq!( |
| 1242 | relativize(file, "/Users/vayun/Documents/Modern-Apps-wt/isess-parsers"), |
| 1243 | Some("Modern-Apps/calculator/src/main/java/App.kt".to_string()) |
| 1244 | ); |
| 1245 | } |
| 1246 | |
| 1247 | #[test] |
| 1248 | fn junit_failure_xml_is_parsed() { |
| 1249 | let xml = xml_fixture("junit_failure.xml"); |
| 1250 | let summary = parse_junit_xml(&xml).expect("parse failure xml"); |
| 1251 | assert_eq!(summary.failed, 1); |
| 1252 | assert_eq!(summary.errors, 0); |
| 1253 | assert_eq!(summary.passed, 35); |
| 1254 | assert_eq!(summary.failures.len(), 1); |
| 1255 | let f = &summary.failures[0]; |
| 1256 | assert_eq!(f.class, "com.vayunmathur.calculator.util.ExpressionTest"); |
| 1257 | assert_eq!(f.name, "multiplicationBindsTighterThanAddition"); |
| 1258 | assert!(f.message.contains("999.0")); |
| 1259 | assert!(f.trace.lines().count() <= TRACE_LINES); |
| 1260 | } |
| 1261 | |
| 1262 | #[test] |
| 1263 | fn junit_pass_xml_is_parsed() { |
| 1264 | let xml = xml_fixture("junit_pass.xml"); |
| 1265 | let summary = parse_junit_xml(&xml).expect("parse pass xml"); |
| 1266 | assert_eq!(summary.failed, 0); |
| 1267 | assert_eq!(summary.errors, 0); |
| 1268 | assert_eq!(summary.passed, 22); |
| 1269 | assert!(summary.failures.is_empty()); |
| 1270 | } |
| 1271 | |
| 1272 | #[test] |
| 1273 | fn junit_merge_adds_counters_and_caps_failures() { |
| 1274 | let a = TestSummary { |
| 1275 | passed: 10, |
| 1276 | failed: 2, |
| 1277 | skipped: 1, |
| 1278 | errors: 1, |
| 1279 | failures: vec![ |
| 1280 | TestFailure { |
| 1281 | class: "A".into(), |
| 1282 | name: "t1".into(), |
| 1283 | message: "m".into(), |
| 1284 | trace: "t".into(), |
| 1285 | }, |
| 1286 | TestFailure { |
| 1287 | class: "A".into(), |
| 1288 | name: "t2".into(), |
| 1289 | message: "m".into(), |
| 1290 | trace: "t".into(), |
| 1291 | }, |
| 1292 | ], |
| 1293 | }; |
| 1294 | let b = TestSummary { |
| 1295 | passed: 5, |
| 1296 | failed: 1, |
| 1297 | skipped: 0, |
| 1298 | errors: 0, |
| 1299 | failures: vec![TestFailure { |
| 1300 | class: "B".into(), |
| 1301 | name: "t3".into(), |
| 1302 | message: "m".into(), |
| 1303 | trace: "t".into(), |
| 1304 | }], |
| 1305 | }; |
| 1306 | let merged = merge_test_summaries(&[a, b]); |
| 1307 | assert_eq!(merged.passed, 15); |
| 1308 | assert_eq!(merged.failed, 3); |
| 1309 | assert_eq!(merged.skipped, 1); |
| 1310 | assert_eq!(merged.errors, 1); |
| 1311 | assert_eq!(merged.failures.len(), 3); |
| 1312 | } |
| 1313 | |
| 1314 | #[test] |
| 1315 | fn junit_rejects_garbage() { |
| 1316 | assert!(parse_junit_xml("not xml at all").is_err()); |
| 1317 | assert!(parse_junit_xml("<testsuites></testsuites>").is_err()); |
| 1318 | } |
| 1319 | |
| 1320 | #[test] |
| 1321 | fn render_build_stays_under_budget() { |
| 1322 | let (out, err) = testdata("lint_error"); |
| 1323 | let summary = parse_build_output(&out, &err, Some(1), ROOT); |
| 1324 | let rendered = render_build_for_model(&summary); |
| 1325 | assert!(rendered.len() <= RENDER_BUDGET_BYTES); |
| 1326 | assert!(rendered.contains("build: FAILED")); |
| 1327 | assert!(rendered.contains("ToastUsage")); |
| 1328 | } |
| 1329 | |
| 1330 | #[test] |
| 1331 | fn render_tests_stays_under_budget() { |
| 1332 | let xml = xml_fixture("junit_failure.xml"); |
| 1333 | let summary = parse_junit_xml(&xml).expect("parse"); |
| 1334 | let rendered = render_tests_for_model(&summary); |
| 1335 | assert!(rendered.len() <= RENDER_BUDGET_BYTES); |
| 1336 | assert!(rendered.contains("tests: FAILED")); |
| 1337 | assert!(rendered.contains("multiplicationBindsTighterThanAddition")); |
| 1338 | } |
| 1339 | |
| 1340 | #[test] |
| 1341 | fn render_success_omits_tail() { |
| 1342 | let (out, err) = testdata("kotlin_success"); |
| 1343 | let summary = parse_build_output(&out, &err, Some(0), ROOT); |
| 1344 | let rendered = render_build_for_model(&summary); |
| 1345 | assert!(rendered.starts_with("build: OK")); |
| 1346 | assert!(!rendered.contains("tail:")); |
| 1347 | } |
| 1348 | } |