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