1use std::fmt::Write;
2use std::path::Path;
3
4use fallow_core::duplicates::DuplicationReport;
5use fallow_core::results::{AnalysisResults, UnusedExport, UnusedMember};
6
7use super::{normalize_uri, relative_path};
8
9fn escape_backticks(s: &str) -> String {
11 s.replace('`', "\\`")
12}
13
14pub(super) fn print_markdown(results: &AnalysisResults, root: &Path) {
15 println!("{}", build_markdown(results, root));
16}
17
18pub fn build_markdown(results: &AnalysisResults, root: &Path) -> String {
20 let rel = |p: &Path| {
21 escape_backticks(&normalize_uri(
22 &relative_path(p, root).display().to_string(),
23 ))
24 };
25
26 let total = results.total_issues();
27 let mut out = String::new();
28
29 if total == 0 {
30 out.push_str("## Fallow: no issues found\n");
31 return out;
32 }
33
34 let _ = write!(
35 out,
36 "## Fallow: {total} issue{} found\n\n",
37 if total == 1 { "" } else { "s" }
38 );
39
40 markdown_section(&mut out, &results.unused_files, "Unused files", |file| {
42 vec![format!("- `{}`", rel(&file.path))]
43 });
44
45 markdown_grouped_section(
47 &mut out,
48 &results.unused_exports,
49 "Unused exports",
50 root,
51 |e| e.path.as_path(),
52 format_export,
53 );
54
55 markdown_grouped_section(
57 &mut out,
58 &results.unused_types,
59 "Unused type exports",
60 root,
61 |e| e.path.as_path(),
62 format_export,
63 );
64
65 markdown_section(
67 &mut out,
68 &results.unused_dependencies,
69 "Unused dependencies",
70 |dep| format_dependency(&dep.package_name, &dep.path, root),
71 );
72
73 markdown_section(
75 &mut out,
76 &results.unused_dev_dependencies,
77 "Unused devDependencies",
78 |dep| format_dependency(&dep.package_name, &dep.path, root),
79 );
80
81 markdown_section(
83 &mut out,
84 &results.unused_optional_dependencies,
85 "Unused optionalDependencies",
86 |dep| format_dependency(&dep.package_name, &dep.path, root),
87 );
88
89 markdown_grouped_section(
91 &mut out,
92 &results.unused_enum_members,
93 "Unused enum members",
94 root,
95 |m| m.path.as_path(),
96 format_member,
97 );
98
99 markdown_grouped_section(
101 &mut out,
102 &results.unused_class_members,
103 "Unused class members",
104 root,
105 |m| m.path.as_path(),
106 format_member,
107 );
108
109 markdown_grouped_section(
111 &mut out,
112 &results.unresolved_imports,
113 "Unresolved imports",
114 root,
115 |i| i.path.as_path(),
116 |i| format!(":{} `{}`", i.line, escape_backticks(&i.specifier)),
117 );
118
119 markdown_section(
121 &mut out,
122 &results.unlisted_dependencies,
123 "Unlisted dependencies",
124 |dep| vec![format!("- `{}`", escape_backticks(&dep.package_name))],
125 );
126
127 markdown_section(
129 &mut out,
130 &results.duplicate_exports,
131 "Duplicate exports",
132 |dup| {
133 let locations: Vec<String> = dup
134 .locations
135 .iter()
136 .map(|loc| format!("`{}`", rel(&loc.path)))
137 .collect();
138 vec![format!(
139 "- `{}` in {}",
140 escape_backticks(&dup.export_name),
141 locations.join(", ")
142 )]
143 },
144 );
145
146 markdown_section(
148 &mut out,
149 &results.type_only_dependencies,
150 "Type-only dependencies (consider moving to devDependencies)",
151 |dep| format_dependency(&dep.package_name, &dep.path, root),
152 );
153
154 markdown_section(
156 &mut out,
157 &results.circular_dependencies,
158 "Circular dependencies",
159 |cycle| {
160 let chain: Vec<String> = cycle.files.iter().map(|p| rel(p)).collect();
161 let mut display_chain = chain.clone();
162 if let Some(first) = chain.first() {
163 display_chain.push(first.clone());
164 }
165 vec![format!(
166 "- {}",
167 display_chain
168 .iter()
169 .map(|s| format!("`{s}`"))
170 .collect::<Vec<_>>()
171 .join(" \u{2192} ")
172 )]
173 },
174 );
175
176 out
177}
178
179fn format_export(e: &UnusedExport) -> String {
180 let re = if e.is_re_export { " (re-export)" } else { "" };
181 format!(":{} `{}`{re}", e.line, escape_backticks(&e.export_name))
182}
183
184fn format_member(m: &UnusedMember) -> String {
185 format!(
186 ":{} `{}.{}`",
187 m.line,
188 escape_backticks(&m.parent_name),
189 escape_backticks(&m.member_name)
190 )
191}
192
193fn format_dependency(dep_name: &str, pkg_path: &Path, root: &Path) -> Vec<String> {
194 let name = escape_backticks(dep_name);
195 let pkg_label = relative_path(pkg_path, root).display().to_string();
196 if pkg_label == "package.json" {
197 vec![format!("- `{name}`")]
198 } else {
199 let label = escape_backticks(&pkg_label);
200 vec![format!("- `{name}` ({label})")]
201 }
202}
203
204fn markdown_section<T>(
206 out: &mut String,
207 items: &[T],
208 title: &str,
209 format_lines: impl Fn(&T) -> Vec<String>,
210) {
211 if items.is_empty() {
212 return;
213 }
214 let _ = write!(out, "### {title} ({})\n\n", items.len());
215 for item in items {
216 for line in format_lines(item) {
217 out.push_str(&line);
218 out.push('\n');
219 }
220 }
221 out.push('\n');
222}
223
224fn markdown_grouped_section<'a, T>(
226 out: &mut String,
227 items: &'a [T],
228 title: &str,
229 root: &Path,
230 get_path: impl Fn(&'a T) -> &'a Path,
231 format_detail: impl Fn(&T) -> String,
232) {
233 if items.is_empty() {
234 return;
235 }
236 let _ = write!(out, "### {title} ({})\n\n", items.len());
237
238 let mut indices: Vec<usize> = (0..items.len()).collect();
239 indices.sort_by(|&a, &b| get_path(&items[a]).cmp(get_path(&items[b])));
240
241 let rel = |p: &Path| normalize_uri(&relative_path(p, root).display().to_string());
242 let mut last_file = String::new();
243 for &i in &indices {
244 let item = &items[i];
245 let file_str = rel(get_path(item));
246 if file_str != last_file {
247 let _ = writeln!(out, "- `{file_str}`");
248 last_file = file_str;
249 }
250 let _ = writeln!(out, " - {}", format_detail(item));
251 }
252 out.push('\n');
253}
254
255pub(super) fn print_duplication_markdown(report: &DuplicationReport, root: &Path) {
258 println!("{}", build_duplication_markdown(report, root));
259}
260
261pub fn build_duplication_markdown(report: &DuplicationReport, root: &Path) -> String {
263 let rel = |p: &Path| normalize_uri(&relative_path(p, root).display().to_string());
264
265 let mut out = String::new();
266
267 if report.clone_groups.is_empty() {
268 out.push_str("## Fallow: no code duplication found\n");
269 return out;
270 }
271
272 let stats = &report.stats;
273 let _ = write!(
274 out,
275 "## Fallow: {} clone group{} found ({:.1}% duplication)\n\n",
276 stats.clone_groups,
277 if stats.clone_groups == 1 { "" } else { "s" },
278 stats.duplication_percentage,
279 );
280
281 out.push_str("### Duplicates\n\n");
282 for (i, group) in report.clone_groups.iter().enumerate() {
283 let instance_count = group.instances.len();
284 let _ = write!(
285 out,
286 "**Clone group {}** ({} lines, {instance_count} instance{})\n\n",
287 i + 1,
288 group.line_count,
289 if instance_count == 1 { "" } else { "s" }
290 );
291 for instance in &group.instances {
292 let relative = rel(&instance.file);
293 let _ = writeln!(
294 out,
295 "- `{relative}:{}-{}`",
296 instance.start_line, instance.end_line
297 );
298 }
299 out.push('\n');
300 }
301
302 if !report.clone_families.is_empty() {
304 out.push_str("### Clone Families\n\n");
305 for (i, family) in report.clone_families.iter().enumerate() {
306 let file_names: Vec<_> = family.files.iter().map(|f| rel(f)).collect();
307 let _ = write!(
308 out,
309 "**Family {}** ({} group{}, {} lines across {})\n\n",
310 i + 1,
311 family.groups.len(),
312 if family.groups.len() == 1 { "" } else { "s" },
313 family.total_duplicated_lines,
314 file_names
315 .iter()
316 .map(|s| format!("`{s}`"))
317 .collect::<Vec<_>>()
318 .join(", "),
319 );
320 for suggestion in &family.suggestions {
321 let savings = if suggestion.estimated_savings > 0 {
322 format!(" (~{} lines saved)", suggestion.estimated_savings)
323 } else {
324 String::new()
325 };
326 let _ = writeln!(out, "- {}{savings}", suggestion.description);
327 }
328 out.push('\n');
329 }
330 }
331
332 let _ = writeln!(
334 out,
335 "**Summary:** {} duplicated lines ({:.1}%) across {} file{}",
336 stats.duplicated_lines,
337 stats.duplication_percentage,
338 stats.files_with_clones,
339 if stats.files_with_clones == 1 {
340 ""
341 } else {
342 "s"
343 },
344 );
345
346 out
347}
348
349pub(super) fn print_health_markdown(report: &crate::health_types::HealthReport, root: &Path) {
352 println!("{}", build_health_markdown(report, root));
353}
354
355pub fn build_health_markdown(report: &crate::health_types::HealthReport, root: &Path) -> String {
357 let rel = |p: &Path| {
358 escape_backticks(&normalize_uri(
359 &relative_path(p, root).display().to_string(),
360 ))
361 };
362
363 let mut out = String::new();
364
365 if report.findings.is_empty()
366 && report.file_scores.is_empty()
367 && report.hotspots.is_empty()
368 && report.targets.is_empty()
369 {
370 let _ = write!(
371 out,
372 "## Fallow: no functions exceed complexity thresholds\n\n\
373 **{}** functions analyzed (max cyclomatic: {}, max cognitive: {})\n",
374 report.summary.functions_analyzed,
375 report.summary.max_cyclomatic_threshold,
376 report.summary.max_cognitive_threshold,
377 );
378 return out;
379 }
380
381 if !report.findings.is_empty() {
382 let count = report.summary.functions_above_threshold;
383 let shown = report.findings.len();
384 if shown < count {
385 let _ = write!(
386 out,
387 "## Fallow: {count} high complexity function{} ({shown} shown)\n\n",
388 if count == 1 { "" } else { "s" },
389 );
390 } else {
391 let _ = write!(
392 out,
393 "## Fallow: {count} high complexity function{}\n\n",
394 if count == 1 { "" } else { "s" },
395 );
396 }
397
398 out.push_str("| File | Function | Cyclomatic | Cognitive | Lines |\n");
399 out.push_str("|:-----|:---------|:-----------|:----------|:------|\n");
400
401 for finding in &report.findings {
402 let file_str = rel(&finding.path);
403 let cyc_marker = if finding.cyclomatic > report.summary.max_cyclomatic_threshold {
404 " **!**"
405 } else {
406 ""
407 };
408 let cog_marker = if finding.cognitive > report.summary.max_cognitive_threshold {
409 " **!**"
410 } else {
411 ""
412 };
413 let _ = writeln!(
414 out,
415 "| `{file_str}:{line}` | `{name}` | {cyc}{cyc_marker} | {cog}{cog_marker} | {lines} |",
416 line = finding.line,
417 name = escape_backticks(&finding.name),
418 cyc = finding.cyclomatic,
419 cog = finding.cognitive,
420 lines = finding.line_count,
421 );
422 }
423
424 let s = &report.summary;
425 let _ = write!(
426 out,
427 "\n**{files}** files, **{funcs}** functions analyzed \
428 (thresholds: cyclomatic > {cyc}, cognitive > {cog})\n",
429 files = s.files_analyzed,
430 funcs = s.functions_analyzed,
431 cyc = s.max_cyclomatic_threshold,
432 cog = s.max_cognitive_threshold,
433 );
434 }
435
436 if !report.file_scores.is_empty() {
438 out.push('\n');
439 let _ = writeln!(
440 out,
441 "### File Health Scores ({} files)\n",
442 report.file_scores.len(),
443 );
444 out.push_str("| File | MI | Fan-in | Fan-out | Dead Code | Density |\n");
445 out.push_str("|:-----|:---|:-------|:--------|:----------|:--------|\n");
446
447 for score in &report.file_scores {
448 let file_str = rel(&score.path);
449 let _ = writeln!(
450 out,
451 "| `{file_str}` | {mi:.1} | {fi} | {fan_out} | {dead:.0}% | {density:.2} |",
452 mi = score.maintainability_index,
453 fi = score.fan_in,
454 fan_out = score.fan_out,
455 dead = score.dead_code_ratio * 100.0,
456 density = score.complexity_density,
457 );
458 }
459
460 if let Some(avg) = report.summary.average_maintainability {
461 let _ = write!(out, "\n**Average maintainability index:** {avg:.1}/100\n");
462 }
463 }
464
465 if !report.hotspots.is_empty() {
467 out.push('\n');
468 let header = if let Some(ref summary) = report.hotspot_summary {
469 format!(
470 "### Hotspots ({} files, since {})\n",
471 report.hotspots.len(),
472 summary.since,
473 )
474 } else {
475 format!("### Hotspots ({} files)\n", report.hotspots.len())
476 };
477 let _ = writeln!(out, "{header}");
478 out.push_str("| File | Score | Commits | Churn | Density | Fan-in | Trend |\n");
479 out.push_str("|:-----|:------|:--------|:------|:--------|:-------|:------|\n");
480
481 for entry in &report.hotspots {
482 let file_str = rel(&entry.path);
483 let _ = writeln!(
484 out,
485 "| `{file_str}` | {score:.1} | {commits} | {churn} | {density:.2} | {fi} | {trend} |",
486 score = entry.score,
487 commits = entry.commits,
488 churn = entry.lines_added + entry.lines_deleted,
489 density = entry.complexity_density,
490 fi = entry.fan_in,
491 trend = entry.trend,
492 );
493 }
494
495 if let Some(ref summary) = report.hotspot_summary
496 && summary.files_excluded > 0
497 {
498 let _ = write!(
499 out,
500 "\n*{} file{} excluded (< {} commits)*\n",
501 summary.files_excluded,
502 if summary.files_excluded == 1 { "" } else { "s" },
503 summary.min_commits,
504 );
505 }
506 }
507
508 if !report.targets.is_empty() {
510 let _ = write!(
511 out,
512 "\n### Refactoring Targets ({})\n\n",
513 report.targets.len()
514 );
515 out.push_str("| Priority | Category | Effort | File | Recommendation |\n");
516 out.push_str("|----------|----------|--------|------|----------------|\n");
517 for target in &report.targets {
518 let file_str = normalize_uri(&relative_path(&target.path, root).display().to_string());
519 let category = target.category.label();
520 let effort = target.effort.label();
521 let _ = writeln!(
522 out,
523 "| {:.1} | {category} | {effort} | `{file_str}` | {} |",
524 target.priority, target.recommendation,
525 );
526 }
527 }
528
529 let has_scores = !report.file_scores.is_empty();
531 let has_hotspots = !report.hotspots.is_empty();
532 let has_targets = !report.targets.is_empty();
533 if has_scores || has_hotspots || has_targets {
534 out.push_str("\n---\n\n<details><summary>Metric definitions</summary>\n\n");
535 if has_scores {
536 out.push_str("- **MI** — Maintainability Index (0\u{2013}100, higher is better)\n");
537 out.push_str("- **Fan-in** — files that import this file (blast radius)\n");
538 out.push_str("- **Fan-out** — files this file imports (coupling)\n");
539 out.push_str("- **Dead Code** — % of value exports with zero references\n");
540 out.push_str("- **Density** — cyclomatic complexity / lines of code\n");
541 }
542 if has_hotspots {
543 out.push_str(
544 "- **Score** — churn \u{00d7} complexity (0\u{2013}100, higher = riskier)\n",
545 );
546 out.push_str("- **Commits** — commits in the analysis window\n");
547 out.push_str("- **Churn** — total lines added + deleted\n");
548 out.push_str("- **Trend** — accelerating / stable / cooling\n");
549 }
550 if has_targets {
551 out.push_str("- **Priority** — weighted refactoring urgency (0\u{2013}100, higher = more urgent)\n");
552 out.push_str("- **Category** — recommendation type (churn+complexity, high impact, dead code, complexity, coupling, circular dep)\n");
553 out.push_str("- **Effort** — estimated effort (low / medium / high) based on file size, function count, and fan-in\n");
554 }
555 out.push_str("\n[Full metric reference](https://docs.fallow.tools/explanations/metrics)\n\n</details>\n");
556 }
557
558 out
559}
560
561#[cfg(test)]
562mod tests {
563 use super::*;
564 use fallow_core::duplicates::{
565 CloneFamily, CloneGroup, CloneInstance, DuplicationReport, DuplicationStats,
566 RefactoringKind, RefactoringSuggestion,
567 };
568 use fallow_core::extract::MemberKind;
569 use fallow_core::results::*;
570 use std::path::PathBuf;
571
572 fn sample_results(root: &Path) -> AnalysisResults {
574 let mut r = AnalysisResults::default();
575
576 r.unused_files.push(UnusedFile {
577 path: root.join("src/dead.ts"),
578 });
579 r.unused_exports.push(UnusedExport {
580 path: root.join("src/utils.ts"),
581 export_name: "helperFn".to_string(),
582 is_type_only: false,
583 line: 10,
584 col: 4,
585 span_start: 120,
586 is_re_export: false,
587 });
588 r.unused_types.push(UnusedExport {
589 path: root.join("src/types.ts"),
590 export_name: "OldType".to_string(),
591 is_type_only: true,
592 line: 5,
593 col: 0,
594 span_start: 60,
595 is_re_export: false,
596 });
597 r.unused_dependencies.push(UnusedDependency {
598 package_name: "lodash".to_string(),
599 location: DependencyLocation::Dependencies,
600 path: root.join("package.json"),
601 line: 5,
602 });
603 r.unused_dev_dependencies.push(UnusedDependency {
604 package_name: "jest".to_string(),
605 location: DependencyLocation::DevDependencies,
606 path: root.join("package.json"),
607 line: 5,
608 });
609 r.unused_enum_members.push(UnusedMember {
610 path: root.join("src/enums.ts"),
611 parent_name: "Status".to_string(),
612 member_name: "Deprecated".to_string(),
613 kind: MemberKind::EnumMember,
614 line: 8,
615 col: 2,
616 });
617 r.unused_class_members.push(UnusedMember {
618 path: root.join("src/service.ts"),
619 parent_name: "UserService".to_string(),
620 member_name: "legacyMethod".to_string(),
621 kind: MemberKind::ClassMethod,
622 line: 42,
623 col: 4,
624 });
625 r.unresolved_imports.push(UnresolvedImport {
626 path: root.join("src/app.ts"),
627 specifier: "./missing-module".to_string(),
628 line: 3,
629 col: 0,
630 specifier_col: 0,
631 });
632 r.unlisted_dependencies.push(UnlistedDependency {
633 package_name: "chalk".to_string(),
634 imported_from: vec![ImportSite {
635 path: root.join("src/cli.ts"),
636 line: 2,
637 col: 0,
638 }],
639 });
640 r.duplicate_exports.push(DuplicateExport {
641 export_name: "Config".to_string(),
642 locations: vec![
643 DuplicateLocation {
644 path: root.join("src/config.ts"),
645 line: 15,
646 col: 0,
647 },
648 DuplicateLocation {
649 path: root.join("src/types.ts"),
650 line: 30,
651 col: 0,
652 },
653 ],
654 });
655 r.type_only_dependencies.push(TypeOnlyDependency {
656 package_name: "zod".to_string(),
657 path: root.join("package.json"),
658 line: 8,
659 });
660 r.circular_dependencies.push(CircularDependency {
661 files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
662 length: 2,
663 line: 3,
664 col: 0,
665 });
666
667 r
668 }
669
670 #[test]
671 fn markdown_empty_results_no_issues() {
672 let root = PathBuf::from("/project");
673 let results = AnalysisResults::default();
674 let md = build_markdown(&results, &root);
675 assert_eq!(md, "## Fallow: no issues found\n");
676 }
677
678 #[test]
679 fn markdown_contains_header_with_count() {
680 let root = PathBuf::from("/project");
681 let results = sample_results(&root);
682 let md = build_markdown(&results, &root);
683 assert!(md.starts_with(&format!(
684 "## Fallow: {} issues found\n",
685 results.total_issues()
686 )));
687 }
688
689 #[test]
690 fn markdown_contains_all_sections() {
691 let root = PathBuf::from("/project");
692 let results = sample_results(&root);
693 let md = build_markdown(&results, &root);
694
695 assert!(md.contains("### Unused files (1)"));
696 assert!(md.contains("### Unused exports (1)"));
697 assert!(md.contains("### Unused type exports (1)"));
698 assert!(md.contains("### Unused dependencies (1)"));
699 assert!(md.contains("### Unused devDependencies (1)"));
700 assert!(md.contains("### Unused enum members (1)"));
701 assert!(md.contains("### Unused class members (1)"));
702 assert!(md.contains("### Unresolved imports (1)"));
703 assert!(md.contains("### Unlisted dependencies (1)"));
704 assert!(md.contains("### Duplicate exports (1)"));
705 assert!(md.contains("### Type-only dependencies"));
706 assert!(md.contains("### Circular dependencies (1)"));
707 }
708
709 #[test]
710 fn markdown_unused_file_format() {
711 let root = PathBuf::from("/project");
712 let mut results = AnalysisResults::default();
713 results.unused_files.push(UnusedFile {
714 path: root.join("src/dead.ts"),
715 });
716 let md = build_markdown(&results, &root);
717 assert!(md.contains("- `src/dead.ts`"));
718 }
719
720 #[test]
721 fn markdown_unused_export_grouped_by_file() {
722 let root = PathBuf::from("/project");
723 let mut results = AnalysisResults::default();
724 results.unused_exports.push(UnusedExport {
725 path: root.join("src/utils.ts"),
726 export_name: "helperFn".to_string(),
727 is_type_only: false,
728 line: 10,
729 col: 4,
730 span_start: 120,
731 is_re_export: false,
732 });
733 let md = build_markdown(&results, &root);
734 assert!(md.contains("- `src/utils.ts`"));
735 assert!(md.contains(":10 `helperFn`"));
736 }
737
738 #[test]
739 fn markdown_re_export_tagged() {
740 let root = PathBuf::from("/project");
741 let mut results = AnalysisResults::default();
742 results.unused_exports.push(UnusedExport {
743 path: root.join("src/index.ts"),
744 export_name: "reExported".to_string(),
745 is_type_only: false,
746 line: 1,
747 col: 0,
748 span_start: 0,
749 is_re_export: true,
750 });
751 let md = build_markdown(&results, &root);
752 assert!(md.contains("(re-export)"));
753 }
754
755 #[test]
756 fn markdown_unused_dep_format() {
757 let root = PathBuf::from("/project");
758 let mut results = AnalysisResults::default();
759 results.unused_dependencies.push(UnusedDependency {
760 package_name: "lodash".to_string(),
761 location: DependencyLocation::Dependencies,
762 path: root.join("package.json"),
763 line: 5,
764 });
765 let md = build_markdown(&results, &root);
766 assert!(md.contains("- `lodash`"));
767 }
768
769 #[test]
770 fn markdown_circular_dep_format() {
771 let root = PathBuf::from("/project");
772 let mut results = AnalysisResults::default();
773 results.circular_dependencies.push(CircularDependency {
774 files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
775 length: 2,
776 line: 3,
777 col: 0,
778 });
779 let md = build_markdown(&results, &root);
780 assert!(md.contains("`src/a.ts`"));
781 assert!(md.contains("`src/b.ts`"));
782 assert!(md.contains("\u{2192}"));
783 }
784
785 #[test]
786 fn markdown_strips_root_prefix() {
787 let root = PathBuf::from("/project");
788 let mut results = AnalysisResults::default();
789 results.unused_files.push(UnusedFile {
790 path: PathBuf::from("/project/src/deep/nested/file.ts"),
791 });
792 let md = build_markdown(&results, &root);
793 assert!(md.contains("`src/deep/nested/file.ts`"));
794 assert!(!md.contains("/project/"));
795 }
796
797 #[test]
798 fn markdown_single_issue_no_plural() {
799 let root = PathBuf::from("/project");
800 let mut results = AnalysisResults::default();
801 results.unused_files.push(UnusedFile {
802 path: root.join("src/dead.ts"),
803 });
804 let md = build_markdown(&results, &root);
805 assert!(md.starts_with("## Fallow: 1 issue found\n"));
806 }
807
808 #[test]
809 fn markdown_type_only_dep_format() {
810 let root = PathBuf::from("/project");
811 let mut results = AnalysisResults::default();
812 results.type_only_dependencies.push(TypeOnlyDependency {
813 package_name: "zod".to_string(),
814 path: root.join("package.json"),
815 line: 8,
816 });
817 let md = build_markdown(&results, &root);
818 assert!(md.contains("### Type-only dependencies"));
819 assert!(md.contains("- `zod`"));
820 }
821
822 #[test]
823 fn markdown_escapes_backticks_in_export_names() {
824 let root = PathBuf::from("/project");
825 let mut results = AnalysisResults::default();
826 results.unused_exports.push(UnusedExport {
827 path: root.join("src/utils.ts"),
828 export_name: "foo`bar".to_string(),
829 is_type_only: false,
830 line: 1,
831 col: 0,
832 span_start: 0,
833 is_re_export: false,
834 });
835 let md = build_markdown(&results, &root);
836 assert!(md.contains("foo\\`bar"));
837 assert!(!md.contains("foo`bar`"));
838 }
839
840 #[test]
841 fn markdown_escapes_backticks_in_package_names() {
842 let root = PathBuf::from("/project");
843 let mut results = AnalysisResults::default();
844 results.unused_dependencies.push(UnusedDependency {
845 package_name: "pkg`name".to_string(),
846 location: DependencyLocation::Dependencies,
847 path: root.join("package.json"),
848 line: 5,
849 });
850 let md = build_markdown(&results, &root);
851 assert!(md.contains("pkg\\`name"));
852 }
853
854 #[test]
857 fn duplication_markdown_empty() {
858 let report = DuplicationReport::default();
859 let root = PathBuf::from("/project");
860 let md = build_duplication_markdown(&report, &root);
861 assert_eq!(md, "## Fallow: no code duplication found\n");
862 }
863
864 #[test]
865 fn duplication_markdown_contains_groups() {
866 let root = PathBuf::from("/project");
867 let report = DuplicationReport {
868 clone_groups: vec![CloneGroup {
869 instances: vec![
870 CloneInstance {
871 file: root.join("src/a.ts"),
872 start_line: 1,
873 end_line: 10,
874 start_col: 0,
875 end_col: 0,
876 fragment: String::new(),
877 },
878 CloneInstance {
879 file: root.join("src/b.ts"),
880 start_line: 5,
881 end_line: 14,
882 start_col: 0,
883 end_col: 0,
884 fragment: String::new(),
885 },
886 ],
887 token_count: 50,
888 line_count: 10,
889 }],
890 clone_families: vec![],
891 stats: DuplicationStats {
892 total_files: 10,
893 files_with_clones: 2,
894 total_lines: 500,
895 duplicated_lines: 20,
896 total_tokens: 2500,
897 duplicated_tokens: 100,
898 clone_groups: 1,
899 clone_instances: 2,
900 duplication_percentage: 4.0,
901 },
902 };
903 let md = build_duplication_markdown(&report, &root);
904 assert!(md.contains("**Clone group 1**"));
905 assert!(md.contains("`src/a.ts:1-10`"));
906 assert!(md.contains("`src/b.ts:5-14`"));
907 assert!(md.contains("4.0% duplication"));
908 }
909
910 #[test]
911 fn duplication_markdown_contains_families() {
912 let root = PathBuf::from("/project");
913 let report = DuplicationReport {
914 clone_groups: vec![CloneGroup {
915 instances: vec![CloneInstance {
916 file: root.join("src/a.ts"),
917 start_line: 1,
918 end_line: 5,
919 start_col: 0,
920 end_col: 0,
921 fragment: String::new(),
922 }],
923 token_count: 30,
924 line_count: 5,
925 }],
926 clone_families: vec![CloneFamily {
927 files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
928 groups: vec![],
929 total_duplicated_lines: 20,
930 total_duplicated_tokens: 100,
931 suggestions: vec![RefactoringSuggestion {
932 kind: RefactoringKind::ExtractFunction,
933 description: "Extract shared utility function".to_string(),
934 estimated_savings: 15,
935 }],
936 }],
937 stats: DuplicationStats {
938 clone_groups: 1,
939 clone_instances: 1,
940 duplication_percentage: 2.0,
941 ..Default::default()
942 },
943 };
944 let md = build_duplication_markdown(&report, &root);
945 assert!(md.contains("### Clone Families"));
946 assert!(md.contains("**Family 1**"));
947 assert!(md.contains("Extract shared utility function"));
948 assert!(md.contains("~15 lines saved"));
949 }
950
951 #[test]
954 fn health_markdown_empty_no_findings() {
955 let root = PathBuf::from("/project");
956 let report = crate::health_types::HealthReport {
957 findings: vec![],
958 summary: crate::health_types::HealthSummary {
959 files_analyzed: 10,
960 functions_analyzed: 50,
961 functions_above_threshold: 0,
962 max_cyclomatic_threshold: 20,
963 max_cognitive_threshold: 15,
964 files_scored: None,
965 average_maintainability: None,
966 },
967 file_scores: vec![],
968 hotspots: vec![],
969 hotspot_summary: None,
970 targets: vec![],
971 };
972 let md = build_health_markdown(&report, &root);
973 assert!(md.contains("no functions exceed complexity thresholds"));
974 assert!(md.contains("**50** functions analyzed"));
975 }
976
977 #[test]
978 fn health_markdown_table_format() {
979 let root = PathBuf::from("/project");
980 let report = crate::health_types::HealthReport {
981 findings: vec![crate::health_types::HealthFinding {
982 path: root.join("src/utils.ts"),
983 name: "parseExpression".to_string(),
984 line: 42,
985 col: 0,
986 cyclomatic: 25,
987 cognitive: 30,
988 line_count: 80,
989 exceeded: crate::health_types::ExceededThreshold::Both,
990 }],
991 summary: crate::health_types::HealthSummary {
992 files_analyzed: 10,
993 functions_analyzed: 50,
994 functions_above_threshold: 1,
995 max_cyclomatic_threshold: 20,
996 max_cognitive_threshold: 15,
997 files_scored: None,
998 average_maintainability: None,
999 },
1000 file_scores: vec![],
1001 hotspots: vec![],
1002 hotspot_summary: None,
1003 targets: vec![],
1004 };
1005 let md = build_health_markdown(&report, &root);
1006 assert!(md.contains("## Fallow: 1 high complexity function\n"));
1007 assert!(md.contains("| File | Function |"));
1008 assert!(md.contains("`src/utils.ts:42`"));
1009 assert!(md.contains("`parseExpression`"));
1010 assert!(md.contains("25 **!**"));
1011 assert!(md.contains("30 **!**"));
1012 assert!(md.contains("| 80 |"));
1013 }
1014
1015 #[test]
1016 fn health_markdown_no_marker_when_below_threshold() {
1017 let root = PathBuf::from("/project");
1018 let report = crate::health_types::HealthReport {
1019 findings: vec![crate::health_types::HealthFinding {
1020 path: root.join("src/utils.ts"),
1021 name: "helper".to_string(),
1022 line: 10,
1023 col: 0,
1024 cyclomatic: 15,
1025 cognitive: 20,
1026 line_count: 30,
1027 exceeded: crate::health_types::ExceededThreshold::Cognitive,
1028 }],
1029 summary: crate::health_types::HealthSummary {
1030 files_analyzed: 5,
1031 functions_analyzed: 20,
1032 functions_above_threshold: 1,
1033 max_cyclomatic_threshold: 20,
1034 max_cognitive_threshold: 15,
1035 files_scored: None,
1036 average_maintainability: None,
1037 },
1038 file_scores: vec![],
1039 hotspots: vec![],
1040 hotspot_summary: None,
1041 targets: vec![],
1042 };
1043 let md = build_health_markdown(&report, &root);
1044 assert!(md.contains("| 15 |"));
1046 assert!(md.contains("20 **!**"));
1048 }
1049
1050 #[test]
1051 fn health_markdown_with_targets() {
1052 use crate::health_types::*;
1053
1054 let root = PathBuf::from("/project");
1055 let report = HealthReport {
1056 findings: vec![],
1057 summary: HealthSummary {
1058 files_analyzed: 10,
1059 functions_analyzed: 50,
1060 functions_above_threshold: 0,
1061 max_cyclomatic_threshold: 20,
1062 max_cognitive_threshold: 15,
1063 files_scored: None,
1064 average_maintainability: None,
1065 },
1066 file_scores: vec![],
1067 hotspots: vec![],
1068 hotspot_summary: None,
1069 targets: vec![
1070 RefactoringTarget {
1071 path: PathBuf::from("/project/src/complex.ts"),
1072 priority: 82.5,
1073 recommendation: "Split high-impact file".into(),
1074 category: RecommendationCategory::SplitHighImpact,
1075 effort: crate::health_types::EffortEstimate::High,
1076 factors: vec![ContributingFactor {
1077 metric: "fan_in",
1078 value: 25.0,
1079 threshold: 10.0,
1080 detail: "25 files depend on this".into(),
1081 }],
1082 evidence: None,
1083 },
1084 RefactoringTarget {
1085 path: PathBuf::from("/project/src/legacy.ts"),
1086 priority: 45.0,
1087 recommendation: "Remove 5 unused exports".into(),
1088 category: RecommendationCategory::RemoveDeadCode,
1089 effort: crate::health_types::EffortEstimate::Low,
1090 factors: vec![],
1091 evidence: None,
1092 },
1093 ],
1094 };
1095 let md = build_health_markdown(&report, &root);
1096
1097 assert!(
1099 md.contains("Refactoring Targets"),
1100 "should contain targets heading"
1101 );
1102 assert!(
1103 md.contains("src/complex.ts"),
1104 "should contain target file path"
1105 );
1106 assert!(md.contains("82.5"), "should contain priority score");
1107 assert!(
1108 md.contains("Split high-impact file"),
1109 "should contain recommendation"
1110 );
1111 assert!(md.contains("src/legacy.ts"), "should contain second target");
1112 }
1113}