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