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 |\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} |",
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 );
669 }
670
671 if let Some(avg) = report.summary.average_maintainability {
672 let _ = write!(out, "\n**Average maintainability index:** {avg:.1}/100\n");
673 }
674}
675
676fn write_coverage_gaps_section(
677 out: &mut String,
678 report: &crate::health_types::HealthReport,
679 root: &Path,
680) {
681 let Some(ref gaps) = report.coverage_gaps else {
682 return;
683 };
684
685 out.push('\n');
686 let _ = writeln!(out, "### Coverage Gaps\n");
687 let _ = writeln!(
688 out,
689 "*{} untested files · {} untested exports · {:.1}% file coverage*\n",
690 gaps.summary.untested_files, gaps.summary.untested_exports, gaps.summary.file_coverage_pct,
691 );
692
693 if gaps.files.is_empty() && gaps.exports.is_empty() {
694 out.push_str("_No coverage gaps found in scope._\n");
695 return;
696 }
697
698 if !gaps.files.is_empty() {
699 out.push_str("#### Files\n");
700 for item in &gaps.files {
701 let file_str = escape_backticks(&normalize_uri(
702 &relative_path(&item.path, root).display().to_string(),
703 ));
704 let _ = writeln!(
705 out,
706 "- `{file_str}` ({count} value export{})",
707 if item.value_export_count == 1 {
708 ""
709 } else {
710 "s"
711 },
712 count = item.value_export_count,
713 );
714 }
715 out.push('\n');
716 }
717
718 if !gaps.exports.is_empty() {
719 out.push_str("#### Exports\n");
720 for item in &gaps.exports {
721 let file_str = escape_backticks(&normalize_uri(
722 &relative_path(&item.path, root).display().to_string(),
723 ));
724 let _ = writeln!(out, "- `{file_str}`:{} `{}`", item.line, item.export_name);
725 }
726 }
727}
728
729fn write_hotspots_section(
731 out: &mut String,
732 report: &crate::health_types::HealthReport,
733 root: &Path,
734) {
735 if report.hotspots.is_empty() {
736 return;
737 }
738
739 let rel = |p: &Path| {
740 escape_backticks(&normalize_uri(
741 &relative_path(p, root).display().to_string(),
742 ))
743 };
744
745 out.push('\n');
746 let header = report.hotspot_summary.as_ref().map_or_else(
747 || format!("### Hotspots ({} files)\n", report.hotspots.len()),
748 |summary| {
749 format!(
750 "### Hotspots ({} files, since {})\n",
751 report.hotspots.len(),
752 summary.since,
753 )
754 },
755 );
756 let _ = writeln!(out, "{header}");
757 out.push_str("| File | Score | Commits | Churn | Density | Fan-in | Trend |\n");
758 out.push_str("|:-----|:------|:--------|:------|:--------|:-------|:------|\n");
759
760 for entry in &report.hotspots {
761 let file_str = rel(&entry.path);
762 let _ = writeln!(
763 out,
764 "| `{file_str}` | {score:.1} | {commits} | {churn} | {density:.2} | {fi} | {trend} |",
765 score = entry.score,
766 commits = entry.commits,
767 churn = entry.lines_added + entry.lines_deleted,
768 density = entry.complexity_density,
769 fi = entry.fan_in,
770 trend = entry.trend,
771 );
772 }
773
774 if let Some(ref summary) = report.hotspot_summary
775 && summary.files_excluded > 0
776 {
777 let _ = write!(
778 out,
779 "\n*{} file{} excluded (< {} commits)*\n",
780 summary.files_excluded,
781 plural(summary.files_excluded),
782 summary.min_commits,
783 );
784 }
785}
786
787fn write_targets_section(
789 out: &mut String,
790 report: &crate::health_types::HealthReport,
791 root: &Path,
792) {
793 if report.targets.is_empty() {
794 return;
795 }
796 let _ = write!(
797 out,
798 "\n### Refactoring Targets ({})\n\n",
799 report.targets.len()
800 );
801 out.push_str("| Efficiency | Category | Effort / Confidence | File | Recommendation |\n");
802 out.push_str("|:-----------|:---------|:--------------------|:-----|:---------------|\n");
803 for target in &report.targets {
804 let file_str = normalize_uri(&relative_path(&target.path, root).display().to_string());
805 let category = target.category.label();
806 let effort = target.effort.label();
807 let confidence = target.confidence.label();
808 let _ = writeln!(
809 out,
810 "| {:.1} | {category} | {effort} / {confidence} | `{file_str}` | {} |",
811 target.efficiency, target.recommendation,
812 );
813 }
814}
815
816fn write_metric_legend(out: &mut String, report: &crate::health_types::HealthReport) {
818 let has_scores = !report.file_scores.is_empty();
819 let has_coverage = report.coverage_gaps.is_some();
820 let has_hotspots = !report.hotspots.is_empty();
821 let has_targets = !report.targets.is_empty();
822 if !has_scores && !has_coverage && !has_hotspots && !has_targets {
823 return;
824 }
825 out.push_str("\n---\n\n<details><summary>Metric definitions</summary>\n\n");
826 if has_scores {
827 out.push_str("- **MI** — Maintainability Index (0\u{2013}100, higher is better)\n");
828 out.push_str("- **Fan-in** — files that import this file (blast radius)\n");
829 out.push_str("- **Fan-out** — files this file imports (coupling)\n");
830 out.push_str("- **Dead Code** — % of value exports with zero references\n");
831 out.push_str("- **Density** — cyclomatic complexity / lines of code\n");
832 }
833 if has_coverage {
834 out.push_str(
835 "- **File coverage** — runtime files also reachable from a discovered test root\n",
836 );
837 out.push_str("- **Untested export** — export with no reference chain from any test-reachable module\n");
838 }
839 if has_hotspots {
840 out.push_str("- **Score** — churn \u{00d7} complexity (0\u{2013}100, higher = riskier)\n");
841 out.push_str("- **Commits** — commits in the analysis window\n");
842 out.push_str("- **Churn** — total lines added + deleted\n");
843 out.push_str("- **Trend** — accelerating / stable / cooling\n");
844 }
845 if has_targets {
846 out.push_str("- **Efficiency** — priority / effort (higher = better quick-win value, default sort)\n");
847 out.push_str("- **Category** — recommendation type (churn+complexity, high impact, dead code, complexity, coupling, circular dep)\n");
848 out.push_str("- **Effort** — estimated effort (low / medium / high) based on file size, function count, and fan-in\n");
849 out.push_str("- **Confidence** — recommendation reliability (high = deterministic analysis, medium = heuristic, low = git-dependent)\n");
850 }
851 out.push_str(
852 "\n[Full metric reference](https://docs.fallow.tools/explanations/metrics)\n\n</details>\n",
853 );
854}
855
856#[cfg(test)]
857mod tests {
858 use super::*;
859 use crate::report::test_helpers::sample_results;
860 use fallow_core::duplicates::{
861 CloneFamily, CloneGroup, CloneInstance, DuplicationReport, DuplicationStats,
862 RefactoringKind, RefactoringSuggestion,
863 };
864 use fallow_core::results::*;
865 use std::path::PathBuf;
866
867 #[test]
868 fn markdown_empty_results_no_issues() {
869 let root = PathBuf::from("/project");
870 let results = AnalysisResults::default();
871 let md = build_markdown(&results, &root);
872 assert_eq!(md, "## Fallow: no issues found\n");
873 }
874
875 #[test]
876 fn markdown_contains_header_with_count() {
877 let root = PathBuf::from("/project");
878 let results = sample_results(&root);
879 let md = build_markdown(&results, &root);
880 assert!(md.starts_with(&format!(
881 "## Fallow: {} issues found\n",
882 results.total_issues()
883 )));
884 }
885
886 #[test]
887 fn markdown_contains_all_sections() {
888 let root = PathBuf::from("/project");
889 let results = sample_results(&root);
890 let md = build_markdown(&results, &root);
891
892 assert!(md.contains("### Unused files (1)"));
893 assert!(md.contains("### Unused exports (1)"));
894 assert!(md.contains("### Unused type exports (1)"));
895 assert!(md.contains("### Unused dependencies (1)"));
896 assert!(md.contains("### Unused devDependencies (1)"));
897 assert!(md.contains("### Unused enum members (1)"));
898 assert!(md.contains("### Unused class members (1)"));
899 assert!(md.contains("### Unresolved imports (1)"));
900 assert!(md.contains("### Unlisted dependencies (1)"));
901 assert!(md.contains("### Duplicate exports (1)"));
902 assert!(md.contains("### Type-only dependencies"));
903 assert!(md.contains("### Test-only production dependencies"));
904 assert!(md.contains("### Circular dependencies (1)"));
905 }
906
907 #[test]
908 fn markdown_unused_file_format() {
909 let root = PathBuf::from("/project");
910 let mut results = AnalysisResults::default();
911 results.unused_files.push(UnusedFile {
912 path: root.join("src/dead.ts"),
913 });
914 let md = build_markdown(&results, &root);
915 assert!(md.contains("- `src/dead.ts`"));
916 }
917
918 #[test]
919 fn markdown_unused_export_grouped_by_file() {
920 let root = PathBuf::from("/project");
921 let mut results = AnalysisResults::default();
922 results.unused_exports.push(UnusedExport {
923 path: root.join("src/utils.ts"),
924 export_name: "helperFn".to_string(),
925 is_type_only: false,
926 line: 10,
927 col: 4,
928 span_start: 120,
929 is_re_export: false,
930 });
931 let md = build_markdown(&results, &root);
932 assert!(md.contains("- `src/utils.ts`"));
933 assert!(md.contains(":10 `helperFn`"));
934 }
935
936 #[test]
937 fn markdown_re_export_tagged() {
938 let root = PathBuf::from("/project");
939 let mut results = AnalysisResults::default();
940 results.unused_exports.push(UnusedExport {
941 path: root.join("src/index.ts"),
942 export_name: "reExported".to_string(),
943 is_type_only: false,
944 line: 1,
945 col: 0,
946 span_start: 0,
947 is_re_export: true,
948 });
949 let md = build_markdown(&results, &root);
950 assert!(md.contains("(re-export)"));
951 }
952
953 #[test]
954 fn markdown_unused_dep_format() {
955 let root = PathBuf::from("/project");
956 let mut results = AnalysisResults::default();
957 results.unused_dependencies.push(UnusedDependency {
958 package_name: "lodash".to_string(),
959 location: DependencyLocation::Dependencies,
960 path: root.join("package.json"),
961 line: 5,
962 });
963 let md = build_markdown(&results, &root);
964 assert!(md.contains("- `lodash`"));
965 }
966
967 #[test]
968 fn markdown_circular_dep_format() {
969 let root = PathBuf::from("/project");
970 let mut results = AnalysisResults::default();
971 results.circular_dependencies.push(CircularDependency {
972 files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
973 length: 2,
974 line: 3,
975 col: 0,
976 is_cross_package: false,
977 });
978 let md = build_markdown(&results, &root);
979 assert!(md.contains("`src/a.ts`"));
980 assert!(md.contains("`src/b.ts`"));
981 assert!(md.contains("\u{2192}"));
982 }
983
984 #[test]
985 fn markdown_strips_root_prefix() {
986 let root = PathBuf::from("/project");
987 let mut results = AnalysisResults::default();
988 results.unused_files.push(UnusedFile {
989 path: PathBuf::from("/project/src/deep/nested/file.ts"),
990 });
991 let md = build_markdown(&results, &root);
992 assert!(md.contains("`src/deep/nested/file.ts`"));
993 assert!(!md.contains("/project/"));
994 }
995
996 #[test]
997 fn markdown_single_issue_no_plural() {
998 let root = PathBuf::from("/project");
999 let mut results = AnalysisResults::default();
1000 results.unused_files.push(UnusedFile {
1001 path: root.join("src/dead.ts"),
1002 });
1003 let md = build_markdown(&results, &root);
1004 assert!(md.starts_with("## Fallow: 1 issue found\n"));
1005 }
1006
1007 #[test]
1008 fn markdown_type_only_dep_format() {
1009 let root = PathBuf::from("/project");
1010 let mut results = AnalysisResults::default();
1011 results.type_only_dependencies.push(TypeOnlyDependency {
1012 package_name: "zod".to_string(),
1013 path: root.join("package.json"),
1014 line: 8,
1015 });
1016 let md = build_markdown(&results, &root);
1017 assert!(md.contains("### Type-only dependencies"));
1018 assert!(md.contains("- `zod`"));
1019 }
1020
1021 #[test]
1022 fn markdown_escapes_backticks_in_export_names() {
1023 let root = PathBuf::from("/project");
1024 let mut results = AnalysisResults::default();
1025 results.unused_exports.push(UnusedExport {
1026 path: root.join("src/utils.ts"),
1027 export_name: "foo`bar".to_string(),
1028 is_type_only: false,
1029 line: 1,
1030 col: 0,
1031 span_start: 0,
1032 is_re_export: false,
1033 });
1034 let md = build_markdown(&results, &root);
1035 assert!(md.contains("foo\\`bar"));
1036 assert!(!md.contains("foo`bar`"));
1037 }
1038
1039 #[test]
1040 fn markdown_escapes_backticks_in_package_names() {
1041 let root = PathBuf::from("/project");
1042 let mut results = AnalysisResults::default();
1043 results.unused_dependencies.push(UnusedDependency {
1044 package_name: "pkg`name".to_string(),
1045 location: DependencyLocation::Dependencies,
1046 path: root.join("package.json"),
1047 line: 5,
1048 });
1049 let md = build_markdown(&results, &root);
1050 assert!(md.contains("pkg\\`name"));
1051 }
1052
1053 #[test]
1056 fn duplication_markdown_empty() {
1057 let report = DuplicationReport::default();
1058 let root = PathBuf::from("/project");
1059 let md = build_duplication_markdown(&report, &root);
1060 assert_eq!(md, "## Fallow: no code duplication found\n");
1061 }
1062
1063 #[test]
1064 fn duplication_markdown_contains_groups() {
1065 let root = PathBuf::from("/project");
1066 let report = DuplicationReport {
1067 clone_groups: vec![CloneGroup {
1068 instances: vec![
1069 CloneInstance {
1070 file: root.join("src/a.ts"),
1071 start_line: 1,
1072 end_line: 10,
1073 start_col: 0,
1074 end_col: 0,
1075 fragment: String::new(),
1076 },
1077 CloneInstance {
1078 file: root.join("src/b.ts"),
1079 start_line: 5,
1080 end_line: 14,
1081 start_col: 0,
1082 end_col: 0,
1083 fragment: String::new(),
1084 },
1085 ],
1086 token_count: 50,
1087 line_count: 10,
1088 }],
1089 clone_families: vec![],
1090 mirrored_directories: vec![],
1091 stats: DuplicationStats {
1092 total_files: 10,
1093 files_with_clones: 2,
1094 total_lines: 500,
1095 duplicated_lines: 20,
1096 total_tokens: 2500,
1097 duplicated_tokens: 100,
1098 clone_groups: 1,
1099 clone_instances: 2,
1100 duplication_percentage: 4.0,
1101 },
1102 };
1103 let md = build_duplication_markdown(&report, &root);
1104 assert!(md.contains("**Clone group 1**"));
1105 assert!(md.contains("`src/a.ts:1-10`"));
1106 assert!(md.contains("`src/b.ts:5-14`"));
1107 assert!(md.contains("4.0% duplication"));
1108 }
1109
1110 #[test]
1111 fn duplication_markdown_contains_families() {
1112 let root = PathBuf::from("/project");
1113 let report = DuplicationReport {
1114 clone_groups: vec![CloneGroup {
1115 instances: vec![CloneInstance {
1116 file: root.join("src/a.ts"),
1117 start_line: 1,
1118 end_line: 5,
1119 start_col: 0,
1120 end_col: 0,
1121 fragment: String::new(),
1122 }],
1123 token_count: 30,
1124 line_count: 5,
1125 }],
1126 clone_families: vec![CloneFamily {
1127 files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
1128 groups: vec![],
1129 total_duplicated_lines: 20,
1130 total_duplicated_tokens: 100,
1131 suggestions: vec![RefactoringSuggestion {
1132 kind: RefactoringKind::ExtractFunction,
1133 description: "Extract shared utility function".to_string(),
1134 estimated_savings: 15,
1135 }],
1136 }],
1137 mirrored_directories: vec![],
1138 stats: DuplicationStats {
1139 clone_groups: 1,
1140 clone_instances: 1,
1141 duplication_percentage: 2.0,
1142 ..Default::default()
1143 },
1144 };
1145 let md = build_duplication_markdown(&report, &root);
1146 assert!(md.contains("### Clone Families"));
1147 assert!(md.contains("**Family 1**"));
1148 assert!(md.contains("Extract shared utility function"));
1149 assert!(md.contains("~15 lines saved"));
1150 }
1151
1152 #[test]
1155 fn health_markdown_empty_no_findings() {
1156 let root = PathBuf::from("/project");
1157 let report = crate::health_types::HealthReport {
1158 findings: vec![],
1159 summary: crate::health_types::HealthSummary {
1160 files_analyzed: 10,
1161 functions_analyzed: 50,
1162 functions_above_threshold: 0,
1163 max_cyclomatic_threshold: 20,
1164 max_cognitive_threshold: 15,
1165 files_scored: None,
1166 average_maintainability: None,
1167 },
1168 vital_signs: None,
1169 health_score: None,
1170 file_scores: vec![],
1171 coverage_gaps: None,
1172 hotspots: vec![],
1173 hotspot_summary: None,
1174 targets: vec![],
1175 target_thresholds: None,
1176 health_trend: None,
1177 };
1178 let md = build_health_markdown(&report, &root);
1179 assert!(md.contains("no functions exceed complexity thresholds"));
1180 assert!(md.contains("**50** functions analyzed"));
1181 }
1182
1183 #[test]
1184 fn health_markdown_table_format() {
1185 let root = PathBuf::from("/project");
1186 let report = crate::health_types::HealthReport {
1187 findings: vec![crate::health_types::HealthFinding {
1188 path: root.join("src/utils.ts"),
1189 name: "parseExpression".to_string(),
1190 line: 42,
1191 col: 0,
1192 cyclomatic: 25,
1193 cognitive: 30,
1194 line_count: 80,
1195 exceeded: crate::health_types::ExceededThreshold::Both,
1196 }],
1197 summary: crate::health_types::HealthSummary {
1198 files_analyzed: 10,
1199 functions_analyzed: 50,
1200 functions_above_threshold: 1,
1201 max_cyclomatic_threshold: 20,
1202 max_cognitive_threshold: 15,
1203 files_scored: None,
1204 average_maintainability: None,
1205 },
1206 vital_signs: None,
1207 health_score: None,
1208 file_scores: vec![],
1209 coverage_gaps: None,
1210 hotspots: vec![],
1211 hotspot_summary: None,
1212 targets: vec![],
1213 target_thresholds: None,
1214 health_trend: None,
1215 };
1216 let md = build_health_markdown(&report, &root);
1217 assert!(md.contains("## Fallow: 1 high complexity function\n"));
1218 assert!(md.contains("| File | Function |"));
1219 assert!(md.contains("`src/utils.ts:42`"));
1220 assert!(md.contains("`parseExpression`"));
1221 assert!(md.contains("25 **!**"));
1222 assert!(md.contains("30 **!**"));
1223 assert!(md.contains("| 80 |"));
1224 }
1225
1226 #[test]
1227 fn health_markdown_no_marker_when_below_threshold() {
1228 let root = PathBuf::from("/project");
1229 let report = crate::health_types::HealthReport {
1230 findings: vec![crate::health_types::HealthFinding {
1231 path: root.join("src/utils.ts"),
1232 name: "helper".to_string(),
1233 line: 10,
1234 col: 0,
1235 cyclomatic: 15,
1236 cognitive: 20,
1237 line_count: 30,
1238 exceeded: crate::health_types::ExceededThreshold::Cognitive,
1239 }],
1240 summary: crate::health_types::HealthSummary {
1241 files_analyzed: 5,
1242 functions_analyzed: 20,
1243 functions_above_threshold: 1,
1244 max_cyclomatic_threshold: 20,
1245 max_cognitive_threshold: 15,
1246 files_scored: None,
1247 average_maintainability: None,
1248 },
1249 vital_signs: None,
1250 health_score: None,
1251 file_scores: vec![],
1252 coverage_gaps: None,
1253 hotspots: vec![],
1254 hotspot_summary: None,
1255 targets: vec![],
1256 target_thresholds: None,
1257 health_trend: None,
1258 };
1259 let md = build_health_markdown(&report, &root);
1260 assert!(md.contains("| 15 |"));
1262 assert!(md.contains("20 **!**"));
1264 }
1265
1266 #[test]
1267 fn health_markdown_with_targets() {
1268 use crate::health_types::*;
1269
1270 let root = PathBuf::from("/project");
1271 let report = HealthReport {
1272 findings: vec![],
1273 summary: HealthSummary {
1274 files_analyzed: 10,
1275 functions_analyzed: 50,
1276 functions_above_threshold: 0,
1277 max_cyclomatic_threshold: 20,
1278 max_cognitive_threshold: 15,
1279 files_scored: None,
1280 average_maintainability: None,
1281 },
1282 vital_signs: None,
1283 health_score: None,
1284 file_scores: vec![],
1285 coverage_gaps: None,
1286 hotspots: vec![],
1287 hotspot_summary: None,
1288 targets: vec![
1289 RefactoringTarget {
1290 path: PathBuf::from("/project/src/complex.ts"),
1291 priority: 82.5,
1292 efficiency: 27.5,
1293 recommendation: "Split high-impact file".into(),
1294 category: RecommendationCategory::SplitHighImpact,
1295 effort: crate::health_types::EffortEstimate::High,
1296 confidence: crate::health_types::Confidence::Medium,
1297 factors: vec![ContributingFactor {
1298 metric: "fan_in",
1299 value: 25.0,
1300 threshold: 10.0,
1301 detail: "25 files depend on this".into(),
1302 }],
1303 evidence: None,
1304 },
1305 RefactoringTarget {
1306 path: PathBuf::from("/project/src/legacy.ts"),
1307 priority: 45.0,
1308 efficiency: 45.0,
1309 recommendation: "Remove 5 unused exports".into(),
1310 category: RecommendationCategory::RemoveDeadCode,
1311 effort: crate::health_types::EffortEstimate::Low,
1312 confidence: crate::health_types::Confidence::High,
1313 factors: vec![],
1314 evidence: None,
1315 },
1316 ],
1317 target_thresholds: None,
1318 health_trend: None,
1319 };
1320 let md = build_health_markdown(&report, &root);
1321
1322 assert!(
1324 md.contains("Refactoring Targets"),
1325 "should contain targets heading"
1326 );
1327 assert!(
1328 md.contains("src/complex.ts"),
1329 "should contain target file path"
1330 );
1331 assert!(md.contains("27.5"), "should contain efficiency score");
1332 assert!(
1333 md.contains("Split high-impact file"),
1334 "should contain recommendation"
1335 );
1336 assert!(md.contains("src/legacy.ts"), "should contain second target");
1337 }
1338
1339 #[test]
1340 fn health_markdown_with_coverage_gaps() {
1341 use crate::health_types::*;
1342
1343 let root = PathBuf::from("/project");
1344 let report = HealthReport {
1345 findings: vec![],
1346 summary: HealthSummary {
1347 files_analyzed: 10,
1348 functions_analyzed: 50,
1349 functions_above_threshold: 0,
1350 max_cyclomatic_threshold: 20,
1351 max_cognitive_threshold: 15,
1352 files_scored: None,
1353 average_maintainability: None,
1354 },
1355 vital_signs: None,
1356 health_score: None,
1357 file_scores: vec![],
1358 coverage_gaps: Some(CoverageGaps {
1359 summary: CoverageGapSummary {
1360 runtime_files: 2,
1361 covered_files: 0,
1362 file_coverage_pct: 0.0,
1363 untested_files: 1,
1364 untested_exports: 1,
1365 },
1366 files: vec![UntestedFile {
1367 path: root.join("src/app.ts"),
1368 value_export_count: 2,
1369 }],
1370 exports: vec![UntestedExport {
1371 path: root.join("src/app.ts"),
1372 export_name: "loader".into(),
1373 line: 12,
1374 col: 4,
1375 }],
1376 }),
1377 hotspots: vec![],
1378 hotspot_summary: None,
1379 targets: vec![],
1380 target_thresholds: None,
1381 health_trend: None,
1382 };
1383
1384 let md = build_health_markdown(&report, &root);
1385 assert!(md.contains("### Coverage Gaps"));
1386 assert!(md.contains("*1 untested files"));
1387 assert!(md.contains("`src/app.ts` (2 value exports)"));
1388 assert!(md.contains("`src/app.ts`:12 `loader`"));
1389 }
1390
1391 #[test]
1394 fn markdown_dep_in_workspace_shows_package_label() {
1395 let root = PathBuf::from("/project");
1396 let mut results = AnalysisResults::default();
1397 results.unused_dependencies.push(UnusedDependency {
1398 package_name: "lodash".to_string(),
1399 location: DependencyLocation::Dependencies,
1400 path: root.join("packages/core/package.json"),
1401 line: 5,
1402 });
1403 let md = build_markdown(&results, &root);
1404 assert!(md.contains("(packages/core/package.json)"));
1406 }
1407
1408 #[test]
1409 fn markdown_dep_at_root_no_extra_label() {
1410 let root = PathBuf::from("/project");
1411 let mut results = AnalysisResults::default();
1412 results.unused_dependencies.push(UnusedDependency {
1413 package_name: "lodash".to_string(),
1414 location: DependencyLocation::Dependencies,
1415 path: root.join("package.json"),
1416 line: 5,
1417 });
1418 let md = build_markdown(&results, &root);
1419 assert!(md.contains("- `lodash`"));
1420 assert!(!md.contains("(package.json)"));
1421 }
1422
1423 #[test]
1426 fn markdown_exports_grouped_by_file() {
1427 let root = PathBuf::from("/project");
1428 let mut results = AnalysisResults::default();
1429 results.unused_exports.push(UnusedExport {
1430 path: root.join("src/utils.ts"),
1431 export_name: "alpha".to_string(),
1432 is_type_only: false,
1433 line: 5,
1434 col: 0,
1435 span_start: 0,
1436 is_re_export: false,
1437 });
1438 results.unused_exports.push(UnusedExport {
1439 path: root.join("src/utils.ts"),
1440 export_name: "beta".to_string(),
1441 is_type_only: false,
1442 line: 10,
1443 col: 0,
1444 span_start: 0,
1445 is_re_export: false,
1446 });
1447 results.unused_exports.push(UnusedExport {
1448 path: root.join("src/other.ts"),
1449 export_name: "gamma".to_string(),
1450 is_type_only: false,
1451 line: 1,
1452 col: 0,
1453 span_start: 0,
1454 is_re_export: false,
1455 });
1456 let md = build_markdown(&results, &root);
1457 let utils_count = md.matches("- `src/utils.ts`").count();
1459 assert_eq!(utils_count, 1, "file header should appear once per file");
1460 assert!(md.contains(":5 `alpha`"));
1462 assert!(md.contains(":10 `beta`"));
1463 }
1464
1465 #[test]
1468 fn markdown_multiple_issues_plural() {
1469 let root = PathBuf::from("/project");
1470 let mut results = AnalysisResults::default();
1471 results.unused_files.push(UnusedFile {
1472 path: root.join("src/a.ts"),
1473 });
1474 results.unused_files.push(UnusedFile {
1475 path: root.join("src/b.ts"),
1476 });
1477 let md = build_markdown(&results, &root);
1478 assert!(md.starts_with("## Fallow: 2 issues found\n"));
1479 }
1480
1481 #[test]
1484 fn duplication_markdown_zero_savings_no_suffix() {
1485 let root = PathBuf::from("/project");
1486 let report = DuplicationReport {
1487 clone_groups: vec![CloneGroup {
1488 instances: vec![CloneInstance {
1489 file: root.join("src/a.ts"),
1490 start_line: 1,
1491 end_line: 5,
1492 start_col: 0,
1493 end_col: 0,
1494 fragment: String::new(),
1495 }],
1496 token_count: 30,
1497 line_count: 5,
1498 }],
1499 clone_families: vec![CloneFamily {
1500 files: vec![root.join("src/a.ts")],
1501 groups: vec![],
1502 total_duplicated_lines: 5,
1503 total_duplicated_tokens: 30,
1504 suggestions: vec![RefactoringSuggestion {
1505 kind: RefactoringKind::ExtractFunction,
1506 description: "Extract function".to_string(),
1507 estimated_savings: 0,
1508 }],
1509 }],
1510 mirrored_directories: vec![],
1511 stats: DuplicationStats {
1512 clone_groups: 1,
1513 clone_instances: 1,
1514 duplication_percentage: 1.0,
1515 ..Default::default()
1516 },
1517 };
1518 let md = build_duplication_markdown(&report, &root);
1519 assert!(md.contains("Extract function"));
1520 assert!(!md.contains("lines saved"));
1521 }
1522
1523 #[test]
1526 fn health_markdown_vital_signs_table() {
1527 let root = PathBuf::from("/project");
1528 let report = crate::health_types::HealthReport {
1529 findings: vec![],
1530 summary: crate::health_types::HealthSummary {
1531 files_analyzed: 10,
1532 functions_analyzed: 50,
1533 functions_above_threshold: 0,
1534 max_cyclomatic_threshold: 20,
1535 max_cognitive_threshold: 15,
1536 files_scored: None,
1537 average_maintainability: None,
1538 },
1539 vital_signs: Some(crate::health_types::VitalSigns {
1540 avg_cyclomatic: 3.5,
1541 p90_cyclomatic: 12,
1542 dead_file_pct: Some(5.0),
1543 dead_export_pct: Some(10.2),
1544 duplication_pct: None,
1545 maintainability_avg: Some(72.3),
1546 hotspot_count: Some(3),
1547 circular_dep_count: Some(1),
1548 unused_dep_count: Some(2),
1549 counts: None,
1550 }),
1551 health_score: None,
1552 file_scores: vec![],
1553 coverage_gaps: None,
1554 hotspots: vec![],
1555 hotspot_summary: None,
1556 targets: vec![],
1557 target_thresholds: None,
1558 health_trend: None,
1559 };
1560 let md = build_health_markdown(&report, &root);
1561 assert!(md.contains("## Vital Signs"));
1562 assert!(md.contains("| Metric | Value |"));
1563 assert!(md.contains("| Avg Cyclomatic | 3.5 |"));
1564 assert!(md.contains("| P90 Cyclomatic | 12 |"));
1565 assert!(md.contains("| Dead Files | 5.0% |"));
1566 assert!(md.contains("| Dead Exports | 10.2% |"));
1567 assert!(md.contains("| Maintainability (avg) | 72.3 |"));
1568 assert!(md.contains("| Hotspots | 3 |"));
1569 assert!(md.contains("| Circular Deps | 1 |"));
1570 assert!(md.contains("| Unused Deps | 2 |"));
1571 }
1572
1573 #[test]
1576 fn health_markdown_file_scores_table() {
1577 let root = PathBuf::from("/project");
1578 let report = crate::health_types::HealthReport {
1579 findings: vec![crate::health_types::HealthFinding {
1580 path: root.join("src/dummy.ts"),
1581 name: "fn".to_string(),
1582 line: 1,
1583 col: 0,
1584 cyclomatic: 25,
1585 cognitive: 20,
1586 line_count: 50,
1587 exceeded: crate::health_types::ExceededThreshold::Both,
1588 }],
1589 summary: crate::health_types::HealthSummary {
1590 files_analyzed: 5,
1591 functions_analyzed: 10,
1592 functions_above_threshold: 1,
1593 max_cyclomatic_threshold: 20,
1594 max_cognitive_threshold: 15,
1595 files_scored: Some(1),
1596 average_maintainability: Some(65.0),
1597 },
1598 vital_signs: None,
1599 health_score: None,
1600 file_scores: vec![crate::health_types::FileHealthScore {
1601 path: root.join("src/utils.ts"),
1602 fan_in: 5,
1603 fan_out: 3,
1604 dead_code_ratio: 0.25,
1605 complexity_density: 0.8,
1606 maintainability_index: 72.5,
1607 total_cyclomatic: 40,
1608 total_cognitive: 30,
1609 function_count: 10,
1610 lines: 200,
1611 }],
1612 coverage_gaps: None,
1613 hotspots: vec![],
1614 hotspot_summary: None,
1615 targets: vec![],
1616 target_thresholds: None,
1617 health_trend: None,
1618 };
1619 let md = build_health_markdown(&report, &root);
1620 assert!(md.contains("### File Health Scores (1 files)"));
1621 assert!(md.contains("| File | Maintainability | Fan-in | Fan-out | Dead Code | Density |"));
1622 assert!(md.contains("| `src/utils.ts` | 72.5 | 5 | 3 | 25% | 0.80 |"));
1623 assert!(md.contains("**Average maintainability index:** 65.0/100"));
1624 }
1625
1626 #[test]
1629 fn health_markdown_hotspots_table() {
1630 let root = PathBuf::from("/project");
1631 let report = crate::health_types::HealthReport {
1632 findings: vec![crate::health_types::HealthFinding {
1633 path: root.join("src/dummy.ts"),
1634 name: "fn".to_string(),
1635 line: 1,
1636 col: 0,
1637 cyclomatic: 25,
1638 cognitive: 20,
1639 line_count: 50,
1640 exceeded: crate::health_types::ExceededThreshold::Both,
1641 }],
1642 summary: crate::health_types::HealthSummary {
1643 files_analyzed: 5,
1644 functions_analyzed: 10,
1645 functions_above_threshold: 1,
1646 max_cyclomatic_threshold: 20,
1647 max_cognitive_threshold: 15,
1648 files_scored: None,
1649 average_maintainability: None,
1650 },
1651 vital_signs: None,
1652 health_score: None,
1653 file_scores: vec![],
1654 coverage_gaps: None,
1655 hotspots: vec![crate::health_types::HotspotEntry {
1656 path: root.join("src/hot.ts"),
1657 score: 85.0,
1658 commits: 42,
1659 weighted_commits: 35.0,
1660 lines_added: 500,
1661 lines_deleted: 200,
1662 complexity_density: 1.2,
1663 fan_in: 10,
1664 trend: fallow_core::churn::ChurnTrend::Accelerating,
1665 }],
1666 hotspot_summary: Some(crate::health_types::HotspotSummary {
1667 since: "6 months".to_string(),
1668 min_commits: 3,
1669 files_analyzed: 50,
1670 files_excluded: 5,
1671 shallow_clone: false,
1672 }),
1673 targets: vec![],
1674 target_thresholds: None,
1675 health_trend: None,
1676 };
1677 let md = build_health_markdown(&report, &root);
1678 assert!(md.contains("### Hotspots (1 files, since 6 months)"));
1679 assert!(md.contains("| `src/hot.ts` | 85.0 | 42 | 700 | 1.20 | 10 | accelerating |"));
1680 assert!(md.contains("*5 files excluded (< 3 commits)*"));
1681 }
1682
1683 #[test]
1686 fn health_markdown_metric_legend_with_scores() {
1687 let root = PathBuf::from("/project");
1688 let report = crate::health_types::HealthReport {
1689 findings: vec![crate::health_types::HealthFinding {
1690 path: root.join("src/x.ts"),
1691 name: "f".to_string(),
1692 line: 1,
1693 col: 0,
1694 cyclomatic: 25,
1695 cognitive: 20,
1696 line_count: 10,
1697 exceeded: crate::health_types::ExceededThreshold::Both,
1698 }],
1699 summary: crate::health_types::HealthSummary {
1700 files_analyzed: 1,
1701 functions_analyzed: 1,
1702 functions_above_threshold: 1,
1703 max_cyclomatic_threshold: 20,
1704 max_cognitive_threshold: 15,
1705 files_scored: Some(1),
1706 average_maintainability: Some(70.0),
1707 },
1708 vital_signs: None,
1709 health_score: None,
1710 file_scores: vec![crate::health_types::FileHealthScore {
1711 path: root.join("src/x.ts"),
1712 fan_in: 1,
1713 fan_out: 1,
1714 dead_code_ratio: 0.0,
1715 complexity_density: 0.5,
1716 maintainability_index: 80.0,
1717 total_cyclomatic: 10,
1718 total_cognitive: 8,
1719 function_count: 2,
1720 lines: 50,
1721 }],
1722 coverage_gaps: None,
1723 hotspots: vec![],
1724 hotspot_summary: None,
1725 targets: vec![],
1726 target_thresholds: None,
1727 health_trend: None,
1728 };
1729 let md = build_health_markdown(&report, &root);
1730 assert!(md.contains("<details><summary>Metric definitions</summary>"));
1731 assert!(md.contains("**MI** \u{2014} Maintainability Index"));
1732 assert!(md.contains("**Fan-in**"));
1733 assert!(md.contains("Full metric reference"));
1734 }
1735
1736 #[test]
1739 fn health_markdown_truncated_findings_shown_count() {
1740 let root = PathBuf::from("/project");
1741 let report = crate::health_types::HealthReport {
1742 findings: vec![crate::health_types::HealthFinding {
1743 path: root.join("src/x.ts"),
1744 name: "f".to_string(),
1745 line: 1,
1746 col: 0,
1747 cyclomatic: 25,
1748 cognitive: 20,
1749 line_count: 10,
1750 exceeded: crate::health_types::ExceededThreshold::Both,
1751 }],
1752 summary: crate::health_types::HealthSummary {
1753 files_analyzed: 10,
1754 functions_analyzed: 50,
1755 functions_above_threshold: 5, max_cyclomatic_threshold: 20,
1757 max_cognitive_threshold: 15,
1758 files_scored: None,
1759 average_maintainability: None,
1760 },
1761 vital_signs: None,
1762 health_score: None,
1763 file_scores: vec![],
1764 coverage_gaps: None,
1765 hotspots: vec![],
1766 hotspot_summary: None,
1767 targets: vec![],
1768 target_thresholds: None,
1769 health_trend: None,
1770 };
1771 let md = build_health_markdown(&report, &root);
1772 assert!(md.contains("5 high complexity functions (1 shown)"));
1773 }
1774
1775 #[test]
1778 fn escape_backticks_handles_multiple() {
1779 assert_eq!(escape_backticks("a`b`c"), "a\\`b\\`c");
1780 }
1781
1782 #[test]
1783 fn escape_backticks_no_backticks_unchanged() {
1784 assert_eq!(escape_backticks("hello"), "hello");
1785 }
1786
1787 #[test]
1790 fn markdown_unresolved_import_grouped_by_file() {
1791 let root = PathBuf::from("/project");
1792 let mut results = AnalysisResults::default();
1793 results.unresolved_imports.push(UnresolvedImport {
1794 path: root.join("src/app.ts"),
1795 specifier: "./missing".to_string(),
1796 line: 3,
1797 col: 0,
1798 specifier_col: 0,
1799 });
1800 let md = build_markdown(&results, &root);
1801 assert!(md.contains("### Unresolved imports (1)"));
1802 assert!(md.contains("- `src/app.ts`"));
1803 assert!(md.contains(":3 `./missing`"));
1804 }
1805
1806 #[test]
1809 fn markdown_unused_optional_dep() {
1810 let root = PathBuf::from("/project");
1811 let mut results = AnalysisResults::default();
1812 results.unused_optional_dependencies.push(UnusedDependency {
1813 package_name: "fsevents".to_string(),
1814 location: DependencyLocation::OptionalDependencies,
1815 path: root.join("package.json"),
1816 line: 12,
1817 });
1818 let md = build_markdown(&results, &root);
1819 assert!(md.contains("### Unused optionalDependencies (1)"));
1820 assert!(md.contains("- `fsevents`"));
1821 }
1822
1823 #[test]
1826 fn health_markdown_hotspots_no_excluded_message() {
1827 let root = PathBuf::from("/project");
1828 let report = crate::health_types::HealthReport {
1829 findings: vec![crate::health_types::HealthFinding {
1830 path: root.join("src/x.ts"),
1831 name: "f".to_string(),
1832 line: 1,
1833 col: 0,
1834 cyclomatic: 25,
1835 cognitive: 20,
1836 line_count: 10,
1837 exceeded: crate::health_types::ExceededThreshold::Both,
1838 }],
1839 summary: crate::health_types::HealthSummary {
1840 files_analyzed: 5,
1841 functions_analyzed: 10,
1842 functions_above_threshold: 1,
1843 max_cyclomatic_threshold: 20,
1844 max_cognitive_threshold: 15,
1845 files_scored: None,
1846 average_maintainability: None,
1847 },
1848 vital_signs: None,
1849 health_score: None,
1850 file_scores: vec![],
1851 coverage_gaps: None,
1852 hotspots: vec![crate::health_types::HotspotEntry {
1853 path: root.join("src/hot.ts"),
1854 score: 50.0,
1855 commits: 10,
1856 weighted_commits: 8.0,
1857 lines_added: 100,
1858 lines_deleted: 50,
1859 complexity_density: 0.5,
1860 fan_in: 3,
1861 trend: fallow_core::churn::ChurnTrend::Stable,
1862 }],
1863 hotspot_summary: Some(crate::health_types::HotspotSummary {
1864 since: "6 months".to_string(),
1865 min_commits: 3,
1866 files_analyzed: 50,
1867 files_excluded: 0,
1868 shallow_clone: false,
1869 }),
1870 targets: vec![],
1871 target_thresholds: None,
1872 health_trend: None,
1873 };
1874 let md = build_health_markdown(&report, &root);
1875 assert!(!md.contains("files excluded"));
1876 }
1877
1878 #[test]
1881 fn duplication_markdown_single_group_no_plural() {
1882 let root = PathBuf::from("/project");
1883 let report = DuplicationReport {
1884 clone_groups: vec![CloneGroup {
1885 instances: vec![CloneInstance {
1886 file: root.join("src/a.ts"),
1887 start_line: 1,
1888 end_line: 5,
1889 start_col: 0,
1890 end_col: 0,
1891 fragment: String::new(),
1892 }],
1893 token_count: 30,
1894 line_count: 5,
1895 }],
1896 clone_families: vec![],
1897 mirrored_directories: vec![],
1898 stats: DuplicationStats {
1899 clone_groups: 1,
1900 clone_instances: 1,
1901 duplication_percentage: 2.0,
1902 ..Default::default()
1903 },
1904 };
1905 let md = build_duplication_markdown(&report, &root);
1906 assert!(md.contains("1 clone group found"));
1907 assert!(!md.contains("1 clone groups found"));
1908 }
1909}