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 });
600 r.unlisted_dependencies.push(UnlistedDependency {
601 package_name: "chalk".to_string(),
602 imported_from: vec![ImportSite {
603 path: root.join("src/cli.ts"),
604 line: 2,
605 col: 0,
606 }],
607 });
608 r.duplicate_exports.push(DuplicateExport {
609 export_name: "Config".to_string(),
610 locations: vec![
611 DuplicateLocation {
612 path: root.join("src/config.ts"),
613 line: 15,
614 col: 0,
615 },
616 DuplicateLocation {
617 path: root.join("src/types.ts"),
618 line: 30,
619 col: 0,
620 },
621 ],
622 });
623 r.type_only_dependencies.push(TypeOnlyDependency {
624 package_name: "zod".to_string(),
625 path: root.join("package.json"),
626 line: 8,
627 });
628 r.circular_dependencies.push(CircularDependency {
629 files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
630 length: 2,
631 line: 3,
632 col: 0,
633 });
634
635 r
636 }
637
638 #[test]
639 fn markdown_empty_results_no_issues() {
640 let root = PathBuf::from("/project");
641 let results = AnalysisResults::default();
642 let md = build_markdown(&results, &root);
643 assert_eq!(md, "## Fallow: no issues found\n");
644 }
645
646 #[test]
647 fn markdown_contains_header_with_count() {
648 let root = PathBuf::from("/project");
649 let results = sample_results(&root);
650 let md = build_markdown(&results, &root);
651 assert!(md.starts_with(&format!(
652 "## Fallow: {} issues found\n",
653 results.total_issues()
654 )));
655 }
656
657 #[test]
658 fn markdown_contains_all_sections() {
659 let root = PathBuf::from("/project");
660 let results = sample_results(&root);
661 let md = build_markdown(&results, &root);
662
663 assert!(md.contains("### Unused files (1)"));
664 assert!(md.contains("### Unused exports (1)"));
665 assert!(md.contains("### Unused type exports (1)"));
666 assert!(md.contains("### Unused dependencies (1)"));
667 assert!(md.contains("### Unused devDependencies (1)"));
668 assert!(md.contains("### Unused enum members (1)"));
669 assert!(md.contains("### Unused class members (1)"));
670 assert!(md.contains("### Unresolved imports (1)"));
671 assert!(md.contains("### Unlisted dependencies (1)"));
672 assert!(md.contains("### Duplicate exports (1)"));
673 assert!(md.contains("### Type-only dependencies"));
674 assert!(md.contains("### Circular dependencies (1)"));
675 }
676
677 #[test]
678 fn markdown_unused_file_format() {
679 let root = PathBuf::from("/project");
680 let mut results = AnalysisResults::default();
681 results.unused_files.push(UnusedFile {
682 path: root.join("src/dead.ts"),
683 });
684 let md = build_markdown(&results, &root);
685 assert!(md.contains("- `src/dead.ts`"));
686 }
687
688 #[test]
689 fn markdown_unused_export_grouped_by_file() {
690 let root = PathBuf::from("/project");
691 let mut results = AnalysisResults::default();
692 results.unused_exports.push(UnusedExport {
693 path: root.join("src/utils.ts"),
694 export_name: "helperFn".to_string(),
695 is_type_only: false,
696 line: 10,
697 col: 4,
698 span_start: 120,
699 is_re_export: false,
700 });
701 let md = build_markdown(&results, &root);
702 assert!(md.contains("- `src/utils.ts`"));
703 assert!(md.contains(":10 `helperFn`"));
704 }
705
706 #[test]
707 fn markdown_re_export_tagged() {
708 let root = PathBuf::from("/project");
709 let mut results = AnalysisResults::default();
710 results.unused_exports.push(UnusedExport {
711 path: root.join("src/index.ts"),
712 export_name: "reExported".to_string(),
713 is_type_only: false,
714 line: 1,
715 col: 0,
716 span_start: 0,
717 is_re_export: true,
718 });
719 let md = build_markdown(&results, &root);
720 assert!(md.contains("(re-export)"));
721 }
722
723 #[test]
724 fn markdown_unused_dep_format() {
725 let root = PathBuf::from("/project");
726 let mut results = AnalysisResults::default();
727 results.unused_dependencies.push(UnusedDependency {
728 package_name: "lodash".to_string(),
729 location: DependencyLocation::Dependencies,
730 path: root.join("package.json"),
731 line: 5,
732 });
733 let md = build_markdown(&results, &root);
734 assert!(md.contains("- `lodash`"));
735 }
736
737 #[test]
738 fn markdown_circular_dep_format() {
739 let root = PathBuf::from("/project");
740 let mut results = AnalysisResults::default();
741 results.circular_dependencies.push(CircularDependency {
742 files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
743 length: 2,
744 line: 3,
745 col: 0,
746 });
747 let md = build_markdown(&results, &root);
748 assert!(md.contains("`src/a.ts`"));
749 assert!(md.contains("`src/b.ts`"));
750 assert!(md.contains("\u{2192}"));
751 }
752
753 #[test]
754 fn markdown_strips_root_prefix() {
755 let root = PathBuf::from("/project");
756 let mut results = AnalysisResults::default();
757 results.unused_files.push(UnusedFile {
758 path: PathBuf::from("/project/src/deep/nested/file.ts"),
759 });
760 let md = build_markdown(&results, &root);
761 assert!(md.contains("`src/deep/nested/file.ts`"));
762 assert!(!md.contains("/project/"));
763 }
764
765 #[test]
766 fn markdown_single_issue_no_plural() {
767 let root = PathBuf::from("/project");
768 let mut results = AnalysisResults::default();
769 results.unused_files.push(UnusedFile {
770 path: root.join("src/dead.ts"),
771 });
772 let md = build_markdown(&results, &root);
773 assert!(md.starts_with("## Fallow: 1 issue found\n"));
774 }
775
776 #[test]
777 fn markdown_type_only_dep_format() {
778 let root = PathBuf::from("/project");
779 let mut results = AnalysisResults::default();
780 results.type_only_dependencies.push(TypeOnlyDependency {
781 package_name: "zod".to_string(),
782 path: root.join("package.json"),
783 line: 8,
784 });
785 let md = build_markdown(&results, &root);
786 assert!(md.contains("### Type-only dependencies"));
787 assert!(md.contains("- `zod`"));
788 }
789
790 #[test]
791 fn markdown_escapes_backticks_in_export_names() {
792 let root = PathBuf::from("/project");
793 let mut results = AnalysisResults::default();
794 results.unused_exports.push(UnusedExport {
795 path: root.join("src/utils.ts"),
796 export_name: "foo`bar".to_string(),
797 is_type_only: false,
798 line: 1,
799 col: 0,
800 span_start: 0,
801 is_re_export: false,
802 });
803 let md = build_markdown(&results, &root);
804 assert!(md.contains("foo\\`bar"));
805 assert!(!md.contains("foo`bar`"));
806 }
807
808 #[test]
809 fn markdown_escapes_backticks_in_package_names() {
810 let root = PathBuf::from("/project");
811 let mut results = AnalysisResults::default();
812 results.unused_dependencies.push(UnusedDependency {
813 package_name: "pkg`name".to_string(),
814 location: DependencyLocation::Dependencies,
815 path: root.join("package.json"),
816 line: 5,
817 });
818 let md = build_markdown(&results, &root);
819 assert!(md.contains("pkg\\`name"));
820 }
821
822 #[test]
825 fn duplication_markdown_empty() {
826 let report = DuplicationReport::default();
827 let root = PathBuf::from("/project");
828 let md = build_duplication_markdown(&report, &root);
829 assert_eq!(md, "## Fallow: no code duplication found\n");
830 }
831
832 #[test]
833 fn duplication_markdown_contains_groups() {
834 let root = PathBuf::from("/project");
835 let report = DuplicationReport {
836 clone_groups: vec![CloneGroup {
837 instances: vec![
838 CloneInstance {
839 file: root.join("src/a.ts"),
840 start_line: 1,
841 end_line: 10,
842 start_col: 0,
843 end_col: 0,
844 fragment: String::new(),
845 },
846 CloneInstance {
847 file: root.join("src/b.ts"),
848 start_line: 5,
849 end_line: 14,
850 start_col: 0,
851 end_col: 0,
852 fragment: String::new(),
853 },
854 ],
855 token_count: 50,
856 line_count: 10,
857 }],
858 clone_families: vec![],
859 stats: DuplicationStats {
860 total_files: 10,
861 files_with_clones: 2,
862 total_lines: 500,
863 duplicated_lines: 20,
864 total_tokens: 2500,
865 duplicated_tokens: 100,
866 clone_groups: 1,
867 clone_instances: 2,
868 duplication_percentage: 4.0,
869 },
870 };
871 let md = build_duplication_markdown(&report, &root);
872 assert!(md.contains("**Clone group 1**"));
873 assert!(md.contains("`src/a.ts:1-10`"));
874 assert!(md.contains("`src/b.ts:5-14`"));
875 assert!(md.contains("4.0% duplication"));
876 }
877
878 #[test]
879 fn duplication_markdown_contains_families() {
880 let root = PathBuf::from("/project");
881 let report = DuplicationReport {
882 clone_groups: vec![CloneGroup {
883 instances: vec![CloneInstance {
884 file: root.join("src/a.ts"),
885 start_line: 1,
886 end_line: 5,
887 start_col: 0,
888 end_col: 0,
889 fragment: String::new(),
890 }],
891 token_count: 30,
892 line_count: 5,
893 }],
894 clone_families: vec![CloneFamily {
895 files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
896 groups: vec![],
897 total_duplicated_lines: 20,
898 total_duplicated_tokens: 100,
899 suggestions: vec![RefactoringSuggestion {
900 kind: RefactoringKind::ExtractFunction,
901 description: "Extract shared utility function".to_string(),
902 estimated_savings: 15,
903 }],
904 }],
905 stats: DuplicationStats {
906 clone_groups: 1,
907 clone_instances: 1,
908 duplication_percentage: 2.0,
909 ..Default::default()
910 },
911 };
912 let md = build_duplication_markdown(&report, &root);
913 assert!(md.contains("### Clone Families"));
914 assert!(md.contains("**Family 1**"));
915 assert!(md.contains("Extract shared utility function"));
916 assert!(md.contains("~15 lines saved"));
917 }
918
919 #[test]
922 fn health_markdown_empty_no_findings() {
923 let root = PathBuf::from("/project");
924 let report = crate::health_types::HealthReport {
925 findings: vec![],
926 summary: crate::health_types::HealthSummary {
927 files_analyzed: 10,
928 functions_analyzed: 50,
929 functions_above_threshold: 0,
930 max_cyclomatic_threshold: 20,
931 max_cognitive_threshold: 15,
932 files_scored: None,
933 average_maintainability: None,
934 },
935 file_scores: vec![],
936 hotspots: vec![],
937 hotspot_summary: None,
938 };
939 let md = build_health_markdown(&report, &root);
940 assert!(md.contains("no functions exceed complexity thresholds"));
941 assert!(md.contains("**50** functions analyzed"));
942 }
943
944 #[test]
945 fn health_markdown_table_format() {
946 let root = PathBuf::from("/project");
947 let report = crate::health_types::HealthReport {
948 findings: vec![crate::health_types::HealthFinding {
949 path: root.join("src/utils.ts"),
950 name: "parseExpression".to_string(),
951 line: 42,
952 col: 0,
953 cyclomatic: 25,
954 cognitive: 30,
955 line_count: 80,
956 exceeded: crate::health_types::ExceededThreshold::Both,
957 }],
958 summary: crate::health_types::HealthSummary {
959 files_analyzed: 10,
960 functions_analyzed: 50,
961 functions_above_threshold: 1,
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 };
971 let md = build_health_markdown(&report, &root);
972 assert!(md.contains("## Fallow: 1 high complexity function\n"));
973 assert!(md.contains("| File | Function |"));
974 assert!(md.contains("`src/utils.ts:42`"));
975 assert!(md.contains("`parseExpression`"));
976 assert!(md.contains("25 **!**"));
977 assert!(md.contains("30 **!**"));
978 assert!(md.contains("| 80 |"));
979 }
980
981 #[test]
982 fn health_markdown_no_marker_when_below_threshold() {
983 let root = PathBuf::from("/project");
984 let report = crate::health_types::HealthReport {
985 findings: vec![crate::health_types::HealthFinding {
986 path: root.join("src/utils.ts"),
987 name: "helper".to_string(),
988 line: 10,
989 col: 0,
990 cyclomatic: 15,
991 cognitive: 20,
992 line_count: 30,
993 exceeded: crate::health_types::ExceededThreshold::Cognitive,
994 }],
995 summary: crate::health_types::HealthSummary {
996 files_analyzed: 5,
997 functions_analyzed: 20,
998 functions_above_threshold: 1,
999 max_cyclomatic_threshold: 20,
1000 max_cognitive_threshold: 15,
1001 files_scored: None,
1002 average_maintainability: None,
1003 },
1004 file_scores: vec![],
1005 hotspots: vec![],
1006 hotspot_summary: None,
1007 };
1008 let md = build_health_markdown(&report, &root);
1009 assert!(md.contains("| 15 |"));
1011 assert!(md.contains("20 **!**"));
1013 }
1014}