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 summary: crate::health_types::HealthSummary {
1160 files_analyzed: 10,
1161 functions_analyzed: 50,
1162 ..Default::default()
1163 },
1164 ..Default::default()
1165 };
1166 let md = build_health_markdown(&report, &root);
1167 assert!(md.contains("no functions exceed complexity thresholds"));
1168 assert!(md.contains("**50** functions analyzed"));
1169 }
1170
1171 #[test]
1172 fn health_markdown_table_format() {
1173 let root = PathBuf::from("/project");
1174 let report = crate::health_types::HealthReport {
1175 findings: vec![crate::health_types::HealthFinding {
1176 path: root.join("src/utils.ts"),
1177 name: "parseExpression".to_string(),
1178 line: 42,
1179 col: 0,
1180 cyclomatic: 25,
1181 cognitive: 30,
1182 line_count: 80,
1183 param_count: 0,
1184 exceeded: crate::health_types::ExceededThreshold::Both,
1185 }],
1186 summary: crate::health_types::HealthSummary {
1187 files_analyzed: 10,
1188 functions_analyzed: 50,
1189 functions_above_threshold: 1,
1190 ..Default::default()
1191 },
1192 ..Default::default()
1193 };
1194 let md = build_health_markdown(&report, &root);
1195 assert!(md.contains("## Fallow: 1 high complexity function\n"));
1196 assert!(md.contains("| File | Function |"));
1197 assert!(md.contains("`src/utils.ts:42`"));
1198 assert!(md.contains("`parseExpression`"));
1199 assert!(md.contains("25 **!**"));
1200 assert!(md.contains("30 **!**"));
1201 assert!(md.contains("| 80 |"));
1202 }
1203
1204 #[test]
1205 fn health_markdown_no_marker_when_below_threshold() {
1206 let root = PathBuf::from("/project");
1207 let report = crate::health_types::HealthReport {
1208 findings: vec![crate::health_types::HealthFinding {
1209 path: root.join("src/utils.ts"),
1210 name: "helper".to_string(),
1211 line: 10,
1212 col: 0,
1213 cyclomatic: 15,
1214 cognitive: 20,
1215 line_count: 30,
1216 param_count: 0,
1217 exceeded: crate::health_types::ExceededThreshold::Cognitive,
1218 }],
1219 summary: crate::health_types::HealthSummary {
1220 files_analyzed: 5,
1221 functions_analyzed: 20,
1222 functions_above_threshold: 1,
1223 ..Default::default()
1224 },
1225 ..Default::default()
1226 };
1227 let md = build_health_markdown(&report, &root);
1228 assert!(md.contains("| 15 |"));
1230 assert!(md.contains("20 **!**"));
1232 }
1233
1234 #[test]
1235 fn health_markdown_with_targets() {
1236 use crate::health_types::*;
1237
1238 let root = PathBuf::from("/project");
1239 let report = HealthReport {
1240 summary: HealthSummary {
1241 files_analyzed: 10,
1242 functions_analyzed: 50,
1243 ..Default::default()
1244 },
1245 targets: vec![
1246 RefactoringTarget {
1247 path: PathBuf::from("/project/src/complex.ts"),
1248 priority: 82.5,
1249 efficiency: 27.5,
1250 recommendation: "Split high-impact file".into(),
1251 category: RecommendationCategory::SplitHighImpact,
1252 effort: crate::health_types::EffortEstimate::High,
1253 confidence: crate::health_types::Confidence::Medium,
1254 factors: vec![ContributingFactor {
1255 metric: "fan_in",
1256 value: 25.0,
1257 threshold: 10.0,
1258 detail: "25 files depend on this".into(),
1259 }],
1260 evidence: None,
1261 },
1262 RefactoringTarget {
1263 path: PathBuf::from("/project/src/legacy.ts"),
1264 priority: 45.0,
1265 efficiency: 45.0,
1266 recommendation: "Remove 5 unused exports".into(),
1267 category: RecommendationCategory::RemoveDeadCode,
1268 effort: crate::health_types::EffortEstimate::Low,
1269 confidence: crate::health_types::Confidence::High,
1270 factors: vec![],
1271 evidence: None,
1272 },
1273 ],
1274 ..Default::default()
1275 };
1276 let md = build_health_markdown(&report, &root);
1277
1278 assert!(
1280 md.contains("Refactoring Targets"),
1281 "should contain targets heading"
1282 );
1283 assert!(
1284 md.contains("src/complex.ts"),
1285 "should contain target file path"
1286 );
1287 assert!(md.contains("27.5"), "should contain efficiency score");
1288 assert!(
1289 md.contains("Split high-impact file"),
1290 "should contain recommendation"
1291 );
1292 assert!(md.contains("src/legacy.ts"), "should contain second target");
1293 }
1294
1295 #[test]
1296 fn health_markdown_with_coverage_gaps() {
1297 use crate::health_types::*;
1298
1299 let root = PathBuf::from("/project");
1300 let report = HealthReport {
1301 summary: HealthSummary {
1302 files_analyzed: 10,
1303 functions_analyzed: 50,
1304 ..Default::default()
1305 },
1306 coverage_gaps: Some(CoverageGaps {
1307 summary: CoverageGapSummary {
1308 runtime_files: 2,
1309 covered_files: 0,
1310 file_coverage_pct: 0.0,
1311 untested_files: 1,
1312 untested_exports: 1,
1313 },
1314 files: vec![UntestedFile {
1315 path: root.join("src/app.ts"),
1316 value_export_count: 2,
1317 }],
1318 exports: vec![UntestedExport {
1319 path: root.join("src/app.ts"),
1320 export_name: "loader".into(),
1321 line: 12,
1322 col: 4,
1323 }],
1324 }),
1325 ..Default::default()
1326 };
1327
1328 let md = build_health_markdown(&report, &root);
1329 assert!(md.contains("### Coverage Gaps"));
1330 assert!(md.contains("*1 untested files"));
1331 assert!(md.contains("`src/app.ts` (2 value exports)"));
1332 assert!(md.contains("`src/app.ts`:12 `loader`"));
1333 }
1334
1335 #[test]
1338 fn markdown_dep_in_workspace_shows_package_label() {
1339 let root = PathBuf::from("/project");
1340 let mut results = AnalysisResults::default();
1341 results.unused_dependencies.push(UnusedDependency {
1342 package_name: "lodash".to_string(),
1343 location: DependencyLocation::Dependencies,
1344 path: root.join("packages/core/package.json"),
1345 line: 5,
1346 });
1347 let md = build_markdown(&results, &root);
1348 assert!(md.contains("(packages/core/package.json)"));
1350 }
1351
1352 #[test]
1353 fn markdown_dep_at_root_no_extra_label() {
1354 let root = PathBuf::from("/project");
1355 let mut results = AnalysisResults::default();
1356 results.unused_dependencies.push(UnusedDependency {
1357 package_name: "lodash".to_string(),
1358 location: DependencyLocation::Dependencies,
1359 path: root.join("package.json"),
1360 line: 5,
1361 });
1362 let md = build_markdown(&results, &root);
1363 assert!(md.contains("- `lodash`"));
1364 assert!(!md.contains("(package.json)"));
1365 }
1366
1367 #[test]
1370 fn markdown_exports_grouped_by_file() {
1371 let root = PathBuf::from("/project");
1372 let mut results = AnalysisResults::default();
1373 results.unused_exports.push(UnusedExport {
1374 path: root.join("src/utils.ts"),
1375 export_name: "alpha".to_string(),
1376 is_type_only: false,
1377 line: 5,
1378 col: 0,
1379 span_start: 0,
1380 is_re_export: false,
1381 });
1382 results.unused_exports.push(UnusedExport {
1383 path: root.join("src/utils.ts"),
1384 export_name: "beta".to_string(),
1385 is_type_only: false,
1386 line: 10,
1387 col: 0,
1388 span_start: 0,
1389 is_re_export: false,
1390 });
1391 results.unused_exports.push(UnusedExport {
1392 path: root.join("src/other.ts"),
1393 export_name: "gamma".to_string(),
1394 is_type_only: false,
1395 line: 1,
1396 col: 0,
1397 span_start: 0,
1398 is_re_export: false,
1399 });
1400 let md = build_markdown(&results, &root);
1401 let utils_count = md.matches("- `src/utils.ts`").count();
1403 assert_eq!(utils_count, 1, "file header should appear once per file");
1404 assert!(md.contains(":5 `alpha`"));
1406 assert!(md.contains(":10 `beta`"));
1407 }
1408
1409 #[test]
1412 fn markdown_multiple_issues_plural() {
1413 let root = PathBuf::from("/project");
1414 let mut results = AnalysisResults::default();
1415 results.unused_files.push(UnusedFile {
1416 path: root.join("src/a.ts"),
1417 });
1418 results.unused_files.push(UnusedFile {
1419 path: root.join("src/b.ts"),
1420 });
1421 let md = build_markdown(&results, &root);
1422 assert!(md.starts_with("## Fallow: 2 issues found\n"));
1423 }
1424
1425 #[test]
1428 fn duplication_markdown_zero_savings_no_suffix() {
1429 let root = PathBuf::from("/project");
1430 let report = DuplicationReport {
1431 clone_groups: vec![CloneGroup {
1432 instances: vec![CloneInstance {
1433 file: root.join("src/a.ts"),
1434 start_line: 1,
1435 end_line: 5,
1436 start_col: 0,
1437 end_col: 0,
1438 fragment: String::new(),
1439 }],
1440 token_count: 30,
1441 line_count: 5,
1442 }],
1443 clone_families: vec![CloneFamily {
1444 files: vec![root.join("src/a.ts")],
1445 groups: vec![],
1446 total_duplicated_lines: 5,
1447 total_duplicated_tokens: 30,
1448 suggestions: vec![RefactoringSuggestion {
1449 kind: RefactoringKind::ExtractFunction,
1450 description: "Extract function".to_string(),
1451 estimated_savings: 0,
1452 }],
1453 }],
1454 mirrored_directories: vec![],
1455 stats: DuplicationStats {
1456 clone_groups: 1,
1457 clone_instances: 1,
1458 duplication_percentage: 1.0,
1459 ..Default::default()
1460 },
1461 };
1462 let md = build_duplication_markdown(&report, &root);
1463 assert!(md.contains("Extract function"));
1464 assert!(!md.contains("lines saved"));
1465 }
1466
1467 #[test]
1470 fn health_markdown_vital_signs_table() {
1471 let root = PathBuf::from("/project");
1472 let report = crate::health_types::HealthReport {
1473 summary: crate::health_types::HealthSummary {
1474 files_analyzed: 10,
1475 functions_analyzed: 50,
1476 ..Default::default()
1477 },
1478 vital_signs: Some(crate::health_types::VitalSigns {
1479 avg_cyclomatic: 3.5,
1480 p90_cyclomatic: 12,
1481 dead_file_pct: Some(5.0),
1482 dead_export_pct: Some(10.2),
1483 duplication_pct: None,
1484 maintainability_avg: Some(72.3),
1485 hotspot_count: Some(3),
1486 circular_dep_count: Some(1),
1487 unused_dep_count: Some(2),
1488 counts: None,
1489 unit_size_profile: None,
1490 unit_interfacing_profile: None,
1491 p95_fan_in: None,
1492 coupling_high_pct: None,
1493 }),
1494 ..Default::default()
1495 };
1496 let md = build_health_markdown(&report, &root);
1497 assert!(md.contains("## Vital Signs"));
1498 assert!(md.contains("| Metric | Value |"));
1499 assert!(md.contains("| Avg Cyclomatic | 3.5 |"));
1500 assert!(md.contains("| P90 Cyclomatic | 12 |"));
1501 assert!(md.contains("| Dead Files | 5.0% |"));
1502 assert!(md.contains("| Dead Exports | 10.2% |"));
1503 assert!(md.contains("| Maintainability (avg) | 72.3 |"));
1504 assert!(md.contains("| Hotspots | 3 |"));
1505 assert!(md.contains("| Circular Deps | 1 |"));
1506 assert!(md.contains("| Unused Deps | 2 |"));
1507 }
1508
1509 #[test]
1512 fn health_markdown_file_scores_table() {
1513 let root = PathBuf::from("/project");
1514 let report = crate::health_types::HealthReport {
1515 findings: vec![crate::health_types::HealthFinding {
1516 path: root.join("src/dummy.ts"),
1517 name: "fn".to_string(),
1518 line: 1,
1519 col: 0,
1520 cyclomatic: 25,
1521 cognitive: 20,
1522 line_count: 50,
1523 param_count: 0,
1524 exceeded: crate::health_types::ExceededThreshold::Both,
1525 }],
1526 summary: crate::health_types::HealthSummary {
1527 files_analyzed: 5,
1528 functions_analyzed: 10,
1529 functions_above_threshold: 1,
1530 files_scored: Some(1),
1531 average_maintainability: Some(65.0),
1532 ..Default::default()
1533 },
1534 file_scores: vec![crate::health_types::FileHealthScore {
1535 path: root.join("src/utils.ts"),
1536 fan_in: 5,
1537 fan_out: 3,
1538 dead_code_ratio: 0.25,
1539 complexity_density: 0.8,
1540 maintainability_index: 72.5,
1541 total_cyclomatic: 40,
1542 total_cognitive: 30,
1543 function_count: 10,
1544 lines: 200,
1545 crap_max: 0.0,
1546 crap_above_threshold: 0,
1547 }],
1548 ..Default::default()
1549 };
1550 let md = build_health_markdown(&report, &root);
1551 assert!(md.contains("### File Health Scores (1 files)"));
1552 assert!(md.contains("| File | Maintainability | Fan-in | Fan-out | Dead Code | Density |"));
1553 assert!(md.contains("| `src/utils.ts` | 72.5 | 5 | 3 | 25% | 0.80 |"));
1554 assert!(md.contains("**Average maintainability index:** 65.0/100"));
1555 }
1556
1557 #[test]
1560 fn health_markdown_hotspots_table() {
1561 let root = PathBuf::from("/project");
1562 let report = crate::health_types::HealthReport {
1563 findings: vec![crate::health_types::HealthFinding {
1564 path: root.join("src/dummy.ts"),
1565 name: "fn".to_string(),
1566 line: 1,
1567 col: 0,
1568 cyclomatic: 25,
1569 cognitive: 20,
1570 line_count: 50,
1571 param_count: 0,
1572 exceeded: crate::health_types::ExceededThreshold::Both,
1573 }],
1574 summary: crate::health_types::HealthSummary {
1575 files_analyzed: 5,
1576 functions_analyzed: 10,
1577 functions_above_threshold: 1,
1578 ..Default::default()
1579 },
1580 hotspots: vec![crate::health_types::HotspotEntry {
1581 path: root.join("src/hot.ts"),
1582 score: 85.0,
1583 commits: 42,
1584 weighted_commits: 35.0,
1585 lines_added: 500,
1586 lines_deleted: 200,
1587 complexity_density: 1.2,
1588 fan_in: 10,
1589 trend: fallow_core::churn::ChurnTrend::Accelerating,
1590 }],
1591 hotspot_summary: Some(crate::health_types::HotspotSummary {
1592 since: "6 months".to_string(),
1593 min_commits: 3,
1594 files_analyzed: 50,
1595 files_excluded: 5,
1596 shallow_clone: false,
1597 }),
1598 ..Default::default()
1599 };
1600 let md = build_health_markdown(&report, &root);
1601 assert!(md.contains("### Hotspots (1 files, since 6 months)"));
1602 assert!(md.contains("| `src/hot.ts` | 85.0 | 42 | 700 | 1.20 | 10 | accelerating |"));
1603 assert!(md.contains("*5 files excluded (< 3 commits)*"));
1604 }
1605
1606 #[test]
1609 fn health_markdown_metric_legend_with_scores() {
1610 let root = PathBuf::from("/project");
1611 let report = crate::health_types::HealthReport {
1612 findings: vec![crate::health_types::HealthFinding {
1613 path: root.join("src/x.ts"),
1614 name: "f".to_string(),
1615 line: 1,
1616 col: 0,
1617 cyclomatic: 25,
1618 cognitive: 20,
1619 line_count: 10,
1620 param_count: 0,
1621 exceeded: crate::health_types::ExceededThreshold::Both,
1622 }],
1623 summary: crate::health_types::HealthSummary {
1624 files_analyzed: 1,
1625 functions_analyzed: 1,
1626 functions_above_threshold: 1,
1627 files_scored: Some(1),
1628 average_maintainability: Some(70.0),
1629 ..Default::default()
1630 },
1631 file_scores: vec![crate::health_types::FileHealthScore {
1632 path: root.join("src/x.ts"),
1633 fan_in: 1,
1634 fan_out: 1,
1635 dead_code_ratio: 0.0,
1636 complexity_density: 0.5,
1637 maintainability_index: 80.0,
1638 total_cyclomatic: 10,
1639 total_cognitive: 8,
1640 function_count: 2,
1641 lines: 50,
1642 crap_max: 0.0,
1643 crap_above_threshold: 0,
1644 }],
1645 ..Default::default()
1646 };
1647 let md = build_health_markdown(&report, &root);
1648 assert!(md.contains("<details><summary>Metric definitions</summary>"));
1649 assert!(md.contains("**MI** \u{2014} Maintainability Index"));
1650 assert!(md.contains("**Fan-in**"));
1651 assert!(md.contains("Full metric reference"));
1652 }
1653
1654 #[test]
1657 fn health_markdown_truncated_findings_shown_count() {
1658 let root = PathBuf::from("/project");
1659 let report = crate::health_types::HealthReport {
1660 findings: vec![crate::health_types::HealthFinding {
1661 path: root.join("src/x.ts"),
1662 name: "f".to_string(),
1663 line: 1,
1664 col: 0,
1665 cyclomatic: 25,
1666 cognitive: 20,
1667 line_count: 10,
1668 param_count: 0,
1669 exceeded: crate::health_types::ExceededThreshold::Both,
1670 }],
1671 summary: crate::health_types::HealthSummary {
1672 files_analyzed: 10,
1673 functions_analyzed: 50,
1674 functions_above_threshold: 5, ..Default::default()
1676 },
1677 ..Default::default()
1678 };
1679 let md = build_health_markdown(&report, &root);
1680 assert!(md.contains("5 high complexity functions (1 shown)"));
1681 }
1682
1683 #[test]
1686 fn escape_backticks_handles_multiple() {
1687 assert_eq!(escape_backticks("a`b`c"), "a\\`b\\`c");
1688 }
1689
1690 #[test]
1691 fn escape_backticks_no_backticks_unchanged() {
1692 assert_eq!(escape_backticks("hello"), "hello");
1693 }
1694
1695 #[test]
1698 fn markdown_unresolved_import_grouped_by_file() {
1699 let root = PathBuf::from("/project");
1700 let mut results = AnalysisResults::default();
1701 results.unresolved_imports.push(UnresolvedImport {
1702 path: root.join("src/app.ts"),
1703 specifier: "./missing".to_string(),
1704 line: 3,
1705 col: 0,
1706 specifier_col: 0,
1707 });
1708 let md = build_markdown(&results, &root);
1709 assert!(md.contains("### Unresolved imports (1)"));
1710 assert!(md.contains("- `src/app.ts`"));
1711 assert!(md.contains(":3 `./missing`"));
1712 }
1713
1714 #[test]
1717 fn markdown_unused_optional_dep() {
1718 let root = PathBuf::from("/project");
1719 let mut results = AnalysisResults::default();
1720 results.unused_optional_dependencies.push(UnusedDependency {
1721 package_name: "fsevents".to_string(),
1722 location: DependencyLocation::OptionalDependencies,
1723 path: root.join("package.json"),
1724 line: 12,
1725 });
1726 let md = build_markdown(&results, &root);
1727 assert!(md.contains("### Unused optionalDependencies (1)"));
1728 assert!(md.contains("- `fsevents`"));
1729 }
1730
1731 #[test]
1734 fn health_markdown_hotspots_no_excluded_message() {
1735 let root = PathBuf::from("/project");
1736 let report = crate::health_types::HealthReport {
1737 findings: vec![crate::health_types::HealthFinding {
1738 path: root.join("src/x.ts"),
1739 name: "f".to_string(),
1740 line: 1,
1741 col: 0,
1742 cyclomatic: 25,
1743 cognitive: 20,
1744 line_count: 10,
1745 param_count: 0,
1746 exceeded: crate::health_types::ExceededThreshold::Both,
1747 }],
1748 summary: crate::health_types::HealthSummary {
1749 files_analyzed: 5,
1750 functions_analyzed: 10,
1751 functions_above_threshold: 1,
1752 ..Default::default()
1753 },
1754 hotspots: vec![crate::health_types::HotspotEntry {
1755 path: root.join("src/hot.ts"),
1756 score: 50.0,
1757 commits: 10,
1758 weighted_commits: 8.0,
1759 lines_added: 100,
1760 lines_deleted: 50,
1761 complexity_density: 0.5,
1762 fan_in: 3,
1763 trend: fallow_core::churn::ChurnTrend::Stable,
1764 }],
1765 hotspot_summary: Some(crate::health_types::HotspotSummary {
1766 since: "6 months".to_string(),
1767 min_commits: 3,
1768 files_analyzed: 50,
1769 files_excluded: 0,
1770 shallow_clone: false,
1771 }),
1772 ..Default::default()
1773 };
1774 let md = build_health_markdown(&report, &root);
1775 assert!(!md.contains("files excluded"));
1776 }
1777
1778 #[test]
1781 fn duplication_markdown_single_group_no_plural() {
1782 let root = PathBuf::from("/project");
1783 let report = DuplicationReport {
1784 clone_groups: vec![CloneGroup {
1785 instances: vec![CloneInstance {
1786 file: root.join("src/a.ts"),
1787 start_line: 1,
1788 end_line: 5,
1789 start_col: 0,
1790 end_col: 0,
1791 fragment: String::new(),
1792 }],
1793 token_count: 30,
1794 line_count: 5,
1795 }],
1796 clone_families: vec![],
1797 mirrored_directories: vec![],
1798 stats: DuplicationStats {
1799 clone_groups: 1,
1800 clone_instances: 1,
1801 duplication_percentage: 2.0,
1802 ..Default::default()
1803 },
1804 };
1805 let md = build_duplication_markdown(&report, &root);
1806 assert!(md.contains("1 clone group found"));
1807 assert!(!md.contains("1 clone groups found"));
1808 }
1809}