1use crate::compress::caps::{cap_classified_blocks, ClassifiedBlock, DropClass};
2use crate::compress::generic::GenericCompressor;
3use crate::compress::{CompressionResult, Compressor, Specificity};
4
5pub struct BunCompressor;
6
7impl Compressor for BunCompressor {
8 fn specificity(&self) -> Specificity {
9 Specificity::PackageManager
10 }
11
12 fn matches(&self, command: &str) -> bool {
13 command
14 .split_whitespace()
15 .next()
16 .is_some_and(|head| head == "bun")
17 }
18
19 fn compress_with_exit_code(
20 &self,
21 command: &str,
22 output: &str,
23 exit_code: Option<i64>,
24 ) -> CompressionResult {
25 match bun_subcommand(command).as_deref() {
26 Some("install" | "i" | "add" | "remove") => compress_package(output).into(),
27 Some("test") => preserve_bun_failure(output, compress_test(output), exit_code),
28 Some("build") => compress_build(output),
29 _ => GenericCompressor::compress_output(output).into(),
30 }
31 }
32
33 fn matches_output(&self, output: &str) -> bool {
34 let mut saw_ran_summary = false;
35 let mut saw_result_marker = false;
36
37 for line in output.lines() {
38 saw_ran_summary |= is_ran_summary_line(line);
39 saw_result_marker |= is_bun_test_result_marker(line);
40
41 if saw_ran_summary && saw_result_marker {
42 return true;
43 }
44 }
45
46 false
47 }
48
49 fn compress_output_match_with_exit_code(
50 &self,
51 output: &str,
52 exit_code: Option<i64>,
53 ) -> CompressionResult {
54 preserve_bun_failure(output, compress_test(output), exit_code)
55 }
56}
57
58fn preserve_bun_failure(
59 output: &str,
60 compressed: CompressionResult,
61 exit_code: Option<i64>,
62) -> CompressionResult {
63 let stripped_failure =
64 compressed.text.trim().is_empty() || !super::text_has_failure_signal(&compressed.text);
65 if !output.trim().is_empty()
66 && stripped_failure
67 && (matches!(exit_code, Some(code) if code != 0) || super::text_has_failure_signal(output))
68 {
69 GenericCompressor::compress_output(output).into()
70 } else {
71 compressed
72 }
73}
74
75const BUN_SUBCOMMANDS: &[&str] = &[
85 "install", "i", "add", "remove", "update", "outdated", "link", "unlink", "why", "audit",
86 "patch", "pm", "publish", "pack", "run", "test", "x", "exec", "create", "init", "build",
87 "repl", "upgrade", "help", "info",
88];
89
90fn bun_subcommand(command: &str) -> Option<String> {
100 command
101 .split_whitespace()
102 .skip_while(|token| *token != "bun")
103 .skip(1)
104 .find(|token| BUN_SUBCOMMANDS.contains(token))
105 .map(ToString::to_string)
106}
107
108fn compress_package(output: &str) -> String {
109 let mut result = Vec::new();
110 let mut last_content_line = None;
111 for line in output.lines() {
112 if is_bun_progress(line) {
113 continue;
114 }
115 let trimmed = line.trim_start();
116 if !trimmed.is_empty() {
117 last_content_line = Some(line);
118 }
119 if trimmed.contains("packages installed")
120 || trimmed.contains("package installed")
121 || is_bun_install_summary(trimmed)
122 || trimmed.starts_with("error:")
123 || trimmed.starts_with("warn:")
124 || trimmed.starts_with("bun install error:")
125 || trimmed.starts_with("Saved lockfile")
126 {
127 result.push(line.to_string());
128 }
129 }
130 if result.is_empty() {
133 if let Some(line) = last_content_line {
134 result.push(line.to_string());
135 }
136 }
137 trim_trailing_lines(&result.join("\n"))
138}
139
140fn is_bun_install_summary(trimmed: &str) -> bool {
143 trimmed.starts_with("Checked ") && trimmed.contains(" installs across ")
144}
145
146fn compress_build(output: &str) -> CompressionResult {
147 let mut blocks = Vec::new();
148 for line in output.lines() {
149 if is_timing_line(line) {
150 blocks.push(ClassifiedBlock::new(DropClass::Timing, line.to_string()));
151 } else {
152 blocks.push(ClassifiedBlock::unclassified(line.to_string()));
153 }
154 }
155 let capped = cap_classified_blocks(blocks);
156 CompressionResult::with_class_drops(trim_trailing_lines(&capped.text), capped.dropped_by_class)
157}
158
159fn compress_test(output: &str) -> CompressionResult {
180 let lines: Vec<&str> = output.lines().collect();
181 if lines.is_empty() {
182 return CompressionResult::new(output.to_string());
183 }
184
185 let has_failures = lines.iter().any(|line| is_bun_test_fail_marker(line));
189 if !has_failures {
190 return CompressionResult::new(compress_test_pass_only(&lines));
191 }
192
193 let mut blocks: Vec<ClassifiedBlock> = Vec::new();
194 let mut index = 0usize;
195 let mut saw_ran_summary = false;
196 let mut pending_section: Option<String> = None;
197
198 while index < lines.len() {
199 let line = lines[index];
200
201 if saw_ran_summary {
202 blocks.push(ClassifiedBlock::unclassified(line.to_string()));
208 index += 1;
209 continue;
210 }
211
212 if is_bun_test_header(line) {
214 blocks.push(ClassifiedBlock::unclassified(render_bun_header(line)));
215 index += 1;
216 continue;
217 }
218
219 if is_file_section_header(line) {
223 let next_fail = next_index(&lines, index + 1, is_bun_test_fail_marker);
224 let next_section = next_index(&lines, index + 1, |l| {
225 is_file_section_header(l) || is_summary_line(l)
226 });
227 let keep_section = match (next_fail, next_section) {
228 (Some(fi), Some(si)) => fi < si,
229 (Some(_), None) => true,
230 (None, _) => false,
231 };
232 if keep_section {
233 pending_section = Some(line.to_string());
234 }
235 index += 1;
236 continue;
237 }
238
239 if is_summary_line(line) {
241 blocks.push(ClassifiedBlock::unclassified(render_summary_line(line)));
242 if is_ran_summary_line(line) {
247 saw_ran_summary = true;
248 }
249 index += 1;
250 continue;
251 }
252
253 if is_bun_test_error_start(line) || is_bun_test_code_pointer(line) {
258 let block_start = index;
263 let mut block_end = index;
264 while block_end < lines.len() {
265 if is_bun_test_fail_marker(lines[block_end]) {
266 block_end += 1;
267 break;
268 }
269 block_end += 1;
274 }
275
276 let mut block_lines = Vec::new();
277 if let Some(section) = pending_section.take() {
278 block_lines.push(section);
279 }
280 block_lines.extend(
281 lines[block_start..block_end]
282 .iter()
283 .map(|line| (*line).to_string()),
284 );
285 blocks.push(ClassifiedBlock::new(
286 DropClass::Failure,
287 block_lines.join("\n"),
288 ));
289 index = block_end;
290 continue;
291 }
292
293 index += 1;
295 }
296
297 if blocks.is_empty() {
300 return GenericCompressor::compress_output(output).into();
301 }
302 let capped = cap_classified_blocks(blocks);
303 CompressionResult::with_class_drops(trim_trailing_lines(&capped.text), capped.dropped_by_class)
304}
305
306fn compress_test_pass_only(lines: &[&str]) -> String {
319 let mut result: Vec<String> = Vec::new();
320 let mut saw_ran_summary = false;
321
322 for line in lines {
323 if saw_ran_summary {
324 result.push((*line).to_string());
326 continue;
327 }
328 if is_bun_test_header(line) {
329 result.push(render_bun_header(line));
330 } else if is_summary_line(line) {
331 result.push(render_summary_line(line));
332 if is_ran_summary_line(line) {
336 saw_ran_summary = true;
337 }
338 }
339 }
340
341 if result.is_empty() {
342 return GenericCompressor::compress_output(&lines.join("\n"));
343 }
344 trim_trailing_lines(&result.join("\n"))
345}
346
347fn next_index<F>(lines: &[&str], start: usize, predicate: F) -> Option<usize>
348where
349 F: Fn(&str) -> bool,
350{
351 lines
352 .iter()
353 .enumerate()
354 .skip(start)
355 .find(|(_, line)| predicate(line))
356 .map(|(i, _)| i)
357}
358
359fn is_bun_test_header(line: &str) -> bool {
360 line.starts_with("bun test v")
361}
362
363fn render_bun_header(line: &str) -> String {
367 match line.find(" v") {
368 Some(idx) => line[..idx].to_string(),
369 None => line.to_string(),
370 }
371}
372
373fn render_summary_line(line: &str) -> String {
378 if is_ran_summary_line(line.trim_start()) {
379 if let Some(idx) = line.rfind(" [") {
380 return line[..idx].to_string();
381 }
382 }
383 line.to_string()
384}
385
386fn is_file_section_header(line: &str) -> bool {
387 let trimmed = line.trim_end();
392 if trimmed.starts_with(' ') || !trimmed.ends_with(':') {
393 return false;
394 }
395 let path = &trimmed[..trimmed.len() - 1];
396 if path.is_empty() || path.contains(' ') {
397 return false;
398 }
399 path.contains(".test.")
400 || path.contains(".spec.")
401 || path.contains("_test.")
402 || path.contains("_spec.")
403}
404
405fn is_bun_test_result_marker(line: &str) -> bool {
406 is_bun_test_pass_marker(line) || is_bun_test_fail_marker(line)
407}
408
409fn is_bun_test_pass_marker(line: &str) -> bool {
410 is_bun_test_marker(line, "(pass)")
411}
412
413fn is_bun_test_fail_marker(line: &str) -> bool {
414 is_bun_test_marker(line, "(fail)")
415}
416
417fn is_bun_test_marker(line: &str, marker: &str) -> bool {
418 let trimmed = line.trim();
419 let Some(rest) = trimmed.strip_prefix(marker) else {
420 return false;
421 };
422 if !rest.chars().next().is_some_and(|ch| ch.is_whitespace()) {
423 return false;
424 }
425
426 let name_and_timing = rest.trim_start();
427 let Some((name, timing)) = name_and_timing.rsplit_once(" [") else {
428 return false;
429 };
430 if name.trim().is_empty() {
431 return false;
432 }
433
434 let Some(duration) = timing.strip_suffix(']') else {
435 return false;
436 };
437 is_bun_test_duration(duration)
438}
439
440fn is_bun_test_duration(duration: &str) -> bool {
441 ["ms", "µs", "μs", "us", "ns", "s"]
442 .iter()
443 .any(|unit| duration.strip_suffix(*unit).is_some_and(is_decimal_number))
444}
445
446fn is_decimal_number(value: &str) -> bool {
447 let mut saw_digit = false;
448 let mut saw_dot = false;
449
450 for ch in value.chars() {
451 match ch {
452 '0'..='9' => saw_digit = true,
453 '.' if !saw_dot => saw_dot = true,
454 _ => return false,
455 }
456 }
457
458 saw_digit
459}
460
461fn is_bun_test_error_start(line: &str) -> bool {
462 line.starts_with("error:")
467}
468
469fn is_bun_test_code_pointer(line: &str) -> bool {
470 let trimmed = line.trim_start();
474 if !trimmed.contains(" | ") && !trimmed.contains("| ") {
475 return false;
476 }
477 trimmed
479 .chars()
480 .next()
481 .is_some_and(|char| char.is_ascii_digit())
482}
483
484fn is_ran_summary_line(line: &str) -> bool {
488 let Some(rest) = line.strip_prefix("Ran ") else {
489 return false;
490 };
491 let Some((test_count, rest)) = rest.split_once(" tests across ") else {
492 return false;
493 };
494 if test_count.is_empty() || !test_count.chars().all(|ch| ch.is_ascii_digit()) {
495 return false;
496 }
497 let Some((file_count, rest)) = rest.split_once(" file") else {
498 return false;
499 };
500 if file_count.is_empty() || !file_count.chars().all(|ch| ch.is_ascii_digit()) {
501 return false;
502 }
503 rest.starts_with(". [") || rest.starts_with("s. [")
504}
505
506fn is_summary_line(line: &str) -> bool {
507 let trimmed = line.trim_start();
508 if is_ran_summary_line(trimmed) {
512 return true;
513 }
514 if let Some(first_token) = trimmed.split_whitespace().next() {
515 if first_token.chars().all(|char| char.is_ascii_digit()) {
516 let rest = trimmed[first_token.len()..].trim_start();
517 return rest.starts_with("pass")
518 || rest.starts_with("fail")
519 || rest.starts_with("expect()");
520 }
521 }
522 false
523}
524
525fn is_bun_progress(line: &str) -> bool {
526 let trimmed = line.trim();
527 trimmed == "."
528 || trimmed.chars().all(|char| char == '.')
529 || trimmed.starts_with("Resolving")
530 || trimmed.starts_with("Resolved")
531 || trimmed.starts_with("Downloaded")
532 || trimmed.starts_with("Extracted")
533}
534
535fn is_timing_line(line: &str) -> bool {
536 let trimmed = line.trim_start();
537 trimmed.starts_with('[') && trimmed.contains(" ms]")
538}
539
540fn trim_trailing_lines(input: &str) -> String {
541 input
542 .lines()
543 .map(str::trim_end)
544 .collect::<Vec<_>>()
545 .join("\n")
546}
547
548#[cfg(test)]
549mod tests {
550 use super::*;
551
552 #[test]
553 fn bun_test_compile_error_falls_back_when_exit_is_unknown() {
554 let output = "bun test v1.3.14 (0d9b296a)\n\nerror: Cannot find module './missing' from 'src/app.test.ts'\n\nRan 0 tests across 1 file. [12.00ms]\n";
555
556 let compressed = BunCompressor.compress("bun test", output);
557
558 assert!(compressed.text.contains("Cannot find module"));
559 assert!(compressed.text.contains("Ran 0 tests"));
560 assert_ne!(compressed.text, "bun test\nRan 0 tests across 1 file.");
561 }
562
563 #[test]
564 fn bun_install_with_no_changes_keeps_its_summary() {
565 let output = "bun install v1.4.2 (744846f84)\n\nChecked 437 installs across 463 packages (no changes) [18.00ms]\n";
566
567 let compressed = BunCompressor.compress("bun install --frozen-lockfile", output);
568
569 assert_eq!(
570 compressed.text,
571 "Checked 437 installs across 463 packages (no changes) [18.00ms]"
572 );
573 }
574
575 #[test]
576 fn bun_install_keeps_warnings_and_never_returns_empty() {
577 let output = "bun install v1.4.2 (744846f84)\nwarn: incorrect peer dependency \"typebox@1.1.38\"\n\n+ typebox@1.1.38\n\n1 package installed [120.00ms]\n";
578 let compressed = BunCompressor.compress("bun install", output);
579 assert_eq!(
580 compressed.text,
581 "warn: incorrect peer dependency \"typebox@1.1.38\"\n1 package installed [120.00ms]"
582 );
583
584 let unfamiliar = "bun install v9.9.9\n\nDone in 4 steps\n";
586 let compressed = BunCompressor.compress("bun install", unfamiliar);
587 assert_eq!(compressed.text, "Done in 4 steps");
588 }
589}