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 param_count: 0,
1200 exceeded: crate::health_types::ExceededThreshold::Both,
1201 }],
1202 summary: crate::health_types::HealthSummary {
1203 files_analyzed: 10,
1204 functions_analyzed: 50,
1205 functions_above_threshold: 1,
1206 max_cyclomatic_threshold: 20,
1207 max_cognitive_threshold: 15,
1208 files_scored: None,
1209 average_maintainability: None,
1210 coverage_model: None,
1211 istanbul_matched: None,
1212 istanbul_total: None,
1213 },
1214 vital_signs: None,
1215 health_score: None,
1216 file_scores: vec![],
1217 coverage_gaps: None,
1218 hotspots: vec![],
1219 hotspot_summary: None,
1220 targets: vec![],
1221 target_thresholds: None,
1222 health_trend: None,
1223 };
1224 let md = build_health_markdown(&report, &root);
1225 assert!(md.contains("## Fallow: 1 high complexity function\n"));
1226 assert!(md.contains("| File | Function |"));
1227 assert!(md.contains("`src/utils.ts:42`"));
1228 assert!(md.contains("`parseExpression`"));
1229 assert!(md.contains("25 **!**"));
1230 assert!(md.contains("30 **!**"));
1231 assert!(md.contains("| 80 |"));
1232 }
1233
1234 #[test]
1235 fn health_markdown_no_marker_when_below_threshold() {
1236 let root = PathBuf::from("/project");
1237 let report = crate::health_types::HealthReport {
1238 findings: vec![crate::health_types::HealthFinding {
1239 path: root.join("src/utils.ts"),
1240 name: "helper".to_string(),
1241 line: 10,
1242 col: 0,
1243 cyclomatic: 15,
1244 cognitive: 20,
1245 line_count: 30,
1246 param_count: 0,
1247 exceeded: crate::health_types::ExceededThreshold::Cognitive,
1248 }],
1249 summary: crate::health_types::HealthSummary {
1250 files_analyzed: 5,
1251 functions_analyzed: 20,
1252 functions_above_threshold: 1,
1253 max_cyclomatic_threshold: 20,
1254 max_cognitive_threshold: 15,
1255 files_scored: None,
1256 average_maintainability: None,
1257 coverage_model: None,
1258 istanbul_matched: None,
1259 istanbul_total: None,
1260 },
1261 vital_signs: None,
1262 health_score: None,
1263 file_scores: vec![],
1264 coverage_gaps: None,
1265 hotspots: vec![],
1266 hotspot_summary: None,
1267 targets: vec![],
1268 target_thresholds: None,
1269 health_trend: None,
1270 };
1271 let md = build_health_markdown(&report, &root);
1272 assert!(md.contains("| 15 |"));
1274 assert!(md.contains("20 **!**"));
1276 }
1277
1278 #[test]
1279 fn health_markdown_with_targets() {
1280 use crate::health_types::*;
1281
1282 let root = PathBuf::from("/project");
1283 let report = HealthReport {
1284 findings: vec![],
1285 summary: HealthSummary {
1286 files_analyzed: 10,
1287 functions_analyzed: 50,
1288 functions_above_threshold: 0,
1289 max_cyclomatic_threshold: 20,
1290 max_cognitive_threshold: 15,
1291 files_scored: None,
1292 average_maintainability: None,
1293 coverage_model: None,
1294 istanbul_matched: None,
1295 istanbul_total: None,
1296 },
1297 vital_signs: None,
1298 health_score: None,
1299 file_scores: vec![],
1300 coverage_gaps: None,
1301 hotspots: vec![],
1302 hotspot_summary: None,
1303 targets: vec![
1304 RefactoringTarget {
1305 path: PathBuf::from("/project/src/complex.ts"),
1306 priority: 82.5,
1307 efficiency: 27.5,
1308 recommendation: "Split high-impact file".into(),
1309 category: RecommendationCategory::SplitHighImpact,
1310 effort: crate::health_types::EffortEstimate::High,
1311 confidence: crate::health_types::Confidence::Medium,
1312 factors: vec![ContributingFactor {
1313 metric: "fan_in",
1314 value: 25.0,
1315 threshold: 10.0,
1316 detail: "25 files depend on this".into(),
1317 }],
1318 evidence: None,
1319 },
1320 RefactoringTarget {
1321 path: PathBuf::from("/project/src/legacy.ts"),
1322 priority: 45.0,
1323 efficiency: 45.0,
1324 recommendation: "Remove 5 unused exports".into(),
1325 category: RecommendationCategory::RemoveDeadCode,
1326 effort: crate::health_types::EffortEstimate::Low,
1327 confidence: crate::health_types::Confidence::High,
1328 factors: vec![],
1329 evidence: None,
1330 },
1331 ],
1332 target_thresholds: None,
1333 health_trend: None,
1334 };
1335 let md = build_health_markdown(&report, &root);
1336
1337 assert!(
1339 md.contains("Refactoring Targets"),
1340 "should contain targets heading"
1341 );
1342 assert!(
1343 md.contains("src/complex.ts"),
1344 "should contain target file path"
1345 );
1346 assert!(md.contains("27.5"), "should contain efficiency score");
1347 assert!(
1348 md.contains("Split high-impact file"),
1349 "should contain recommendation"
1350 );
1351 assert!(md.contains("src/legacy.ts"), "should contain second target");
1352 }
1353
1354 #[test]
1355 fn health_markdown_with_coverage_gaps() {
1356 use crate::health_types::*;
1357
1358 let root = PathBuf::from("/project");
1359 let report = HealthReport {
1360 findings: vec![],
1361 summary: HealthSummary {
1362 files_analyzed: 10,
1363 functions_analyzed: 50,
1364 functions_above_threshold: 0,
1365 max_cyclomatic_threshold: 20,
1366 max_cognitive_threshold: 15,
1367 files_scored: None,
1368 average_maintainability: None,
1369 coverage_model: None,
1370 istanbul_matched: None,
1371 istanbul_total: None,
1372 },
1373 vital_signs: None,
1374 health_score: None,
1375 file_scores: vec![],
1376 coverage_gaps: Some(CoverageGaps {
1377 summary: CoverageGapSummary {
1378 runtime_files: 2,
1379 covered_files: 0,
1380 file_coverage_pct: 0.0,
1381 untested_files: 1,
1382 untested_exports: 1,
1383 },
1384 files: vec![UntestedFile {
1385 path: root.join("src/app.ts"),
1386 value_export_count: 2,
1387 }],
1388 exports: vec![UntestedExport {
1389 path: root.join("src/app.ts"),
1390 export_name: "loader".into(),
1391 line: 12,
1392 col: 4,
1393 }],
1394 }),
1395 hotspots: vec![],
1396 hotspot_summary: None,
1397 targets: vec![],
1398 target_thresholds: None,
1399 health_trend: None,
1400 };
1401
1402 let md = build_health_markdown(&report, &root);
1403 assert!(md.contains("### Coverage Gaps"));
1404 assert!(md.contains("*1 untested files"));
1405 assert!(md.contains("`src/app.ts` (2 value exports)"));
1406 assert!(md.contains("`src/app.ts`:12 `loader`"));
1407 }
1408
1409 #[test]
1412 fn markdown_dep_in_workspace_shows_package_label() {
1413 let root = PathBuf::from("/project");
1414 let mut results = AnalysisResults::default();
1415 results.unused_dependencies.push(UnusedDependency {
1416 package_name: "lodash".to_string(),
1417 location: DependencyLocation::Dependencies,
1418 path: root.join("packages/core/package.json"),
1419 line: 5,
1420 });
1421 let md = build_markdown(&results, &root);
1422 assert!(md.contains("(packages/core/package.json)"));
1424 }
1425
1426 #[test]
1427 fn markdown_dep_at_root_no_extra_label() {
1428 let root = PathBuf::from("/project");
1429 let mut results = AnalysisResults::default();
1430 results.unused_dependencies.push(UnusedDependency {
1431 package_name: "lodash".to_string(),
1432 location: DependencyLocation::Dependencies,
1433 path: root.join("package.json"),
1434 line: 5,
1435 });
1436 let md = build_markdown(&results, &root);
1437 assert!(md.contains("- `lodash`"));
1438 assert!(!md.contains("(package.json)"));
1439 }
1440
1441 #[test]
1444 fn markdown_exports_grouped_by_file() {
1445 let root = PathBuf::from("/project");
1446 let mut results = AnalysisResults::default();
1447 results.unused_exports.push(UnusedExport {
1448 path: root.join("src/utils.ts"),
1449 export_name: "alpha".to_string(),
1450 is_type_only: false,
1451 line: 5,
1452 col: 0,
1453 span_start: 0,
1454 is_re_export: false,
1455 });
1456 results.unused_exports.push(UnusedExport {
1457 path: root.join("src/utils.ts"),
1458 export_name: "beta".to_string(),
1459 is_type_only: false,
1460 line: 10,
1461 col: 0,
1462 span_start: 0,
1463 is_re_export: false,
1464 });
1465 results.unused_exports.push(UnusedExport {
1466 path: root.join("src/other.ts"),
1467 export_name: "gamma".to_string(),
1468 is_type_only: false,
1469 line: 1,
1470 col: 0,
1471 span_start: 0,
1472 is_re_export: false,
1473 });
1474 let md = build_markdown(&results, &root);
1475 let utils_count = md.matches("- `src/utils.ts`").count();
1477 assert_eq!(utils_count, 1, "file header should appear once per file");
1478 assert!(md.contains(":5 `alpha`"));
1480 assert!(md.contains(":10 `beta`"));
1481 }
1482
1483 #[test]
1486 fn markdown_multiple_issues_plural() {
1487 let root = PathBuf::from("/project");
1488 let mut results = AnalysisResults::default();
1489 results.unused_files.push(UnusedFile {
1490 path: root.join("src/a.ts"),
1491 });
1492 results.unused_files.push(UnusedFile {
1493 path: root.join("src/b.ts"),
1494 });
1495 let md = build_markdown(&results, &root);
1496 assert!(md.starts_with("## Fallow: 2 issues found\n"));
1497 }
1498
1499 #[test]
1502 fn duplication_markdown_zero_savings_no_suffix() {
1503 let root = PathBuf::from("/project");
1504 let report = DuplicationReport {
1505 clone_groups: vec![CloneGroup {
1506 instances: vec![CloneInstance {
1507 file: root.join("src/a.ts"),
1508 start_line: 1,
1509 end_line: 5,
1510 start_col: 0,
1511 end_col: 0,
1512 fragment: String::new(),
1513 }],
1514 token_count: 30,
1515 line_count: 5,
1516 }],
1517 clone_families: vec![CloneFamily {
1518 files: vec![root.join("src/a.ts")],
1519 groups: vec![],
1520 total_duplicated_lines: 5,
1521 total_duplicated_tokens: 30,
1522 suggestions: vec![RefactoringSuggestion {
1523 kind: RefactoringKind::ExtractFunction,
1524 description: "Extract function".to_string(),
1525 estimated_savings: 0,
1526 }],
1527 }],
1528 mirrored_directories: vec![],
1529 stats: DuplicationStats {
1530 clone_groups: 1,
1531 clone_instances: 1,
1532 duplication_percentage: 1.0,
1533 ..Default::default()
1534 },
1535 };
1536 let md = build_duplication_markdown(&report, &root);
1537 assert!(md.contains("Extract function"));
1538 assert!(!md.contains("lines saved"));
1539 }
1540
1541 #[test]
1544 fn health_markdown_vital_signs_table() {
1545 let root = PathBuf::from("/project");
1546 let report = crate::health_types::HealthReport {
1547 findings: vec![],
1548 summary: crate::health_types::HealthSummary {
1549 files_analyzed: 10,
1550 functions_analyzed: 50,
1551 functions_above_threshold: 0,
1552 max_cyclomatic_threshold: 20,
1553 max_cognitive_threshold: 15,
1554 files_scored: None,
1555 average_maintainability: None,
1556 coverage_model: None,
1557 istanbul_matched: None,
1558 istanbul_total: None,
1559 },
1560 vital_signs: Some(crate::health_types::VitalSigns {
1561 avg_cyclomatic: 3.5,
1562 p90_cyclomatic: 12,
1563 dead_file_pct: Some(5.0),
1564 dead_export_pct: Some(10.2),
1565 duplication_pct: None,
1566 maintainability_avg: Some(72.3),
1567 hotspot_count: Some(3),
1568 circular_dep_count: Some(1),
1569 unused_dep_count: Some(2),
1570 counts: None,
1571 unit_size_profile: None,
1572 unit_interfacing_profile: None,
1573 p95_fan_in: None,
1574 coupling_high_pct: None,
1575 }),
1576 health_score: None,
1577 file_scores: vec![],
1578 coverage_gaps: None,
1579 hotspots: vec![],
1580 hotspot_summary: None,
1581 targets: vec![],
1582 target_thresholds: None,
1583 health_trend: None,
1584 };
1585 let md = build_health_markdown(&report, &root);
1586 assert!(md.contains("## Vital Signs"));
1587 assert!(md.contains("| Metric | Value |"));
1588 assert!(md.contains("| Avg Cyclomatic | 3.5 |"));
1589 assert!(md.contains("| P90 Cyclomatic | 12 |"));
1590 assert!(md.contains("| Dead Files | 5.0% |"));
1591 assert!(md.contains("| Dead Exports | 10.2% |"));
1592 assert!(md.contains("| Maintainability (avg) | 72.3 |"));
1593 assert!(md.contains("| Hotspots | 3 |"));
1594 assert!(md.contains("| Circular Deps | 1 |"));
1595 assert!(md.contains("| Unused Deps | 2 |"));
1596 }
1597
1598 #[test]
1601 fn health_markdown_file_scores_table() {
1602 let root = PathBuf::from("/project");
1603 let report = crate::health_types::HealthReport {
1604 findings: vec![crate::health_types::HealthFinding {
1605 path: root.join("src/dummy.ts"),
1606 name: "fn".to_string(),
1607 line: 1,
1608 col: 0,
1609 cyclomatic: 25,
1610 cognitive: 20,
1611 line_count: 50,
1612 param_count: 0,
1613 exceeded: crate::health_types::ExceededThreshold::Both,
1614 }],
1615 summary: crate::health_types::HealthSummary {
1616 files_analyzed: 5,
1617 functions_analyzed: 10,
1618 functions_above_threshold: 1,
1619 max_cyclomatic_threshold: 20,
1620 max_cognitive_threshold: 15,
1621 files_scored: Some(1),
1622 average_maintainability: Some(65.0),
1623 coverage_model: None,
1624 istanbul_matched: None,
1625 istanbul_total: None,
1626 },
1627 vital_signs: None,
1628 health_score: None,
1629 file_scores: vec![crate::health_types::FileHealthScore {
1630 path: root.join("src/utils.ts"),
1631 fan_in: 5,
1632 fan_out: 3,
1633 dead_code_ratio: 0.25,
1634 complexity_density: 0.8,
1635 maintainability_index: 72.5,
1636 total_cyclomatic: 40,
1637 total_cognitive: 30,
1638 function_count: 10,
1639 lines: 200,
1640 crap_max: 0.0,
1641 crap_above_threshold: 0,
1642 }],
1643 coverage_gaps: None,
1644 hotspots: vec![],
1645 hotspot_summary: None,
1646 targets: vec![],
1647 target_thresholds: None,
1648 health_trend: None,
1649 };
1650 let md = build_health_markdown(&report, &root);
1651 assert!(md.contains("### File Health Scores (1 files)"));
1652 assert!(md.contains("| File | Maintainability | Fan-in | Fan-out | Dead Code | Density |"));
1653 assert!(md.contains("| `src/utils.ts` | 72.5 | 5 | 3 | 25% | 0.80 |"));
1654 assert!(md.contains("**Average maintainability index:** 65.0/100"));
1655 }
1656
1657 #[test]
1660 fn health_markdown_hotspots_table() {
1661 let root = PathBuf::from("/project");
1662 let report = crate::health_types::HealthReport {
1663 findings: vec![crate::health_types::HealthFinding {
1664 path: root.join("src/dummy.ts"),
1665 name: "fn".to_string(),
1666 line: 1,
1667 col: 0,
1668 cyclomatic: 25,
1669 cognitive: 20,
1670 line_count: 50,
1671 param_count: 0,
1672 exceeded: crate::health_types::ExceededThreshold::Both,
1673 }],
1674 summary: crate::health_types::HealthSummary {
1675 files_analyzed: 5,
1676 functions_analyzed: 10,
1677 functions_above_threshold: 1,
1678 max_cyclomatic_threshold: 20,
1679 max_cognitive_threshold: 15,
1680 files_scored: None,
1681 average_maintainability: None,
1682 coverage_model: None,
1683 istanbul_matched: None,
1684 istanbul_total: None,
1685 },
1686 vital_signs: None,
1687 health_score: None,
1688 file_scores: vec![],
1689 coverage_gaps: None,
1690 hotspots: vec![crate::health_types::HotspotEntry {
1691 path: root.join("src/hot.ts"),
1692 score: 85.0,
1693 commits: 42,
1694 weighted_commits: 35.0,
1695 lines_added: 500,
1696 lines_deleted: 200,
1697 complexity_density: 1.2,
1698 fan_in: 10,
1699 trend: fallow_core::churn::ChurnTrend::Accelerating,
1700 }],
1701 hotspot_summary: Some(crate::health_types::HotspotSummary {
1702 since: "6 months".to_string(),
1703 min_commits: 3,
1704 files_analyzed: 50,
1705 files_excluded: 5,
1706 shallow_clone: false,
1707 }),
1708 targets: vec![],
1709 target_thresholds: None,
1710 health_trend: None,
1711 };
1712 let md = build_health_markdown(&report, &root);
1713 assert!(md.contains("### Hotspots (1 files, since 6 months)"));
1714 assert!(md.contains("| `src/hot.ts` | 85.0 | 42 | 700 | 1.20 | 10 | accelerating |"));
1715 assert!(md.contains("*5 files excluded (< 3 commits)*"));
1716 }
1717
1718 #[test]
1721 fn health_markdown_metric_legend_with_scores() {
1722 let root = PathBuf::from("/project");
1723 let report = crate::health_types::HealthReport {
1724 findings: vec![crate::health_types::HealthFinding {
1725 path: root.join("src/x.ts"),
1726 name: "f".to_string(),
1727 line: 1,
1728 col: 0,
1729 cyclomatic: 25,
1730 cognitive: 20,
1731 line_count: 10,
1732 param_count: 0,
1733 exceeded: crate::health_types::ExceededThreshold::Both,
1734 }],
1735 summary: crate::health_types::HealthSummary {
1736 files_analyzed: 1,
1737 functions_analyzed: 1,
1738 functions_above_threshold: 1,
1739 max_cyclomatic_threshold: 20,
1740 max_cognitive_threshold: 15,
1741 files_scored: Some(1),
1742 average_maintainability: Some(70.0),
1743 coverage_model: None,
1744 istanbul_matched: None,
1745 istanbul_total: None,
1746 },
1747 vital_signs: None,
1748 health_score: None,
1749 file_scores: vec![crate::health_types::FileHealthScore {
1750 path: root.join("src/x.ts"),
1751 fan_in: 1,
1752 fan_out: 1,
1753 dead_code_ratio: 0.0,
1754 complexity_density: 0.5,
1755 maintainability_index: 80.0,
1756 total_cyclomatic: 10,
1757 total_cognitive: 8,
1758 function_count: 2,
1759 lines: 50,
1760 crap_max: 0.0,
1761 crap_above_threshold: 0,
1762 }],
1763 coverage_gaps: None,
1764 hotspots: vec![],
1765 hotspot_summary: None,
1766 targets: vec![],
1767 target_thresholds: None,
1768 health_trend: None,
1769 };
1770 let md = build_health_markdown(&report, &root);
1771 assert!(md.contains("<details><summary>Metric definitions</summary>"));
1772 assert!(md.contains("**MI** \u{2014} Maintainability Index"));
1773 assert!(md.contains("**Fan-in**"));
1774 assert!(md.contains("Full metric reference"));
1775 }
1776
1777 #[test]
1780 fn health_markdown_truncated_findings_shown_count() {
1781 let root = PathBuf::from("/project");
1782 let report = crate::health_types::HealthReport {
1783 findings: vec![crate::health_types::HealthFinding {
1784 path: root.join("src/x.ts"),
1785 name: "f".to_string(),
1786 line: 1,
1787 col: 0,
1788 cyclomatic: 25,
1789 cognitive: 20,
1790 line_count: 10,
1791 param_count: 0,
1792 exceeded: crate::health_types::ExceededThreshold::Both,
1793 }],
1794 summary: crate::health_types::HealthSummary {
1795 files_analyzed: 10,
1796 functions_analyzed: 50,
1797 functions_above_threshold: 5, max_cyclomatic_threshold: 20,
1799 max_cognitive_threshold: 15,
1800 files_scored: None,
1801 average_maintainability: None,
1802 coverage_model: None,
1803 istanbul_matched: None,
1804 istanbul_total: None,
1805 },
1806 vital_signs: None,
1807 health_score: None,
1808 file_scores: vec![],
1809 coverage_gaps: None,
1810 hotspots: vec![],
1811 hotspot_summary: None,
1812 targets: vec![],
1813 target_thresholds: None,
1814 health_trend: None,
1815 };
1816 let md = build_health_markdown(&report, &root);
1817 assert!(md.contains("5 high complexity functions (1 shown)"));
1818 }
1819
1820 #[test]
1823 fn escape_backticks_handles_multiple() {
1824 assert_eq!(escape_backticks("a`b`c"), "a\\`b\\`c");
1825 }
1826
1827 #[test]
1828 fn escape_backticks_no_backticks_unchanged() {
1829 assert_eq!(escape_backticks("hello"), "hello");
1830 }
1831
1832 #[test]
1835 fn markdown_unresolved_import_grouped_by_file() {
1836 let root = PathBuf::from("/project");
1837 let mut results = AnalysisResults::default();
1838 results.unresolved_imports.push(UnresolvedImport {
1839 path: root.join("src/app.ts"),
1840 specifier: "./missing".to_string(),
1841 line: 3,
1842 col: 0,
1843 specifier_col: 0,
1844 });
1845 let md = build_markdown(&results, &root);
1846 assert!(md.contains("### Unresolved imports (1)"));
1847 assert!(md.contains("- `src/app.ts`"));
1848 assert!(md.contains(":3 `./missing`"));
1849 }
1850
1851 #[test]
1854 fn markdown_unused_optional_dep() {
1855 let root = PathBuf::from("/project");
1856 let mut results = AnalysisResults::default();
1857 results.unused_optional_dependencies.push(UnusedDependency {
1858 package_name: "fsevents".to_string(),
1859 location: DependencyLocation::OptionalDependencies,
1860 path: root.join("package.json"),
1861 line: 12,
1862 });
1863 let md = build_markdown(&results, &root);
1864 assert!(md.contains("### Unused optionalDependencies (1)"));
1865 assert!(md.contains("- `fsevents`"));
1866 }
1867
1868 #[test]
1871 fn health_markdown_hotspots_no_excluded_message() {
1872 let root = PathBuf::from("/project");
1873 let report = crate::health_types::HealthReport {
1874 findings: vec![crate::health_types::HealthFinding {
1875 path: root.join("src/x.ts"),
1876 name: "f".to_string(),
1877 line: 1,
1878 col: 0,
1879 cyclomatic: 25,
1880 cognitive: 20,
1881 line_count: 10,
1882 param_count: 0,
1883 exceeded: crate::health_types::ExceededThreshold::Both,
1884 }],
1885 summary: crate::health_types::HealthSummary {
1886 files_analyzed: 5,
1887 functions_analyzed: 10,
1888 functions_above_threshold: 1,
1889 max_cyclomatic_threshold: 20,
1890 max_cognitive_threshold: 15,
1891 files_scored: None,
1892 average_maintainability: None,
1893 coverage_model: None,
1894 istanbul_matched: None,
1895 istanbul_total: None,
1896 },
1897 vital_signs: None,
1898 health_score: None,
1899 file_scores: vec![],
1900 coverage_gaps: None,
1901 hotspots: vec![crate::health_types::HotspotEntry {
1902 path: root.join("src/hot.ts"),
1903 score: 50.0,
1904 commits: 10,
1905 weighted_commits: 8.0,
1906 lines_added: 100,
1907 lines_deleted: 50,
1908 complexity_density: 0.5,
1909 fan_in: 3,
1910 trend: fallow_core::churn::ChurnTrend::Stable,
1911 }],
1912 hotspot_summary: Some(crate::health_types::HotspotSummary {
1913 since: "6 months".to_string(),
1914 min_commits: 3,
1915 files_analyzed: 50,
1916 files_excluded: 0,
1917 shallow_clone: false,
1918 }),
1919 targets: vec![],
1920 target_thresholds: None,
1921 health_trend: None,
1922 };
1923 let md = build_health_markdown(&report, &root);
1924 assert!(!md.contains("files excluded"));
1925 }
1926
1927 #[test]
1930 fn duplication_markdown_single_group_no_plural() {
1931 let root = PathBuf::from("/project");
1932 let report = DuplicationReport {
1933 clone_groups: vec![CloneGroup {
1934 instances: vec![CloneInstance {
1935 file: root.join("src/a.ts"),
1936 start_line: 1,
1937 end_line: 5,
1938 start_col: 0,
1939 end_col: 0,
1940 fragment: String::new(),
1941 }],
1942 token_count: 30,
1943 line_count: 5,
1944 }],
1945 clone_families: vec![],
1946 mirrored_directories: vec![],
1947 stats: DuplicationStats {
1948 clone_groups: 1,
1949 clone_instances: 1,
1950 duplication_percentage: 2.0,
1951 ..Default::default()
1952 },
1953 };
1954 let md = build_duplication_markdown(&report, &root);
1955 assert!(md.contains("1 clone group found"));
1956 assert!(!md.contains("1 clone groups found"));
1957 }
1958}