1use std::fmt::Write;
2use std::path::Path;
3
4use fallow_core::duplicates::DuplicationReport;
5use fallow_core::results::{AnalysisResults, UnusedExport, UnusedMember};
6
7use super::grouping::ResultGroup;
8use super::{normalize_uri, plural, relative_path};
9
10fn escape_backticks(s: &str) -> String {
12 s.replace('`', "\\`")
13}
14
15pub(super) fn print_markdown(results: &AnalysisResults, root: &Path) {
16 println!("{}", build_markdown(results, root));
17}
18
19#[expect(
21 clippy::too_many_lines,
22 reason = "one section per issue type; splitting would fragment the output builder"
23)]
24pub fn build_markdown(results: &AnalysisResults, root: &Path) -> String {
25 let rel = |p: &Path| {
26 escape_backticks(&normalize_uri(
27 &relative_path(p, root).display().to_string(),
28 ))
29 };
30
31 let total = results.total_issues();
32 let mut out = String::new();
33
34 if total == 0 {
35 out.push_str("## Fallow: no issues found\n");
36 return out;
37 }
38
39 let _ = write!(out, "## Fallow: {total} issue{} found\n\n", plural(total));
40
41 markdown_section(&mut out, &results.unused_files, "Unused files", |file| {
43 vec![format!("- `{}`", rel(&file.path))]
44 });
45
46 markdown_grouped_section(
48 &mut out,
49 &results.unused_exports,
50 "Unused exports",
51 root,
52 |e| e.path.as_path(),
53 format_export,
54 );
55
56 markdown_grouped_section(
58 &mut out,
59 &results.unused_types,
60 "Unused type exports",
61 root,
62 |e| e.path.as_path(),
63 format_export,
64 );
65
66 markdown_section(
68 &mut out,
69 &results.unused_dependencies,
70 "Unused dependencies",
71 |dep| format_dependency(&dep.package_name, &dep.path, root),
72 );
73
74 markdown_section(
76 &mut out,
77 &results.unused_dev_dependencies,
78 "Unused devDependencies",
79 |dep| format_dependency(&dep.package_name, &dep.path, root),
80 );
81
82 markdown_section(
84 &mut out,
85 &results.unused_optional_dependencies,
86 "Unused optionalDependencies",
87 |dep| format_dependency(&dep.package_name, &dep.path, root),
88 );
89
90 markdown_grouped_section(
92 &mut out,
93 &results.unused_enum_members,
94 "Unused enum members",
95 root,
96 |m| m.path.as_path(),
97 format_member,
98 );
99
100 markdown_grouped_section(
102 &mut out,
103 &results.unused_class_members,
104 "Unused class members",
105 root,
106 |m| m.path.as_path(),
107 format_member,
108 );
109
110 markdown_grouped_section(
112 &mut out,
113 &results.unresolved_imports,
114 "Unresolved imports",
115 root,
116 |i| i.path.as_path(),
117 |i| format!(":{} `{}`", i.line, escape_backticks(&i.specifier)),
118 );
119
120 markdown_section(
122 &mut out,
123 &results.unlisted_dependencies,
124 "Unlisted dependencies",
125 |dep| vec![format!("- `{}`", escape_backticks(&dep.package_name))],
126 );
127
128 markdown_section(
130 &mut out,
131 &results.duplicate_exports,
132 "Duplicate exports",
133 |dup| {
134 let locations: Vec<String> = dup
135 .locations
136 .iter()
137 .map(|loc| format!("`{}`", rel(&loc.path)))
138 .collect();
139 vec![format!(
140 "- `{}` in {}",
141 escape_backticks(&dup.export_name),
142 locations.join(", ")
143 )]
144 },
145 );
146
147 markdown_section(
149 &mut out,
150 &results.type_only_dependencies,
151 "Type-only dependencies (consider moving to devDependencies)",
152 |dep| format_dependency(&dep.package_name, &dep.path, root),
153 );
154
155 markdown_section(
157 &mut out,
158 &results.test_only_dependencies,
159 "Test-only production dependencies (consider moving to devDependencies)",
160 |dep| format_dependency(&dep.package_name, &dep.path, root),
161 );
162
163 markdown_section(
165 &mut out,
166 &results.circular_dependencies,
167 "Circular dependencies",
168 |cycle| {
169 let chain: Vec<String> = cycle.files.iter().map(|p| rel(p)).collect();
170 let mut display_chain = chain.clone();
171 if let Some(first) = chain.first() {
172 display_chain.push(first.clone());
173 }
174 let cross_pkg_tag = if cycle.is_cross_package {
175 " *(cross-package)*"
176 } else {
177 ""
178 };
179 vec![format!(
180 "- {}{}",
181 display_chain
182 .iter()
183 .map(|s| format!("`{s}`"))
184 .collect::<Vec<_>>()
185 .join(" \u{2192} "),
186 cross_pkg_tag
187 )]
188 },
189 );
190
191 markdown_section(
193 &mut out,
194 &results.boundary_violations,
195 "Boundary violations",
196 |v| {
197 vec![format!(
198 "- `{}`:{} \u{2192} `{}` ({} \u{2192} {})",
199 rel(&v.from_path),
200 v.line,
201 rel(&v.to_path),
202 v.from_zone,
203 v.to_zone,
204 )]
205 },
206 );
207
208 markdown_section(
210 &mut out,
211 &results.stale_suppressions,
212 "Stale suppressions",
213 |s| {
214 vec![format!(
215 "- `{}`:{} `{}` ({})",
216 rel(&s.path),
217 s.line,
218 escape_backticks(&s.description()),
219 escape_backticks(&s.explanation()),
220 )]
221 },
222 );
223
224 out
225}
226
227pub(super) fn print_grouped_markdown(groups: &[ResultGroup], root: &Path) {
229 let total: usize = groups.iter().map(|g| g.results.total_issues()).sum();
230
231 if total == 0 {
232 println!("## Fallow: no issues found");
233 return;
234 }
235
236 println!(
237 "## Fallow: {total} issue{} found (grouped)\n",
238 plural(total)
239 );
240
241 for group in groups {
242 let count = group.results.total_issues();
243 if count == 0 {
244 continue;
245 }
246 println!(
247 "## {} ({count} issue{})\n",
248 escape_backticks(&group.key),
249 plural(count)
250 );
251 if let Some(ref owners) = group.owners
256 && !owners.is_empty()
257 {
258 let joined = owners
259 .iter()
260 .map(|o| escape_backticks(o))
261 .collect::<Vec<_>>()
262 .join(" ");
263 println!("Owners: {joined}\n");
264 }
265 let body = build_markdown(&group.results, root);
268 let sections = body
270 .strip_prefix("## Fallow: no issues found\n")
271 .or_else(|| body.find("\n\n").map(|pos| &body[pos + 2..]))
272 .unwrap_or(&body);
273 print!("{sections}");
274 }
275}
276
277fn format_export(e: &UnusedExport) -> String {
278 let re = if e.is_re_export { " (re-export)" } else { "" };
279 format!(":{} `{}`{re}", e.line, escape_backticks(&e.export_name))
280}
281
282fn format_member(m: &UnusedMember) -> String {
283 format!(
284 ":{} `{}.{}`",
285 m.line,
286 escape_backticks(&m.parent_name),
287 escape_backticks(&m.member_name)
288 )
289}
290
291fn format_dependency(dep_name: &str, pkg_path: &Path, root: &Path) -> Vec<String> {
292 let name = escape_backticks(dep_name);
293 let pkg_label = relative_path(pkg_path, root).display().to_string();
294 if pkg_label == "package.json" {
295 vec![format!("- `{name}`")]
296 } else {
297 let label = escape_backticks(&pkg_label);
298 vec![format!("- `{name}` ({label})")]
299 }
300}
301
302fn markdown_section<T>(
304 out: &mut String,
305 items: &[T],
306 title: &str,
307 format_lines: impl Fn(&T) -> Vec<String>,
308) {
309 if items.is_empty() {
310 return;
311 }
312 let _ = write!(out, "### {title} ({})\n\n", items.len());
313 for item in items {
314 for line in format_lines(item) {
315 out.push_str(&line);
316 out.push('\n');
317 }
318 }
319 out.push('\n');
320}
321
322fn markdown_grouped_section<'a, T>(
324 out: &mut String,
325 items: &'a [T],
326 title: &str,
327 root: &Path,
328 get_path: impl Fn(&'a T) -> &'a Path,
329 format_detail: impl Fn(&T) -> String,
330) {
331 if items.is_empty() {
332 return;
333 }
334 let _ = write!(out, "### {title} ({})\n\n", items.len());
335
336 let mut indices: Vec<usize> = (0..items.len()).collect();
337 indices.sort_by(|&a, &b| get_path(&items[a]).cmp(get_path(&items[b])));
338
339 let rel = |p: &Path| normalize_uri(&relative_path(p, root).display().to_string());
340 let mut last_file = String::new();
341 for &i in &indices {
342 let item = &items[i];
343 let file_str = rel(get_path(item));
344 if file_str != last_file {
345 let _ = writeln!(out, "- `{file_str}`");
346 last_file = file_str;
347 }
348 let _ = writeln!(out, " - {}", format_detail(item));
349 }
350 out.push('\n');
351}
352
353pub(super) fn print_duplication_markdown(report: &DuplicationReport, root: &Path) {
356 println!("{}", build_duplication_markdown(report, root));
357}
358
359#[must_use]
361pub fn build_duplication_markdown(report: &DuplicationReport, root: &Path) -> String {
362 let rel = |p: &Path| normalize_uri(&relative_path(p, root).display().to_string());
363
364 let mut out = String::new();
365
366 if report.clone_groups.is_empty() {
367 out.push_str("## Fallow: no code duplication found\n");
368 return out;
369 }
370
371 let stats = &report.stats;
372 let _ = write!(
373 out,
374 "## Fallow: {} clone group{} found ({:.1}% duplication)\n\n",
375 stats.clone_groups,
376 plural(stats.clone_groups),
377 stats.duplication_percentage,
378 );
379
380 out.push_str("### Duplicates\n\n");
381 for (i, group) in report.clone_groups.iter().enumerate() {
382 let instance_count = group.instances.len();
383 let _ = write!(
384 out,
385 "**Clone group {}** ({} lines, {instance_count} instance{})\n\n",
386 i + 1,
387 group.line_count,
388 plural(instance_count)
389 );
390 for instance in &group.instances {
391 let relative = rel(&instance.file);
392 let _ = writeln!(
393 out,
394 "- `{relative}:{}-{}`",
395 instance.start_line, instance.end_line
396 );
397 }
398 out.push('\n');
399 }
400
401 if !report.clone_families.is_empty() {
403 out.push_str("### Clone Families\n\n");
404 for (i, family) in report.clone_families.iter().enumerate() {
405 let file_names: Vec<_> = family.files.iter().map(|f| rel(f)).collect();
406 let _ = write!(
407 out,
408 "**Family {}** ({} group{}, {} lines across {})\n\n",
409 i + 1,
410 family.groups.len(),
411 plural(family.groups.len()),
412 family.total_duplicated_lines,
413 file_names
414 .iter()
415 .map(|s| format!("`{s}`"))
416 .collect::<Vec<_>>()
417 .join(", "),
418 );
419 for suggestion in &family.suggestions {
420 let savings = if suggestion.estimated_savings > 0 {
421 format!(" (~{} lines saved)", suggestion.estimated_savings)
422 } else {
423 String::new()
424 };
425 let _ = writeln!(out, "- {}{savings}", suggestion.description);
426 }
427 out.push('\n');
428 }
429 }
430
431 let _ = writeln!(
433 out,
434 "**Summary:** {} duplicated lines ({:.1}%) across {} file{}",
435 stats.duplicated_lines,
436 stats.duplication_percentage,
437 stats.files_with_clones,
438 plural(stats.files_with_clones),
439 );
440
441 out
442}
443
444pub(super) fn print_health_markdown(report: &crate::health_types::HealthReport, root: &Path) {
447 println!("{}", build_health_markdown(report, root));
448}
449
450#[must_use]
452pub fn build_health_markdown(report: &crate::health_types::HealthReport, root: &Path) -> String {
453 let mut out = String::new();
454
455 if let Some(ref hs) = report.health_score {
456 let _ = writeln!(out, "## Health Score: {:.0} ({})\n", hs.score, hs.grade);
457 }
458
459 write_trend_section(&mut out, report);
460 write_vital_signs_section(&mut out, report);
461
462 if report.findings.is_empty()
463 && report.file_scores.is_empty()
464 && report.coverage_gaps.is_none()
465 && report.hotspots.is_empty()
466 && report.targets.is_empty()
467 && report.production_coverage.is_none()
468 {
469 if report.vital_signs.is_none() {
470 let _ = write!(
471 out,
472 "## Fallow: no functions exceed complexity thresholds\n\n\
473 **{}** functions analyzed (max cyclomatic: {}, max cognitive: {}, max CRAP: {:.1})\n",
474 report.summary.functions_analyzed,
475 report.summary.max_cyclomatic_threshold,
476 report.summary.max_cognitive_threshold,
477 report.summary.max_crap_threshold,
478 );
479 }
480 return out;
481 }
482
483 write_findings_section(&mut out, report, root);
484 write_production_coverage_section(&mut out, report, root);
485 write_coverage_gaps_section(&mut out, report, root);
486 write_file_scores_section(&mut out, report, root);
487 write_hotspots_section(&mut out, report, root);
488 write_targets_section(&mut out, report, root);
489 write_metric_legend(&mut out, report);
490
491 out
492}
493
494fn write_production_coverage_section(
495 out: &mut String,
496 report: &crate::health_types::HealthReport,
497 root: &Path,
498) {
499 let Some(ref production) = report.production_coverage else {
500 return;
501 };
502 if !out.is_empty() && !out.ends_with("\n\n") {
506 out.push('\n');
507 }
508 let _ = writeln!(
509 out,
510 "## Production Coverage\n\n- Verdict: {}\n- Functions tracked: {}\n- Hit: {}\n- Unhit: {}\n- Untracked: {}\n- Coverage: {:.1}%\n- Traces observed: {}\n- Period: {} day(s), {} deployment(s)\n",
511 production.verdict,
512 production.summary.functions_tracked,
513 production.summary.functions_hit,
514 production.summary.functions_unhit,
515 production.summary.functions_untracked,
516 production.summary.coverage_percent,
517 production.summary.trace_count,
518 production.summary.period_days,
519 production.summary.deployments_seen,
520 );
521 if let Some(watermark) = production.watermark {
522 let _ = writeln!(out, "- Watermark: {watermark}\n");
523 }
524 if let Some(ref quality) = production.summary.capture_quality
525 && quality.lazy_parse_warning
526 {
527 let window = super::human::health::format_window(quality.window_seconds);
528 let _ = writeln!(
529 out,
530 "- Capture quality: short window ({} from {} instance(s), {:.1}% of functions untracked); lazy-parsed scripts may not appear.\n",
531 window, quality.instances_observed, quality.untracked_ratio_percent,
532 );
533 }
534 let rel = |p: &Path| {
535 escape_backticks(&normalize_uri(
536 &relative_path(p, root).display().to_string(),
537 ))
538 };
539 if !production.findings.is_empty() {
540 out.push_str("| ID | Path | Function | Verdict | Invocations | Confidence |\n");
541 out.push_str("|:---|:-----|:---------|:--------|------------:|:-----------|\n");
542 for finding in &production.findings {
543 let invocations = finding
544 .invocations
545 .map_or_else(|| "—".to_owned(), |hits| hits.to_string());
546 let _ = writeln!(
547 out,
548 "| `{}` | `{}`:{} | `{}` | {} | {} | {} |",
549 escape_backticks(&finding.id),
550 rel(&finding.path),
551 finding.line,
552 escape_backticks(&finding.function),
553 finding.verdict,
554 invocations,
555 finding.confidence,
556 );
557 }
558 out.push('\n');
559 }
560 if !production.hot_paths.is_empty() {
561 out.push_str("| ID | Hot path | Function | Invocations | Percentile |\n");
562 out.push_str("|:---|:---------|:---------|------------:|-----------:|\n");
563 for entry in &production.hot_paths {
564 let _ = writeln!(
565 out,
566 "| `{}` | `{}`:{} | `{}` | {} | {} |",
567 escape_backticks(&entry.id),
568 rel(&entry.path),
569 entry.line,
570 escape_backticks(&entry.function),
571 entry.invocations,
572 entry.percentile,
573 );
574 }
575 out.push('\n');
576 }
577}
578
579fn write_trend_section(out: &mut String, report: &crate::health_types::HealthReport) {
581 let Some(ref trend) = report.health_trend else {
582 return;
583 };
584 let sha_str = trend
585 .compared_to
586 .git_sha
587 .as_deref()
588 .map_or(String::new(), |sha| format!(" ({sha})"));
589 let _ = writeln!(
590 out,
591 "## Trend (vs {}{})\n",
592 trend
593 .compared_to
594 .timestamp
595 .get(..10)
596 .unwrap_or(&trend.compared_to.timestamp),
597 sha_str,
598 );
599 out.push_str("| Metric | Previous | Current | Delta | Direction |\n");
600 out.push_str("|:-------|:---------|:--------|:------|:----------|\n");
601 for m in &trend.metrics {
602 let fmt_val = |v: f64| -> String {
603 if m.unit == "%" {
604 format!("{v:.1}%")
605 } else if (v - v.round()).abs() < 0.05 {
606 format!("{v:.0}")
607 } else {
608 format!("{v:.1}")
609 }
610 };
611 let prev = fmt_val(m.previous);
612 let cur = fmt_val(m.current);
613 let delta = if m.unit == "%" {
614 format!("{:+.1}%", m.delta)
615 } else if (m.delta - m.delta.round()).abs() < 0.05 {
616 format!("{:+.0}", m.delta)
617 } else {
618 format!("{:+.1}", m.delta)
619 };
620 let _ = writeln!(
621 out,
622 "| {} | {} | {} | {} | {} {} |",
623 m.label,
624 prev,
625 cur,
626 delta,
627 m.direction.arrow(),
628 m.direction.label(),
629 );
630 }
631 let md_sha = trend
632 .compared_to
633 .git_sha
634 .as_deref()
635 .map_or(String::new(), |sha| format!(" ({sha})"));
636 let _ = writeln!(
637 out,
638 "\n*vs {}{} · {} {} available*\n",
639 trend
640 .compared_to
641 .timestamp
642 .get(..10)
643 .unwrap_or(&trend.compared_to.timestamp),
644 md_sha,
645 trend.snapshots_loaded,
646 if trend.snapshots_loaded == 1 {
647 "snapshot"
648 } else {
649 "snapshots"
650 },
651 );
652}
653
654fn write_vital_signs_section(out: &mut String, report: &crate::health_types::HealthReport) {
656 let Some(ref vs) = report.vital_signs else {
657 return;
658 };
659 out.push_str("## Vital Signs\n\n");
660 out.push_str("| Metric | Value |\n");
661 out.push_str("|:-------|------:|\n");
662 if vs.total_loc > 0 {
663 let _ = writeln!(out, "| Total LOC | {} |", vs.total_loc);
664 }
665 let _ = writeln!(out, "| Avg Cyclomatic | {:.1} |", vs.avg_cyclomatic);
666 let _ = writeln!(out, "| P90 Cyclomatic | {} |", vs.p90_cyclomatic);
667 if let Some(v) = vs.dead_file_pct {
668 let _ = writeln!(out, "| Dead Files | {v:.1}% |");
669 }
670 if let Some(v) = vs.dead_export_pct {
671 let _ = writeln!(out, "| Dead Exports | {v:.1}% |");
672 }
673 if let Some(v) = vs.maintainability_avg {
674 let _ = writeln!(out, "| Maintainability (avg) | {v:.1} |");
675 }
676 if let Some(v) = vs.hotspot_count {
677 let _ = writeln!(out, "| Hotspots | {v} |");
678 }
679 if let Some(v) = vs.circular_dep_count {
680 let _ = writeln!(out, "| Circular Deps | {v} |");
681 }
682 if let Some(v) = vs.unused_dep_count {
683 let _ = writeln!(out, "| Unused Deps | {v} |");
684 }
685 out.push('\n');
686}
687
688fn write_findings_section(
690 out: &mut String,
691 report: &crate::health_types::HealthReport,
692 root: &Path,
693) {
694 if report.findings.is_empty() {
695 return;
696 }
697
698 let rel = |p: &Path| {
699 escape_backticks(&normalize_uri(
700 &relative_path(p, root).display().to_string(),
701 ))
702 };
703
704 let count = report.summary.functions_above_threshold;
705 let shown = report.findings.len();
706 if shown < count {
707 let _ = write!(
708 out,
709 "## Fallow: {count} high complexity function{} ({shown} shown)\n\n",
710 plural(count),
711 );
712 } else {
713 let _ = write!(
714 out,
715 "## Fallow: {count} high complexity function{}\n\n",
716 plural(count),
717 );
718 }
719
720 out.push_str("| File | Function | Severity | Cyclomatic | Cognitive | CRAP | Lines |\n");
721 out.push_str("|:-----|:---------|:---------|:-----------|:----------|:-----|:------|\n");
722
723 for finding in &report.findings {
724 let file_str = rel(&finding.path);
725 let cyc_marker = if finding.cyclomatic > report.summary.max_cyclomatic_threshold {
726 " **!**"
727 } else {
728 ""
729 };
730 let cog_marker = if finding.cognitive > report.summary.max_cognitive_threshold {
731 " **!**"
732 } else {
733 ""
734 };
735 let severity_label = match finding.severity {
736 crate::health_types::FindingSeverity::Critical => "critical",
737 crate::health_types::FindingSeverity::High => "high",
738 crate::health_types::FindingSeverity::Moderate => "moderate",
739 };
740 let crap_cell = match finding.crap {
741 Some(crap) => {
742 let marker = if crap >= report.summary.max_crap_threshold {
743 " **!**"
744 } else {
745 ""
746 };
747 format!("{crap:.1}{marker}")
748 }
749 None => "-".to_string(),
750 };
751 let _ = writeln!(
752 out,
753 "| `{file_str}:{line}` | `{name}` | {severity_label} | {cyc}{cyc_marker} | {cog}{cog_marker} | {crap_cell} | {lines} |",
754 line = finding.line,
755 name = escape_backticks(&finding.name),
756 cyc = finding.cyclomatic,
757 cog = finding.cognitive,
758 lines = finding.line_count,
759 );
760 }
761
762 let s = &report.summary;
763 let _ = write!(
764 out,
765 "\n**{files}** files, **{funcs}** functions analyzed \
766 (thresholds: cyclomatic > {cyc}, cognitive > {cog}, CRAP >= {crap:.1})\n",
767 files = s.files_analyzed,
768 funcs = s.functions_analyzed,
769 cyc = s.max_cyclomatic_threshold,
770 cog = s.max_cognitive_threshold,
771 crap = s.max_crap_threshold,
772 );
773}
774
775fn write_file_scores_section(
777 out: &mut String,
778 report: &crate::health_types::HealthReport,
779 root: &Path,
780) {
781 if report.file_scores.is_empty() {
782 return;
783 }
784
785 let rel = |p: &Path| {
786 escape_backticks(&normalize_uri(
787 &relative_path(p, root).display().to_string(),
788 ))
789 };
790
791 out.push('\n');
792 let _ = writeln!(
793 out,
794 "### File Health Scores ({} files)\n",
795 report.file_scores.len(),
796 );
797 out.push_str("| File | Maintainability | Fan-in | Fan-out | Dead Code | Density | Risk |\n");
798 out.push_str("|:-----|:---------------|:-------|:--------|:----------|:--------|:-----|\n");
799
800 for score in &report.file_scores {
801 let file_str = rel(&score.path);
802 let _ = writeln!(
803 out,
804 "| `{file_str}` | {mi:.1} | {fi} | {fan_out} | {dead:.0}% | {density:.2} | {crap:.1} |",
805 mi = score.maintainability_index,
806 fi = score.fan_in,
807 fan_out = score.fan_out,
808 dead = score.dead_code_ratio * 100.0,
809 density = score.complexity_density,
810 crap = score.crap_max,
811 );
812 }
813
814 if let Some(avg) = report.summary.average_maintainability {
815 let _ = write!(out, "\n**Average maintainability index:** {avg:.1}/100\n");
816 }
817}
818
819fn write_coverage_gaps_section(
820 out: &mut String,
821 report: &crate::health_types::HealthReport,
822 root: &Path,
823) {
824 let Some(ref gaps) = report.coverage_gaps else {
825 return;
826 };
827
828 out.push('\n');
829 let _ = writeln!(out, "### Coverage Gaps\n");
830 let _ = writeln!(
831 out,
832 "*{} untested files · {} untested exports · {:.1}% file coverage*\n",
833 gaps.summary.untested_files, gaps.summary.untested_exports, gaps.summary.file_coverage_pct,
834 );
835
836 if gaps.files.is_empty() && gaps.exports.is_empty() {
837 out.push_str("_No coverage gaps found in scope._\n");
838 return;
839 }
840
841 if !gaps.files.is_empty() {
842 out.push_str("#### Files\n");
843 for item in &gaps.files {
844 let file_str = escape_backticks(&normalize_uri(
845 &relative_path(&item.path, root).display().to_string(),
846 ));
847 let _ = writeln!(
848 out,
849 "- `{file_str}` ({count} value export{})",
850 if item.value_export_count == 1 {
851 ""
852 } else {
853 "s"
854 },
855 count = item.value_export_count,
856 );
857 }
858 out.push('\n');
859 }
860
861 if !gaps.exports.is_empty() {
862 out.push_str("#### Exports\n");
863 for item in &gaps.exports {
864 let file_str = escape_backticks(&normalize_uri(
865 &relative_path(&item.path, root).display().to_string(),
866 ));
867 let _ = writeln!(out, "- `{file_str}`:{} `{}`", item.line, item.export_name);
868 }
869 }
870}
871
872fn ownership_md_cells(
877 ownership: Option<&crate::health_types::OwnershipMetrics>,
878) -> (String, String, String, String) {
879 let Some(o) = ownership else {
880 let dash = "\u{2013}".to_string();
881 return (dash.clone(), dash.clone(), dash.clone(), dash);
882 };
883 let bus = o.bus_factor.to_string();
884 let top = format!(
885 "`{}` ({:.0}%)",
886 o.top_contributor.identifier,
887 o.top_contributor.share * 100.0,
888 );
889 let owner = o
890 .declared_owner
891 .as_deref()
892 .map_or_else(|| "\u{2013}".to_string(), str::to_string);
893 let mut notes: Vec<&str> = Vec::new();
894 if o.unowned == Some(true) {
895 notes.push("**unowned**");
896 }
897 if o.drift {
898 notes.push("drift");
899 }
900 let notes_str = if notes.is_empty() {
901 "\u{2013}".to_string()
902 } else {
903 notes.join(", ")
904 };
905 (bus, top, owner, notes_str)
906}
907
908fn write_hotspots_section(
909 out: &mut String,
910 report: &crate::health_types::HealthReport,
911 root: &Path,
912) {
913 if report.hotspots.is_empty() {
914 return;
915 }
916
917 let rel = |p: &Path| {
918 escape_backticks(&normalize_uri(
919 &relative_path(p, root).display().to_string(),
920 ))
921 };
922
923 out.push('\n');
924 let header = report.hotspot_summary.as_ref().map_or_else(
925 || format!("### Hotspots ({} files)\n", report.hotspots.len()),
926 |summary| {
927 format!(
928 "### Hotspots ({} files, since {})\n",
929 report.hotspots.len(),
930 summary.since,
931 )
932 },
933 );
934 let _ = writeln!(out, "{header}");
935 let any_ownership = report.hotspots.iter().any(|e| e.ownership.is_some());
937 if any_ownership {
938 out.push_str(
939 "| File | Score | Commits | Churn | Density | Fan-in | Trend | Bus | Top | Owner | Notes |\n"
940 );
941 out.push_str(
942 "|:-----|:------|:--------|:------|:--------|:-------|:------|:----|:----|:------|:------|\n"
943 );
944 } else {
945 out.push_str("| File | Score | Commits | Churn | Density | Fan-in | Trend |\n");
946 out.push_str("|:-----|:------|:--------|:------|:--------|:-------|:------|\n");
947 }
948
949 for entry in &report.hotspots {
950 let file_str = rel(&entry.path);
951 if any_ownership {
952 let (bus, top, owner, notes) = ownership_md_cells(entry.ownership.as_ref());
953 let _ = writeln!(
954 out,
955 "| `{file_str}` | {score:.1} | {commits} | {churn} | {density:.2} | {fi} | {trend} | {bus} | {top} | {owner} | {notes} |",
956 score = entry.score,
957 commits = entry.commits,
958 churn = entry.lines_added + entry.lines_deleted,
959 density = entry.complexity_density,
960 fi = entry.fan_in,
961 trend = entry.trend,
962 );
963 } else {
964 let _ = writeln!(
965 out,
966 "| `{file_str}` | {score:.1} | {commits} | {churn} | {density:.2} | {fi} | {trend} |",
967 score = entry.score,
968 commits = entry.commits,
969 churn = entry.lines_added + entry.lines_deleted,
970 density = entry.complexity_density,
971 fi = entry.fan_in,
972 trend = entry.trend,
973 );
974 }
975 }
976
977 if let Some(ref summary) = report.hotspot_summary
978 && summary.files_excluded > 0
979 {
980 let _ = write!(
981 out,
982 "\n*{} file{} excluded (< {} commits)*\n",
983 summary.files_excluded,
984 plural(summary.files_excluded),
985 summary.min_commits,
986 );
987 }
988}
989
990fn write_targets_section(
992 out: &mut String,
993 report: &crate::health_types::HealthReport,
994 root: &Path,
995) {
996 if report.targets.is_empty() {
997 return;
998 }
999 let _ = write!(
1000 out,
1001 "\n### Refactoring Targets ({})\n\n",
1002 report.targets.len()
1003 );
1004 out.push_str("| Efficiency | Category | Effort / Confidence | File | Recommendation |\n");
1005 out.push_str("|:-----------|:---------|:--------------------|:-----|:---------------|\n");
1006 for target in &report.targets {
1007 let file_str = normalize_uri(&relative_path(&target.path, root).display().to_string());
1008 let category = target.category.label();
1009 let effort = target.effort.label();
1010 let confidence = target.confidence.label();
1011 let _ = writeln!(
1012 out,
1013 "| {:.1} | {category} | {effort} / {confidence} | `{file_str}` | {} |",
1014 target.efficiency, target.recommendation,
1015 );
1016 }
1017}
1018
1019fn write_metric_legend(out: &mut String, report: &crate::health_types::HealthReport) {
1021 let has_scores = !report.file_scores.is_empty();
1022 let has_coverage = report.coverage_gaps.is_some();
1023 let has_hotspots = !report.hotspots.is_empty();
1024 let has_targets = !report.targets.is_empty();
1025 if !has_scores && !has_coverage && !has_hotspots && !has_targets {
1026 return;
1027 }
1028 out.push_str("\n---\n\n<details><summary>Metric definitions</summary>\n\n");
1029 if has_scores {
1030 out.push_str("- **MI** — Maintainability Index (0\u{2013}100, higher is better)\n");
1031 out.push_str("- **Fan-in** — files that import this file (blast radius)\n");
1032 out.push_str("- **Fan-out** — files this file imports (coupling)\n");
1033 out.push_str("- **Dead Code** — % of value exports with zero references\n");
1034 out.push_str("- **Density** — cyclomatic complexity / lines of code\n");
1035 }
1036 if has_coverage {
1037 out.push_str(
1038 "- **File coverage** — runtime files also reachable from a discovered test root\n",
1039 );
1040 out.push_str("- **Untested export** — export with no reference chain from any test-reachable module\n");
1041 }
1042 if has_hotspots {
1043 out.push_str("- **Score** — churn \u{00d7} complexity (0\u{2013}100, higher = riskier)\n");
1044 out.push_str("- **Commits** — commits in the analysis window\n");
1045 out.push_str("- **Churn** — total lines added + deleted\n");
1046 out.push_str("- **Trend** — accelerating / stable / cooling\n");
1047 }
1048 if has_targets {
1049 out.push_str("- **Efficiency** — priority / effort (higher = better quick-win value, default sort)\n");
1050 out.push_str("- **Category** — recommendation type (churn+complexity, high impact, dead code, complexity, coupling, circular dep)\n");
1051 out.push_str("- **Effort** — estimated effort (low / medium / high) based on file size, function count, and fan-in\n");
1052 out.push_str("- **Confidence** — recommendation reliability (high = deterministic analysis, medium = heuristic, low = git-dependent)\n");
1053 }
1054 out.push_str(
1055 "\n[Full metric reference](https://docs.fallow.tools/explanations/metrics)\n\n</details>\n",
1056 );
1057}
1058
1059#[cfg(test)]
1060mod tests {
1061 use super::*;
1062 use crate::report::test_helpers::sample_results;
1063 use fallow_core::duplicates::{
1064 CloneFamily, CloneGroup, CloneInstance, DuplicationReport, DuplicationStats,
1065 RefactoringKind, RefactoringSuggestion,
1066 };
1067 use fallow_core::results::*;
1068 use std::path::PathBuf;
1069
1070 #[test]
1071 fn markdown_empty_results_no_issues() {
1072 let root = PathBuf::from("/project");
1073 let results = AnalysisResults::default();
1074 let md = build_markdown(&results, &root);
1075 assert_eq!(md, "## Fallow: no issues found\n");
1076 }
1077
1078 #[test]
1079 fn markdown_contains_header_with_count() {
1080 let root = PathBuf::from("/project");
1081 let results = sample_results(&root);
1082 let md = build_markdown(&results, &root);
1083 assert!(md.starts_with(&format!(
1084 "## Fallow: {} issues found\n",
1085 results.total_issues()
1086 )));
1087 }
1088
1089 #[test]
1090 fn markdown_contains_all_sections() {
1091 let root = PathBuf::from("/project");
1092 let results = sample_results(&root);
1093 let md = build_markdown(&results, &root);
1094
1095 assert!(md.contains("### Unused files (1)"));
1096 assert!(md.contains("### Unused exports (1)"));
1097 assert!(md.contains("### Unused type exports (1)"));
1098 assert!(md.contains("### Unused dependencies (1)"));
1099 assert!(md.contains("### Unused devDependencies (1)"));
1100 assert!(md.contains("### Unused enum members (1)"));
1101 assert!(md.contains("### Unused class members (1)"));
1102 assert!(md.contains("### Unresolved imports (1)"));
1103 assert!(md.contains("### Unlisted dependencies (1)"));
1104 assert!(md.contains("### Duplicate exports (1)"));
1105 assert!(md.contains("### Type-only dependencies"));
1106 assert!(md.contains("### Test-only production dependencies"));
1107 assert!(md.contains("### Circular dependencies (1)"));
1108 }
1109
1110 #[test]
1111 fn markdown_unused_file_format() {
1112 let root = PathBuf::from("/project");
1113 let mut results = AnalysisResults::default();
1114 results.unused_files.push(UnusedFile {
1115 path: root.join("src/dead.ts"),
1116 });
1117 let md = build_markdown(&results, &root);
1118 assert!(md.contains("- `src/dead.ts`"));
1119 }
1120
1121 #[test]
1122 fn markdown_unused_export_grouped_by_file() {
1123 let root = PathBuf::from("/project");
1124 let mut results = AnalysisResults::default();
1125 results.unused_exports.push(UnusedExport {
1126 path: root.join("src/utils.ts"),
1127 export_name: "helperFn".to_string(),
1128 is_type_only: false,
1129 line: 10,
1130 col: 4,
1131 span_start: 120,
1132 is_re_export: false,
1133 });
1134 let md = build_markdown(&results, &root);
1135 assert!(md.contains("- `src/utils.ts`"));
1136 assert!(md.contains(":10 `helperFn`"));
1137 }
1138
1139 #[test]
1140 fn markdown_re_export_tagged() {
1141 let root = PathBuf::from("/project");
1142 let mut results = AnalysisResults::default();
1143 results.unused_exports.push(UnusedExport {
1144 path: root.join("src/index.ts"),
1145 export_name: "reExported".to_string(),
1146 is_type_only: false,
1147 line: 1,
1148 col: 0,
1149 span_start: 0,
1150 is_re_export: true,
1151 });
1152 let md = build_markdown(&results, &root);
1153 assert!(md.contains("(re-export)"));
1154 }
1155
1156 #[test]
1157 fn markdown_unused_dep_format() {
1158 let root = PathBuf::from("/project");
1159 let mut results = AnalysisResults::default();
1160 results.unused_dependencies.push(UnusedDependency {
1161 package_name: "lodash".to_string(),
1162 location: DependencyLocation::Dependencies,
1163 path: root.join("package.json"),
1164 line: 5,
1165 });
1166 let md = build_markdown(&results, &root);
1167 assert!(md.contains("- `lodash`"));
1168 }
1169
1170 #[test]
1171 fn markdown_circular_dep_format() {
1172 let root = PathBuf::from("/project");
1173 let mut results = AnalysisResults::default();
1174 results.circular_dependencies.push(CircularDependency {
1175 files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
1176 length: 2,
1177 line: 3,
1178 col: 0,
1179 is_cross_package: false,
1180 });
1181 let md = build_markdown(&results, &root);
1182 assert!(md.contains("`src/a.ts`"));
1183 assert!(md.contains("`src/b.ts`"));
1184 assert!(md.contains("\u{2192}"));
1185 }
1186
1187 #[test]
1188 fn markdown_strips_root_prefix() {
1189 let root = PathBuf::from("/project");
1190 let mut results = AnalysisResults::default();
1191 results.unused_files.push(UnusedFile {
1192 path: PathBuf::from("/project/src/deep/nested/file.ts"),
1193 });
1194 let md = build_markdown(&results, &root);
1195 assert!(md.contains("`src/deep/nested/file.ts`"));
1196 assert!(!md.contains("/project/"));
1197 }
1198
1199 #[test]
1200 fn markdown_single_issue_no_plural() {
1201 let root = PathBuf::from("/project");
1202 let mut results = AnalysisResults::default();
1203 results.unused_files.push(UnusedFile {
1204 path: root.join("src/dead.ts"),
1205 });
1206 let md = build_markdown(&results, &root);
1207 assert!(md.starts_with("## Fallow: 1 issue found\n"));
1208 }
1209
1210 #[test]
1211 fn markdown_type_only_dep_format() {
1212 let root = PathBuf::from("/project");
1213 let mut results = AnalysisResults::default();
1214 results.type_only_dependencies.push(TypeOnlyDependency {
1215 package_name: "zod".to_string(),
1216 path: root.join("package.json"),
1217 line: 8,
1218 });
1219 let md = build_markdown(&results, &root);
1220 assert!(md.contains("### Type-only dependencies"));
1221 assert!(md.contains("- `zod`"));
1222 }
1223
1224 #[test]
1225 fn markdown_escapes_backticks_in_export_names() {
1226 let root = PathBuf::from("/project");
1227 let mut results = AnalysisResults::default();
1228 results.unused_exports.push(UnusedExport {
1229 path: root.join("src/utils.ts"),
1230 export_name: "foo`bar".to_string(),
1231 is_type_only: false,
1232 line: 1,
1233 col: 0,
1234 span_start: 0,
1235 is_re_export: false,
1236 });
1237 let md = build_markdown(&results, &root);
1238 assert!(md.contains("foo\\`bar"));
1239 assert!(!md.contains("foo`bar`"));
1240 }
1241
1242 #[test]
1243 fn markdown_escapes_backticks_in_package_names() {
1244 let root = PathBuf::from("/project");
1245 let mut results = AnalysisResults::default();
1246 results.unused_dependencies.push(UnusedDependency {
1247 package_name: "pkg`name".to_string(),
1248 location: DependencyLocation::Dependencies,
1249 path: root.join("package.json"),
1250 line: 5,
1251 });
1252 let md = build_markdown(&results, &root);
1253 assert!(md.contains("pkg\\`name"));
1254 }
1255
1256 #[test]
1259 fn duplication_markdown_empty() {
1260 let report = DuplicationReport::default();
1261 let root = PathBuf::from("/project");
1262 let md = build_duplication_markdown(&report, &root);
1263 assert_eq!(md, "## Fallow: no code duplication found\n");
1264 }
1265
1266 #[test]
1267 fn duplication_markdown_contains_groups() {
1268 let root = PathBuf::from("/project");
1269 let report = DuplicationReport {
1270 clone_groups: vec![CloneGroup {
1271 instances: vec![
1272 CloneInstance {
1273 file: root.join("src/a.ts"),
1274 start_line: 1,
1275 end_line: 10,
1276 start_col: 0,
1277 end_col: 0,
1278 fragment: String::new(),
1279 },
1280 CloneInstance {
1281 file: root.join("src/b.ts"),
1282 start_line: 5,
1283 end_line: 14,
1284 start_col: 0,
1285 end_col: 0,
1286 fragment: String::new(),
1287 },
1288 ],
1289 token_count: 50,
1290 line_count: 10,
1291 }],
1292 clone_families: vec![],
1293 mirrored_directories: vec![],
1294 stats: DuplicationStats {
1295 total_files: 10,
1296 files_with_clones: 2,
1297 total_lines: 500,
1298 duplicated_lines: 20,
1299 total_tokens: 2500,
1300 duplicated_tokens: 100,
1301 clone_groups: 1,
1302 clone_instances: 2,
1303 duplication_percentage: 4.0,
1304 },
1305 };
1306 let md = build_duplication_markdown(&report, &root);
1307 assert!(md.contains("**Clone group 1**"));
1308 assert!(md.contains("`src/a.ts:1-10`"));
1309 assert!(md.contains("`src/b.ts:5-14`"));
1310 assert!(md.contains("4.0% duplication"));
1311 }
1312
1313 #[test]
1314 fn duplication_markdown_contains_families() {
1315 let root = PathBuf::from("/project");
1316 let report = DuplicationReport {
1317 clone_groups: vec![CloneGroup {
1318 instances: vec![CloneInstance {
1319 file: root.join("src/a.ts"),
1320 start_line: 1,
1321 end_line: 5,
1322 start_col: 0,
1323 end_col: 0,
1324 fragment: String::new(),
1325 }],
1326 token_count: 30,
1327 line_count: 5,
1328 }],
1329 clone_families: vec![CloneFamily {
1330 files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
1331 groups: vec![],
1332 total_duplicated_lines: 20,
1333 total_duplicated_tokens: 100,
1334 suggestions: vec![RefactoringSuggestion {
1335 kind: RefactoringKind::ExtractFunction,
1336 description: "Extract shared utility function".to_string(),
1337 estimated_savings: 15,
1338 }],
1339 }],
1340 mirrored_directories: vec![],
1341 stats: DuplicationStats {
1342 clone_groups: 1,
1343 clone_instances: 1,
1344 duplication_percentage: 2.0,
1345 ..Default::default()
1346 },
1347 };
1348 let md = build_duplication_markdown(&report, &root);
1349 assert!(md.contains("### Clone Families"));
1350 assert!(md.contains("**Family 1**"));
1351 assert!(md.contains("Extract shared utility function"));
1352 assert!(md.contains("~15 lines saved"));
1353 }
1354
1355 #[test]
1358 fn health_markdown_empty_no_findings() {
1359 let root = PathBuf::from("/project");
1360 let report = crate::health_types::HealthReport {
1361 summary: crate::health_types::HealthSummary {
1362 files_analyzed: 10,
1363 functions_analyzed: 50,
1364 ..Default::default()
1365 },
1366 ..Default::default()
1367 };
1368 let md = build_health_markdown(&report, &root);
1369 assert!(md.contains("no functions exceed complexity thresholds"));
1370 assert!(md.contains("**50** functions analyzed"));
1371 }
1372
1373 #[test]
1374 fn health_markdown_table_format() {
1375 let root = PathBuf::from("/project");
1376 let report = crate::health_types::HealthReport {
1377 findings: vec![crate::health_types::HealthFinding {
1378 path: root.join("src/utils.ts"),
1379 name: "parseExpression".to_string(),
1380 line: 42,
1381 col: 0,
1382 cyclomatic: 25,
1383 cognitive: 30,
1384 line_count: 80,
1385 param_count: 0,
1386 exceeded: crate::health_types::ExceededThreshold::Both,
1387 severity: crate::health_types::FindingSeverity::High,
1388 crap: None,
1389 coverage_pct: None,
1390 }],
1391 summary: crate::health_types::HealthSummary {
1392 files_analyzed: 10,
1393 functions_analyzed: 50,
1394 functions_above_threshold: 1,
1395 ..Default::default()
1396 },
1397 ..Default::default()
1398 };
1399 let md = build_health_markdown(&report, &root);
1400 assert!(md.contains("## Fallow: 1 high complexity function\n"));
1401 assert!(md.contains("| File | Function |"));
1402 assert!(md.contains("`src/utils.ts:42`"));
1403 assert!(md.contains("`parseExpression`"));
1404 assert!(md.contains("25 **!**"));
1405 assert!(md.contains("30 **!**"));
1406 assert!(md.contains("| 80 |"));
1407 assert!(md.contains("| - |"));
1409 }
1410
1411 #[test]
1412 fn health_markdown_crap_column_shows_score_and_marker() {
1413 let root = PathBuf::from("/project");
1414 let report = crate::health_types::HealthReport {
1415 findings: vec![crate::health_types::HealthFinding {
1416 path: root.join("src/risky.ts"),
1417 name: "branchy".to_string(),
1418 line: 1,
1419 col: 0,
1420 cyclomatic: 67,
1421 cognitive: 10,
1422 line_count: 80,
1423 param_count: 1,
1424 exceeded: crate::health_types::ExceededThreshold::CyclomaticCrap,
1425 severity: crate::health_types::FindingSeverity::Critical,
1426 crap: Some(182.0),
1427 coverage_pct: None,
1428 }],
1429 summary: crate::health_types::HealthSummary {
1430 files_analyzed: 1,
1431 functions_analyzed: 1,
1432 functions_above_threshold: 1,
1433 ..Default::default()
1434 },
1435 ..Default::default()
1436 };
1437 let md = build_health_markdown(&report, &root);
1438 assert!(
1439 md.contains("| CRAP |"),
1440 "markdown table should have CRAP column header: {md}"
1441 );
1442 assert!(
1443 md.contains("182.0 **!**"),
1444 "CRAP value should be rendered with a threshold marker: {md}"
1445 );
1446 assert!(
1447 md.contains("CRAP >="),
1448 "trailing summary line should reference the CRAP threshold: {md}"
1449 );
1450 }
1451
1452 #[test]
1453 fn health_markdown_no_marker_when_below_threshold() {
1454 let root = PathBuf::from("/project");
1455 let report = crate::health_types::HealthReport {
1456 findings: vec![crate::health_types::HealthFinding {
1457 path: root.join("src/utils.ts"),
1458 name: "helper".to_string(),
1459 line: 10,
1460 col: 0,
1461 cyclomatic: 15,
1462 cognitive: 20,
1463 line_count: 30,
1464 param_count: 0,
1465 exceeded: crate::health_types::ExceededThreshold::Cognitive,
1466 severity: crate::health_types::FindingSeverity::High,
1467 crap: None,
1468 coverage_pct: None,
1469 }],
1470 summary: crate::health_types::HealthSummary {
1471 files_analyzed: 5,
1472 functions_analyzed: 20,
1473 functions_above_threshold: 1,
1474 ..Default::default()
1475 },
1476 ..Default::default()
1477 };
1478 let md = build_health_markdown(&report, &root);
1479 assert!(md.contains("| 15 |"));
1481 assert!(md.contains("20 **!**"));
1483 }
1484
1485 #[test]
1486 fn health_markdown_with_targets() {
1487 use crate::health_types::*;
1488
1489 let root = PathBuf::from("/project");
1490 let report = HealthReport {
1491 summary: HealthSummary {
1492 files_analyzed: 10,
1493 functions_analyzed: 50,
1494 ..Default::default()
1495 },
1496 targets: vec![
1497 RefactoringTarget {
1498 path: PathBuf::from("/project/src/complex.ts"),
1499 priority: 82.5,
1500 efficiency: 27.5,
1501 recommendation: "Split high-impact file".into(),
1502 category: RecommendationCategory::SplitHighImpact,
1503 effort: crate::health_types::EffortEstimate::High,
1504 confidence: crate::health_types::Confidence::Medium,
1505 factors: vec![ContributingFactor {
1506 metric: "fan_in",
1507 value: 25.0,
1508 threshold: 10.0,
1509 detail: "25 files depend on this".into(),
1510 }],
1511 evidence: None,
1512 },
1513 RefactoringTarget {
1514 path: PathBuf::from("/project/src/legacy.ts"),
1515 priority: 45.0,
1516 efficiency: 45.0,
1517 recommendation: "Remove 5 unused exports".into(),
1518 category: RecommendationCategory::RemoveDeadCode,
1519 effort: crate::health_types::EffortEstimate::Low,
1520 confidence: crate::health_types::Confidence::High,
1521 factors: vec![],
1522 evidence: None,
1523 },
1524 ],
1525 ..Default::default()
1526 };
1527 let md = build_health_markdown(&report, &root);
1528
1529 assert!(
1531 md.contains("Refactoring Targets"),
1532 "should contain targets heading"
1533 );
1534 assert!(
1535 md.contains("src/complex.ts"),
1536 "should contain target file path"
1537 );
1538 assert!(md.contains("27.5"), "should contain efficiency score");
1539 assert!(
1540 md.contains("Split high-impact file"),
1541 "should contain recommendation"
1542 );
1543 assert!(md.contains("src/legacy.ts"), "should contain second target");
1544 }
1545
1546 #[test]
1547 fn health_markdown_with_coverage_gaps() {
1548 use crate::health_types::*;
1549
1550 let root = PathBuf::from("/project");
1551 let report = HealthReport {
1552 summary: HealthSummary {
1553 files_analyzed: 10,
1554 functions_analyzed: 50,
1555 ..Default::default()
1556 },
1557 coverage_gaps: Some(CoverageGaps {
1558 summary: CoverageGapSummary {
1559 runtime_files: 2,
1560 covered_files: 0,
1561 file_coverage_pct: 0.0,
1562 untested_files: 1,
1563 untested_exports: 1,
1564 },
1565 files: vec![UntestedFile {
1566 path: root.join("src/app.ts"),
1567 value_export_count: 2,
1568 }],
1569 exports: vec![UntestedExport {
1570 path: root.join("src/app.ts"),
1571 export_name: "loader".into(),
1572 line: 12,
1573 col: 4,
1574 }],
1575 }),
1576 ..Default::default()
1577 };
1578
1579 let md = build_health_markdown(&report, &root);
1580 assert!(md.contains("### Coverage Gaps"));
1581 assert!(md.contains("*1 untested files"));
1582 assert!(md.contains("`src/app.ts` (2 value exports)"));
1583 assert!(md.contains("`src/app.ts`:12 `loader`"));
1584 }
1585
1586 #[test]
1589 fn markdown_dep_in_workspace_shows_package_label() {
1590 let root = PathBuf::from("/project");
1591 let mut results = AnalysisResults::default();
1592 results.unused_dependencies.push(UnusedDependency {
1593 package_name: "lodash".to_string(),
1594 location: DependencyLocation::Dependencies,
1595 path: root.join("packages/core/package.json"),
1596 line: 5,
1597 });
1598 let md = build_markdown(&results, &root);
1599 assert!(md.contains("(packages/core/package.json)"));
1601 }
1602
1603 #[test]
1604 fn markdown_dep_at_root_no_extra_label() {
1605 let root = PathBuf::from("/project");
1606 let mut results = AnalysisResults::default();
1607 results.unused_dependencies.push(UnusedDependency {
1608 package_name: "lodash".to_string(),
1609 location: DependencyLocation::Dependencies,
1610 path: root.join("package.json"),
1611 line: 5,
1612 });
1613 let md = build_markdown(&results, &root);
1614 assert!(md.contains("- `lodash`"));
1615 assert!(!md.contains("(package.json)"));
1616 }
1617
1618 #[test]
1621 fn markdown_exports_grouped_by_file() {
1622 let root = PathBuf::from("/project");
1623 let mut results = AnalysisResults::default();
1624 results.unused_exports.push(UnusedExport {
1625 path: root.join("src/utils.ts"),
1626 export_name: "alpha".to_string(),
1627 is_type_only: false,
1628 line: 5,
1629 col: 0,
1630 span_start: 0,
1631 is_re_export: false,
1632 });
1633 results.unused_exports.push(UnusedExport {
1634 path: root.join("src/utils.ts"),
1635 export_name: "beta".to_string(),
1636 is_type_only: false,
1637 line: 10,
1638 col: 0,
1639 span_start: 0,
1640 is_re_export: false,
1641 });
1642 results.unused_exports.push(UnusedExport {
1643 path: root.join("src/other.ts"),
1644 export_name: "gamma".to_string(),
1645 is_type_only: false,
1646 line: 1,
1647 col: 0,
1648 span_start: 0,
1649 is_re_export: false,
1650 });
1651 let md = build_markdown(&results, &root);
1652 let utils_count = md.matches("- `src/utils.ts`").count();
1654 assert_eq!(utils_count, 1, "file header should appear once per file");
1655 assert!(md.contains(":5 `alpha`"));
1657 assert!(md.contains(":10 `beta`"));
1658 }
1659
1660 #[test]
1663 fn markdown_multiple_issues_plural() {
1664 let root = PathBuf::from("/project");
1665 let mut results = AnalysisResults::default();
1666 results.unused_files.push(UnusedFile {
1667 path: root.join("src/a.ts"),
1668 });
1669 results.unused_files.push(UnusedFile {
1670 path: root.join("src/b.ts"),
1671 });
1672 let md = build_markdown(&results, &root);
1673 assert!(md.starts_with("## Fallow: 2 issues found\n"));
1674 }
1675
1676 #[test]
1679 fn duplication_markdown_zero_savings_no_suffix() {
1680 let root = PathBuf::from("/project");
1681 let report = DuplicationReport {
1682 clone_groups: vec![CloneGroup {
1683 instances: vec![CloneInstance {
1684 file: root.join("src/a.ts"),
1685 start_line: 1,
1686 end_line: 5,
1687 start_col: 0,
1688 end_col: 0,
1689 fragment: String::new(),
1690 }],
1691 token_count: 30,
1692 line_count: 5,
1693 }],
1694 clone_families: vec![CloneFamily {
1695 files: vec![root.join("src/a.ts")],
1696 groups: vec![],
1697 total_duplicated_lines: 5,
1698 total_duplicated_tokens: 30,
1699 suggestions: vec![RefactoringSuggestion {
1700 kind: RefactoringKind::ExtractFunction,
1701 description: "Extract function".to_string(),
1702 estimated_savings: 0,
1703 }],
1704 }],
1705 mirrored_directories: vec![],
1706 stats: DuplicationStats {
1707 clone_groups: 1,
1708 clone_instances: 1,
1709 duplication_percentage: 1.0,
1710 ..Default::default()
1711 },
1712 };
1713 let md = build_duplication_markdown(&report, &root);
1714 assert!(md.contains("Extract function"));
1715 assert!(!md.contains("lines saved"));
1716 }
1717
1718 #[test]
1721 fn health_markdown_vital_signs_table() {
1722 let root = PathBuf::from("/project");
1723 let report = crate::health_types::HealthReport {
1724 summary: crate::health_types::HealthSummary {
1725 files_analyzed: 10,
1726 functions_analyzed: 50,
1727 ..Default::default()
1728 },
1729 vital_signs: Some(crate::health_types::VitalSigns {
1730 avg_cyclomatic: 3.5,
1731 p90_cyclomatic: 12,
1732 dead_file_pct: Some(5.0),
1733 dead_export_pct: Some(10.2),
1734 duplication_pct: None,
1735 maintainability_avg: Some(72.3),
1736 hotspot_count: Some(3),
1737 circular_dep_count: Some(1),
1738 unused_dep_count: Some(2),
1739 counts: None,
1740 unit_size_profile: None,
1741 unit_interfacing_profile: None,
1742 p95_fan_in: None,
1743 coupling_high_pct: None,
1744 total_loc: 15_200,
1745 }),
1746 ..Default::default()
1747 };
1748 let md = build_health_markdown(&report, &root);
1749 assert!(md.contains("## Vital Signs"));
1750 assert!(md.contains("| Metric | Value |"));
1751 assert!(md.contains("| Total LOC | 15200 |"));
1752 assert!(md.contains("| Avg Cyclomatic | 3.5 |"));
1753 assert!(md.contains("| P90 Cyclomatic | 12 |"));
1754 assert!(md.contains("| Dead Files | 5.0% |"));
1755 assert!(md.contains("| Dead Exports | 10.2% |"));
1756 assert!(md.contains("| Maintainability (avg) | 72.3 |"));
1757 assert!(md.contains("| Hotspots | 3 |"));
1758 assert!(md.contains("| Circular Deps | 1 |"));
1759 assert!(md.contains("| Unused Deps | 2 |"));
1760 }
1761
1762 #[test]
1765 fn health_markdown_file_scores_table() {
1766 let root = PathBuf::from("/project");
1767 let report = crate::health_types::HealthReport {
1768 findings: vec![crate::health_types::HealthFinding {
1769 path: root.join("src/dummy.ts"),
1770 name: "fn".to_string(),
1771 line: 1,
1772 col: 0,
1773 cyclomatic: 25,
1774 cognitive: 20,
1775 line_count: 50,
1776 param_count: 0,
1777 exceeded: crate::health_types::ExceededThreshold::Both,
1778 severity: crate::health_types::FindingSeverity::High,
1779 crap: None,
1780 coverage_pct: None,
1781 }],
1782 summary: crate::health_types::HealthSummary {
1783 files_analyzed: 5,
1784 functions_analyzed: 10,
1785 functions_above_threshold: 1,
1786 files_scored: Some(1),
1787 average_maintainability: Some(65.0),
1788 ..Default::default()
1789 },
1790 file_scores: vec![crate::health_types::FileHealthScore {
1791 path: root.join("src/utils.ts"),
1792 fan_in: 5,
1793 fan_out: 3,
1794 dead_code_ratio: 0.25,
1795 complexity_density: 0.8,
1796 maintainability_index: 72.5,
1797 total_cyclomatic: 40,
1798 total_cognitive: 30,
1799 function_count: 10,
1800 lines: 200,
1801 crap_max: 0.0,
1802 crap_above_threshold: 0,
1803 }],
1804 ..Default::default()
1805 };
1806 let md = build_health_markdown(&report, &root);
1807 assert!(md.contains("### File Health Scores (1 files)"));
1808 assert!(md.contains("| File | Maintainability | Fan-in | Fan-out | Dead Code | Density |"));
1809 assert!(md.contains("| `src/utils.ts` | 72.5 | 5 | 3 | 25% | 0.80 |"));
1810 assert!(md.contains("**Average maintainability index:** 65.0/100"));
1811 }
1812
1813 #[test]
1816 fn health_markdown_hotspots_table() {
1817 let root = PathBuf::from("/project");
1818 let report = crate::health_types::HealthReport {
1819 findings: vec![crate::health_types::HealthFinding {
1820 path: root.join("src/dummy.ts"),
1821 name: "fn".to_string(),
1822 line: 1,
1823 col: 0,
1824 cyclomatic: 25,
1825 cognitive: 20,
1826 line_count: 50,
1827 param_count: 0,
1828 exceeded: crate::health_types::ExceededThreshold::Both,
1829 severity: crate::health_types::FindingSeverity::High,
1830 crap: None,
1831 coverage_pct: None,
1832 }],
1833 summary: crate::health_types::HealthSummary {
1834 files_analyzed: 5,
1835 functions_analyzed: 10,
1836 functions_above_threshold: 1,
1837 ..Default::default()
1838 },
1839 hotspots: vec![crate::health_types::HotspotEntry {
1840 path: root.join("src/hot.ts"),
1841 score: 85.0,
1842 commits: 42,
1843 weighted_commits: 35.0,
1844 lines_added: 500,
1845 lines_deleted: 200,
1846 complexity_density: 1.2,
1847 fan_in: 10,
1848 trend: fallow_core::churn::ChurnTrend::Accelerating,
1849 ownership: None,
1850 is_test_path: false,
1851 }],
1852 hotspot_summary: Some(crate::health_types::HotspotSummary {
1853 since: "6 months".to_string(),
1854 min_commits: 3,
1855 files_analyzed: 50,
1856 files_excluded: 5,
1857 shallow_clone: false,
1858 }),
1859 ..Default::default()
1860 };
1861 let md = build_health_markdown(&report, &root);
1862 assert!(md.contains("### Hotspots (1 files, since 6 months)"));
1863 assert!(md.contains("| `src/hot.ts` | 85.0 | 42 | 700 | 1.20 | 10 | accelerating |"));
1864 assert!(md.contains("*5 files excluded (< 3 commits)*"));
1865 }
1866
1867 #[test]
1870 fn health_markdown_metric_legend_with_scores() {
1871 let root = PathBuf::from("/project");
1872 let report = crate::health_types::HealthReport {
1873 findings: vec![crate::health_types::HealthFinding {
1874 path: root.join("src/x.ts"),
1875 name: "f".to_string(),
1876 line: 1,
1877 col: 0,
1878 cyclomatic: 25,
1879 cognitive: 20,
1880 line_count: 10,
1881 param_count: 0,
1882 exceeded: crate::health_types::ExceededThreshold::Both,
1883 severity: crate::health_types::FindingSeverity::High,
1884 crap: None,
1885 coverage_pct: None,
1886 }],
1887 summary: crate::health_types::HealthSummary {
1888 files_analyzed: 1,
1889 functions_analyzed: 1,
1890 functions_above_threshold: 1,
1891 files_scored: Some(1),
1892 average_maintainability: Some(70.0),
1893 ..Default::default()
1894 },
1895 file_scores: vec![crate::health_types::FileHealthScore {
1896 path: root.join("src/x.ts"),
1897 fan_in: 1,
1898 fan_out: 1,
1899 dead_code_ratio: 0.0,
1900 complexity_density: 0.5,
1901 maintainability_index: 80.0,
1902 total_cyclomatic: 10,
1903 total_cognitive: 8,
1904 function_count: 2,
1905 lines: 50,
1906 crap_max: 0.0,
1907 crap_above_threshold: 0,
1908 }],
1909 ..Default::default()
1910 };
1911 let md = build_health_markdown(&report, &root);
1912 assert!(md.contains("<details><summary>Metric definitions</summary>"));
1913 assert!(md.contains("**MI** \u{2014} Maintainability Index"));
1914 assert!(md.contains("**Fan-in**"));
1915 assert!(md.contains("Full metric reference"));
1916 }
1917
1918 #[test]
1921 fn health_markdown_truncated_findings_shown_count() {
1922 let root = PathBuf::from("/project");
1923 let report = crate::health_types::HealthReport {
1924 findings: vec![crate::health_types::HealthFinding {
1925 path: root.join("src/x.ts"),
1926 name: "f".to_string(),
1927 line: 1,
1928 col: 0,
1929 cyclomatic: 25,
1930 cognitive: 20,
1931 line_count: 10,
1932 param_count: 0,
1933 exceeded: crate::health_types::ExceededThreshold::Both,
1934 severity: crate::health_types::FindingSeverity::High,
1935 crap: None,
1936 coverage_pct: None,
1937 }],
1938 summary: crate::health_types::HealthSummary {
1939 files_analyzed: 10,
1940 functions_analyzed: 50,
1941 functions_above_threshold: 5, ..Default::default()
1943 },
1944 ..Default::default()
1945 };
1946 let md = build_health_markdown(&report, &root);
1947 assert!(md.contains("5 high complexity functions (1 shown)"));
1948 }
1949
1950 #[test]
1953 fn escape_backticks_handles_multiple() {
1954 assert_eq!(escape_backticks("a`b`c"), "a\\`b\\`c");
1955 }
1956
1957 #[test]
1958 fn escape_backticks_no_backticks_unchanged() {
1959 assert_eq!(escape_backticks("hello"), "hello");
1960 }
1961
1962 #[test]
1965 fn markdown_unresolved_import_grouped_by_file() {
1966 let root = PathBuf::from("/project");
1967 let mut results = AnalysisResults::default();
1968 results.unresolved_imports.push(UnresolvedImport {
1969 path: root.join("src/app.ts"),
1970 specifier: "./missing".to_string(),
1971 line: 3,
1972 col: 0,
1973 specifier_col: 0,
1974 });
1975 let md = build_markdown(&results, &root);
1976 assert!(md.contains("### Unresolved imports (1)"));
1977 assert!(md.contains("- `src/app.ts`"));
1978 assert!(md.contains(":3 `./missing`"));
1979 }
1980
1981 #[test]
1984 fn markdown_unused_optional_dep() {
1985 let root = PathBuf::from("/project");
1986 let mut results = AnalysisResults::default();
1987 results.unused_optional_dependencies.push(UnusedDependency {
1988 package_name: "fsevents".to_string(),
1989 location: DependencyLocation::OptionalDependencies,
1990 path: root.join("package.json"),
1991 line: 12,
1992 });
1993 let md = build_markdown(&results, &root);
1994 assert!(md.contains("### Unused optionalDependencies (1)"));
1995 assert!(md.contains("- `fsevents`"));
1996 }
1997
1998 #[test]
2001 fn health_markdown_hotspots_no_excluded_message() {
2002 let root = PathBuf::from("/project");
2003 let report = crate::health_types::HealthReport {
2004 findings: vec![crate::health_types::HealthFinding {
2005 path: root.join("src/x.ts"),
2006 name: "f".to_string(),
2007 line: 1,
2008 col: 0,
2009 cyclomatic: 25,
2010 cognitive: 20,
2011 line_count: 10,
2012 param_count: 0,
2013 exceeded: crate::health_types::ExceededThreshold::Both,
2014 severity: crate::health_types::FindingSeverity::High,
2015 crap: None,
2016 coverage_pct: None,
2017 }],
2018 summary: crate::health_types::HealthSummary {
2019 files_analyzed: 5,
2020 functions_analyzed: 10,
2021 functions_above_threshold: 1,
2022 ..Default::default()
2023 },
2024 hotspots: vec![crate::health_types::HotspotEntry {
2025 path: root.join("src/hot.ts"),
2026 score: 50.0,
2027 commits: 10,
2028 weighted_commits: 8.0,
2029 lines_added: 100,
2030 lines_deleted: 50,
2031 complexity_density: 0.5,
2032 fan_in: 3,
2033 trend: fallow_core::churn::ChurnTrend::Stable,
2034 ownership: None,
2035 is_test_path: false,
2036 }],
2037 hotspot_summary: Some(crate::health_types::HotspotSummary {
2038 since: "6 months".to_string(),
2039 min_commits: 3,
2040 files_analyzed: 50,
2041 files_excluded: 0,
2042 shallow_clone: false,
2043 }),
2044 ..Default::default()
2045 };
2046 let md = build_health_markdown(&report, &root);
2047 assert!(!md.contains("files excluded"));
2048 }
2049
2050 #[test]
2053 fn duplication_markdown_single_group_no_plural() {
2054 let root = PathBuf::from("/project");
2055 let report = DuplicationReport {
2056 clone_groups: vec![CloneGroup {
2057 instances: vec![CloneInstance {
2058 file: root.join("src/a.ts"),
2059 start_line: 1,
2060 end_line: 5,
2061 start_col: 0,
2062 end_col: 0,
2063 fragment: String::new(),
2064 }],
2065 token_count: 30,
2066 line_count: 5,
2067 }],
2068 clone_families: vec![],
2069 mirrored_directories: vec![],
2070 stats: DuplicationStats {
2071 clone_groups: 1,
2072 clone_instances: 1,
2073 duplication_percentage: 2.0,
2074 ..Default::default()
2075 },
2076 };
2077 let md = build_duplication_markdown(&report, &root);
2078 assert!(md.contains("1 clone group found"));
2079 assert!(!md.contains("1 clone groups found"));
2080 }
2081}