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() && report.file_scores.is_empty() && report.hotspots.is_empty() {
366 let _ = write!(
367 out,
368 "## Fallow: no functions exceed complexity thresholds\n\n\
369 **{}** functions analyzed (max cyclomatic: {}, max cognitive: {})\n",
370 report.summary.functions_analyzed,
371 report.summary.max_cyclomatic_threshold,
372 report.summary.max_cognitive_threshold,
373 );
374 return out;
375 }
376
377 if !report.findings.is_empty() {
378 let count = report.summary.functions_above_threshold;
379 let shown = report.findings.len();
380 if shown < count {
381 let _ = write!(
382 out,
383 "## Fallow: {count} high complexity function{} ({shown} shown)\n\n",
384 if count == 1 { "" } else { "s" },
385 );
386 } else {
387 let _ = write!(
388 out,
389 "## Fallow: {count} high complexity function{}\n\n",
390 if count == 1 { "" } else { "s" },
391 );
392 }
393
394 out.push_str("| File | Function | Cyclomatic | Cognitive | Lines |\n");
395 out.push_str("|:-----|:---------|:-----------|:----------|:------|\n");
396
397 for finding in &report.findings {
398 let file_str = rel(&finding.path);
399 let cyc_marker = if finding.cyclomatic > report.summary.max_cyclomatic_threshold {
400 " **!**"
401 } else {
402 ""
403 };
404 let cog_marker = if finding.cognitive > report.summary.max_cognitive_threshold {
405 " **!**"
406 } else {
407 ""
408 };
409 let _ = writeln!(
410 out,
411 "| `{file_str}:{line}` | `{name}` | {cyc}{cyc_marker} | {cog}{cog_marker} | {lines} |",
412 line = finding.line,
413 name = escape_backticks(&finding.name),
414 cyc = finding.cyclomatic,
415 cog = finding.cognitive,
416 lines = finding.line_count,
417 );
418 }
419
420 let s = &report.summary;
421 let _ = write!(
422 out,
423 "\n**{files}** files, **{funcs}** functions analyzed \
424 (thresholds: cyclomatic > {cyc}, cognitive > {cog})\n",
425 files = s.files_analyzed,
426 funcs = s.functions_analyzed,
427 cyc = s.max_cyclomatic_threshold,
428 cog = s.max_cognitive_threshold,
429 );
430 }
431
432 if !report.file_scores.is_empty() {
434 out.push('\n');
435 let _ = writeln!(
436 out,
437 "### File Health Scores ({} files)\n",
438 report.file_scores.len(),
439 );
440 out.push_str("| File | MI | Fan-in | Fan-out | Dead Code | Density |\n");
441 out.push_str("|:-----|:---|:-------|:--------|:----------|:--------|\n");
442
443 for score in &report.file_scores {
444 let file_str = rel(&score.path);
445 let _ = writeln!(
446 out,
447 "| `{file_str}` | {mi:.1} | {fi} | {fan_out} | {dead:.0}% | {density:.2} |",
448 mi = score.maintainability_index,
449 fi = score.fan_in,
450 fan_out = score.fan_out,
451 dead = score.dead_code_ratio * 100.0,
452 density = score.complexity_density,
453 );
454 }
455
456 if let Some(avg) = report.summary.average_maintainability {
457 let _ = write!(out, "\n**Average maintainability index:** {avg:.1}/100\n");
458 }
459 }
460
461 if !report.hotspots.is_empty() {
463 out.push('\n');
464 let header = if let Some(ref summary) = report.hotspot_summary {
465 format!(
466 "### Hotspots ({} files, since {})\n",
467 report.hotspots.len(),
468 summary.since,
469 )
470 } else {
471 format!("### Hotspots ({} files)\n", report.hotspots.len())
472 };
473 let _ = writeln!(out, "{header}");
474 out.push_str("| File | Score | Commits | Churn | Density | Fan-in | Trend |\n");
475 out.push_str("|:-----|:------|:--------|:------|:--------|:-------|:------|\n");
476
477 for entry in &report.hotspots {
478 let file_str = rel(&entry.path);
479 let _ = writeln!(
480 out,
481 "| `{file_str}` | {score:.1} | {commits} | {churn} | {density:.2} | {fi} | {trend} |",
482 score = entry.score,
483 commits = entry.commits,
484 churn = entry.lines_added + entry.lines_deleted,
485 density = entry.complexity_density,
486 fi = entry.fan_in,
487 trend = entry.trend,
488 );
489 }
490
491 if let Some(ref summary) = report.hotspot_summary
492 && summary.files_excluded > 0
493 {
494 let _ = write!(
495 out,
496 "\n*{} file{} excluded (< {} commits)*\n",
497 summary.files_excluded,
498 if summary.files_excluded == 1 { "" } else { "s" },
499 summary.min_commits,
500 );
501 }
502 }
503
504 let has_scores = !report.file_scores.is_empty();
506 let has_hotspots = !report.hotspots.is_empty();
507 if has_scores || has_hotspots {
508 out.push_str("\n---\n\n<details><summary>Metric definitions</summary>\n\n");
509 if has_scores {
510 out.push_str("- **MI** — Maintainability Index (0\u{2013}100, higher is better)\n");
511 out.push_str("- **Fan-in** — files that import this file (blast radius)\n");
512 out.push_str("- **Fan-out** — files this file imports (coupling)\n");
513 out.push_str("- **Dead Code** — % of value exports with zero references\n");
514 out.push_str("- **Density** — cyclomatic complexity / lines of code\n");
515 }
516 if has_hotspots {
517 out.push_str(
518 "- **Score** — churn \u{00d7} complexity (0\u{2013}100, higher = riskier)\n",
519 );
520 out.push_str("- **Commits** — commits in the analysis window\n");
521 out.push_str("- **Churn** — total lines added + deleted\n");
522 out.push_str("- **Trend** — accelerating / stable / cooling\n");
523 }
524 out.push_str("\n[Full metric reference](https://docs.fallow.tools/explanations/metrics)\n\n</details>\n");
525 }
526
527 out
528}
529
530#[cfg(test)]
531mod tests {
532 use super::*;
533 use fallow_core::duplicates::{
534 CloneFamily, CloneGroup, CloneInstance, DuplicationReport, DuplicationStats,
535 RefactoringKind, RefactoringSuggestion,
536 };
537 use fallow_core::extract::MemberKind;
538 use fallow_core::results::*;
539 use std::path::PathBuf;
540
541 fn sample_results(root: &Path) -> AnalysisResults {
543 let mut r = AnalysisResults::default();
544
545 r.unused_files.push(UnusedFile {
546 path: root.join("src/dead.ts"),
547 });
548 r.unused_exports.push(UnusedExport {
549 path: root.join("src/utils.ts"),
550 export_name: "helperFn".to_string(),
551 is_type_only: false,
552 line: 10,
553 col: 4,
554 span_start: 120,
555 is_re_export: false,
556 });
557 r.unused_types.push(UnusedExport {
558 path: root.join("src/types.ts"),
559 export_name: "OldType".to_string(),
560 is_type_only: true,
561 line: 5,
562 col: 0,
563 span_start: 60,
564 is_re_export: false,
565 });
566 r.unused_dependencies.push(UnusedDependency {
567 package_name: "lodash".to_string(),
568 location: DependencyLocation::Dependencies,
569 path: root.join("package.json"),
570 line: 5,
571 });
572 r.unused_dev_dependencies.push(UnusedDependency {
573 package_name: "jest".to_string(),
574 location: DependencyLocation::DevDependencies,
575 path: root.join("package.json"),
576 line: 5,
577 });
578 r.unused_enum_members.push(UnusedMember {
579 path: root.join("src/enums.ts"),
580 parent_name: "Status".to_string(),
581 member_name: "Deprecated".to_string(),
582 kind: MemberKind::EnumMember,
583 line: 8,
584 col: 2,
585 });
586 r.unused_class_members.push(UnusedMember {
587 path: root.join("src/service.ts"),
588 parent_name: "UserService".to_string(),
589 member_name: "legacyMethod".to_string(),
590 kind: MemberKind::ClassMethod,
591 line: 42,
592 col: 4,
593 });
594 r.unresolved_imports.push(UnresolvedImport {
595 path: root.join("src/app.ts"),
596 specifier: "./missing-module".to_string(),
597 line: 3,
598 col: 0,
599 specifier_col: 0,
600 });
601 r.unlisted_dependencies.push(UnlistedDependency {
602 package_name: "chalk".to_string(),
603 imported_from: vec![ImportSite {
604 path: root.join("src/cli.ts"),
605 line: 2,
606 col: 0,
607 }],
608 });
609 r.duplicate_exports.push(DuplicateExport {
610 export_name: "Config".to_string(),
611 locations: vec![
612 DuplicateLocation {
613 path: root.join("src/config.ts"),
614 line: 15,
615 col: 0,
616 },
617 DuplicateLocation {
618 path: root.join("src/types.ts"),
619 line: 30,
620 col: 0,
621 },
622 ],
623 });
624 r.type_only_dependencies.push(TypeOnlyDependency {
625 package_name: "zod".to_string(),
626 path: root.join("package.json"),
627 line: 8,
628 });
629 r.circular_dependencies.push(CircularDependency {
630 files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
631 length: 2,
632 line: 3,
633 col: 0,
634 });
635
636 r
637 }
638
639 #[test]
640 fn markdown_empty_results_no_issues() {
641 let root = PathBuf::from("/project");
642 let results = AnalysisResults::default();
643 let md = build_markdown(&results, &root);
644 assert_eq!(md, "## Fallow: no issues found\n");
645 }
646
647 #[test]
648 fn markdown_contains_header_with_count() {
649 let root = PathBuf::from("/project");
650 let results = sample_results(&root);
651 let md = build_markdown(&results, &root);
652 assert!(md.starts_with(&format!(
653 "## Fallow: {} issues found\n",
654 results.total_issues()
655 )));
656 }
657
658 #[test]
659 fn markdown_contains_all_sections() {
660 let root = PathBuf::from("/project");
661 let results = sample_results(&root);
662 let md = build_markdown(&results, &root);
663
664 assert!(md.contains("### Unused files (1)"));
665 assert!(md.contains("### Unused exports (1)"));
666 assert!(md.contains("### Unused type exports (1)"));
667 assert!(md.contains("### Unused dependencies (1)"));
668 assert!(md.contains("### Unused devDependencies (1)"));
669 assert!(md.contains("### Unused enum members (1)"));
670 assert!(md.contains("### Unused class members (1)"));
671 assert!(md.contains("### Unresolved imports (1)"));
672 assert!(md.contains("### Unlisted dependencies (1)"));
673 assert!(md.contains("### Duplicate exports (1)"));
674 assert!(md.contains("### Type-only dependencies"));
675 assert!(md.contains("### Circular dependencies (1)"));
676 }
677
678 #[test]
679 fn markdown_unused_file_format() {
680 let root = PathBuf::from("/project");
681 let mut results = AnalysisResults::default();
682 results.unused_files.push(UnusedFile {
683 path: root.join("src/dead.ts"),
684 });
685 let md = build_markdown(&results, &root);
686 assert!(md.contains("- `src/dead.ts`"));
687 }
688
689 #[test]
690 fn markdown_unused_export_grouped_by_file() {
691 let root = PathBuf::from("/project");
692 let mut results = AnalysisResults::default();
693 results.unused_exports.push(UnusedExport {
694 path: root.join("src/utils.ts"),
695 export_name: "helperFn".to_string(),
696 is_type_only: false,
697 line: 10,
698 col: 4,
699 span_start: 120,
700 is_re_export: false,
701 });
702 let md = build_markdown(&results, &root);
703 assert!(md.contains("- `src/utils.ts`"));
704 assert!(md.contains(":10 `helperFn`"));
705 }
706
707 #[test]
708 fn markdown_re_export_tagged() {
709 let root = PathBuf::from("/project");
710 let mut results = AnalysisResults::default();
711 results.unused_exports.push(UnusedExport {
712 path: root.join("src/index.ts"),
713 export_name: "reExported".to_string(),
714 is_type_only: false,
715 line: 1,
716 col: 0,
717 span_start: 0,
718 is_re_export: true,
719 });
720 let md = build_markdown(&results, &root);
721 assert!(md.contains("(re-export)"));
722 }
723
724 #[test]
725 fn markdown_unused_dep_format() {
726 let root = PathBuf::from("/project");
727 let mut results = AnalysisResults::default();
728 results.unused_dependencies.push(UnusedDependency {
729 package_name: "lodash".to_string(),
730 location: DependencyLocation::Dependencies,
731 path: root.join("package.json"),
732 line: 5,
733 });
734 let md = build_markdown(&results, &root);
735 assert!(md.contains("- `lodash`"));
736 }
737
738 #[test]
739 fn markdown_circular_dep_format() {
740 let root = PathBuf::from("/project");
741 let mut results = AnalysisResults::default();
742 results.circular_dependencies.push(CircularDependency {
743 files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
744 length: 2,
745 line: 3,
746 col: 0,
747 });
748 let md = build_markdown(&results, &root);
749 assert!(md.contains("`src/a.ts`"));
750 assert!(md.contains("`src/b.ts`"));
751 assert!(md.contains("\u{2192}"));
752 }
753
754 #[test]
755 fn markdown_strips_root_prefix() {
756 let root = PathBuf::from("/project");
757 let mut results = AnalysisResults::default();
758 results.unused_files.push(UnusedFile {
759 path: PathBuf::from("/project/src/deep/nested/file.ts"),
760 });
761 let md = build_markdown(&results, &root);
762 assert!(md.contains("`src/deep/nested/file.ts`"));
763 assert!(!md.contains("/project/"));
764 }
765
766 #[test]
767 fn markdown_single_issue_no_plural() {
768 let root = PathBuf::from("/project");
769 let mut results = AnalysisResults::default();
770 results.unused_files.push(UnusedFile {
771 path: root.join("src/dead.ts"),
772 });
773 let md = build_markdown(&results, &root);
774 assert!(md.starts_with("## Fallow: 1 issue found\n"));
775 }
776
777 #[test]
778 fn markdown_type_only_dep_format() {
779 let root = PathBuf::from("/project");
780 let mut results = AnalysisResults::default();
781 results.type_only_dependencies.push(TypeOnlyDependency {
782 package_name: "zod".to_string(),
783 path: root.join("package.json"),
784 line: 8,
785 });
786 let md = build_markdown(&results, &root);
787 assert!(md.contains("### Type-only dependencies"));
788 assert!(md.contains("- `zod`"));
789 }
790
791 #[test]
792 fn markdown_escapes_backticks_in_export_names() {
793 let root = PathBuf::from("/project");
794 let mut results = AnalysisResults::default();
795 results.unused_exports.push(UnusedExport {
796 path: root.join("src/utils.ts"),
797 export_name: "foo`bar".to_string(),
798 is_type_only: false,
799 line: 1,
800 col: 0,
801 span_start: 0,
802 is_re_export: false,
803 });
804 let md = build_markdown(&results, &root);
805 assert!(md.contains("foo\\`bar"));
806 assert!(!md.contains("foo`bar`"));
807 }
808
809 #[test]
810 fn markdown_escapes_backticks_in_package_names() {
811 let root = PathBuf::from("/project");
812 let mut results = AnalysisResults::default();
813 results.unused_dependencies.push(UnusedDependency {
814 package_name: "pkg`name".to_string(),
815 location: DependencyLocation::Dependencies,
816 path: root.join("package.json"),
817 line: 5,
818 });
819 let md = build_markdown(&results, &root);
820 assert!(md.contains("pkg\\`name"));
821 }
822
823 #[test]
826 fn duplication_markdown_empty() {
827 let report = DuplicationReport::default();
828 let root = PathBuf::from("/project");
829 let md = build_duplication_markdown(&report, &root);
830 assert_eq!(md, "## Fallow: no code duplication found\n");
831 }
832
833 #[test]
834 fn duplication_markdown_contains_groups() {
835 let root = PathBuf::from("/project");
836 let report = DuplicationReport {
837 clone_groups: vec![CloneGroup {
838 instances: vec![
839 CloneInstance {
840 file: root.join("src/a.ts"),
841 start_line: 1,
842 end_line: 10,
843 start_col: 0,
844 end_col: 0,
845 fragment: String::new(),
846 },
847 CloneInstance {
848 file: root.join("src/b.ts"),
849 start_line: 5,
850 end_line: 14,
851 start_col: 0,
852 end_col: 0,
853 fragment: String::new(),
854 },
855 ],
856 token_count: 50,
857 line_count: 10,
858 }],
859 clone_families: vec![],
860 stats: DuplicationStats {
861 total_files: 10,
862 files_with_clones: 2,
863 total_lines: 500,
864 duplicated_lines: 20,
865 total_tokens: 2500,
866 duplicated_tokens: 100,
867 clone_groups: 1,
868 clone_instances: 2,
869 duplication_percentage: 4.0,
870 },
871 };
872 let md = build_duplication_markdown(&report, &root);
873 assert!(md.contains("**Clone group 1**"));
874 assert!(md.contains("`src/a.ts:1-10`"));
875 assert!(md.contains("`src/b.ts:5-14`"));
876 assert!(md.contains("4.0% duplication"));
877 }
878
879 #[test]
880 fn duplication_markdown_contains_families() {
881 let root = PathBuf::from("/project");
882 let report = DuplicationReport {
883 clone_groups: vec![CloneGroup {
884 instances: vec![CloneInstance {
885 file: root.join("src/a.ts"),
886 start_line: 1,
887 end_line: 5,
888 start_col: 0,
889 end_col: 0,
890 fragment: String::new(),
891 }],
892 token_count: 30,
893 line_count: 5,
894 }],
895 clone_families: vec![CloneFamily {
896 files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
897 groups: vec![],
898 total_duplicated_lines: 20,
899 total_duplicated_tokens: 100,
900 suggestions: vec![RefactoringSuggestion {
901 kind: RefactoringKind::ExtractFunction,
902 description: "Extract shared utility function".to_string(),
903 estimated_savings: 15,
904 }],
905 }],
906 stats: DuplicationStats {
907 clone_groups: 1,
908 clone_instances: 1,
909 duplication_percentage: 2.0,
910 ..Default::default()
911 },
912 };
913 let md = build_duplication_markdown(&report, &root);
914 assert!(md.contains("### Clone Families"));
915 assert!(md.contains("**Family 1**"));
916 assert!(md.contains("Extract shared utility function"));
917 assert!(md.contains("~15 lines saved"));
918 }
919
920 #[test]
923 fn health_markdown_empty_no_findings() {
924 let root = PathBuf::from("/project");
925 let report = crate::health_types::HealthReport {
926 findings: vec![],
927 summary: crate::health_types::HealthSummary {
928 files_analyzed: 10,
929 functions_analyzed: 50,
930 functions_above_threshold: 0,
931 max_cyclomatic_threshold: 20,
932 max_cognitive_threshold: 15,
933 files_scored: None,
934 average_maintainability: None,
935 },
936 file_scores: vec![],
937 hotspots: vec![],
938 hotspot_summary: None,
939 };
940 let md = build_health_markdown(&report, &root);
941 assert!(md.contains("no functions exceed complexity thresholds"));
942 assert!(md.contains("**50** functions analyzed"));
943 }
944
945 #[test]
946 fn health_markdown_table_format() {
947 let root = PathBuf::from("/project");
948 let report = crate::health_types::HealthReport {
949 findings: vec![crate::health_types::HealthFinding {
950 path: root.join("src/utils.ts"),
951 name: "parseExpression".to_string(),
952 line: 42,
953 col: 0,
954 cyclomatic: 25,
955 cognitive: 30,
956 line_count: 80,
957 exceeded: crate::health_types::ExceededThreshold::Both,
958 }],
959 summary: crate::health_types::HealthSummary {
960 files_analyzed: 10,
961 functions_analyzed: 50,
962 functions_above_threshold: 1,
963 max_cyclomatic_threshold: 20,
964 max_cognitive_threshold: 15,
965 files_scored: None,
966 average_maintainability: None,
967 },
968 file_scores: vec![],
969 hotspots: vec![],
970 hotspot_summary: None,
971 };
972 let md = build_health_markdown(&report, &root);
973 assert!(md.contains("## Fallow: 1 high complexity function\n"));
974 assert!(md.contains("| File | Function |"));
975 assert!(md.contains("`src/utils.ts:42`"));
976 assert!(md.contains("`parseExpression`"));
977 assert!(md.contains("25 **!**"));
978 assert!(md.contains("30 **!**"));
979 assert!(md.contains("| 80 |"));
980 }
981
982 #[test]
983 fn health_markdown_no_marker_when_below_threshold() {
984 let root = PathBuf::from("/project");
985 let report = crate::health_types::HealthReport {
986 findings: vec![crate::health_types::HealthFinding {
987 path: root.join("src/utils.ts"),
988 name: "helper".to_string(),
989 line: 10,
990 col: 0,
991 cyclomatic: 15,
992 cognitive: 20,
993 line_count: 30,
994 exceeded: crate::health_types::ExceededThreshold::Cognitive,
995 }],
996 summary: crate::health_types::HealthSummary {
997 files_analyzed: 5,
998 functions_analyzed: 20,
999 functions_above_threshold: 1,
1000 max_cyclomatic_threshold: 20,
1001 max_cognitive_threshold: 15,
1002 files_scored: None,
1003 average_maintainability: None,
1004 },
1005 file_scores: vec![],
1006 hotspots: vec![],
1007 hotspot_summary: None,
1008 };
1009 let md = build_health_markdown(&report, &root);
1010 assert!(md.contains("| 15 |"));
1012 assert!(md.contains("20 **!**"));
1014 }
1015}