Skip to main content

fallow_cli/report/
markdown.rs

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
9/// Escape backticks in user-controlled strings to prevent breaking markdown code spans.
10fn 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
18/// Build markdown output for analysis results.
19pub 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    // ── Unused files ──
41    markdown_section(&mut out, &results.unused_files, "Unused files", |file| {
42        vec![format!("- `{}`", rel(&file.path))]
43    });
44
45    // ── Unused exports ──
46    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    // ── Unused types ──
56    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    // ── Unused dependencies ──
66    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    // ── Unused devDependencies ──
74    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    // ── Unused optionalDependencies ──
82    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    // ── Unused enum members ──
90    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    // ── Unused class members ──
100    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    // ── Unresolved imports ──
110    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    // ── Unlisted dependencies ──
120    markdown_section(
121        &mut out,
122        &results.unlisted_dependencies,
123        "Unlisted dependencies",
124        |dep| vec![format!("- `{}`", escape_backticks(&dep.package_name))],
125    );
126
127    // ── Duplicate exports ──
128    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    // ── Type-only dependencies ──
147    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    // ── Circular dependencies ──
155    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
204/// Emit a markdown section with a header and per-item lines. Skipped if empty.
205fn 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
224/// Emit a markdown section whose items are grouped by file path.
225fn 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
255// ── Duplication markdown output ──────────────────────────────────
256
257pub(super) fn print_duplication_markdown(report: &DuplicationReport, root: &Path) {
258    println!("{}", build_duplication_markdown(report, root));
259}
260
261/// Build markdown output for duplication results.
262pub 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    // Clone families
303    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    // Summary line
333    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
349// ── Health markdown output ──────────────────────────────────────────
350
351pub(super) fn print_health_markdown(report: &crate::health_types::HealthReport, root: &Path) {
352    println!("{}", build_health_markdown(report, root));
353}
354
355/// Build markdown output for health (complexity) results.
356pub 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    // Vital signs summary table
366    if let Some(ref vs) = report.vital_signs {
367        out.push_str("## Vital Signs\n\n");
368        out.push_str("| Metric | Value |\n");
369        out.push_str("|:-------|------:|\n");
370        let _ = writeln!(out, "| Avg Cyclomatic | {:.1} |", vs.avg_cyclomatic);
371        let _ = writeln!(out, "| P90 Cyclomatic | {} |", vs.p90_cyclomatic);
372        if let Some(v) = vs.dead_file_pct {
373            let _ = writeln!(out, "| Dead Files | {v:.1}% |");
374        }
375        if let Some(v) = vs.dead_export_pct {
376            let _ = writeln!(out, "| Dead Exports | {v:.1}% |");
377        }
378        if let Some(v) = vs.maintainability_avg {
379            let _ = writeln!(out, "| Maintainability (avg) | {v:.1} |");
380        }
381        if let Some(v) = vs.hotspot_count {
382            let _ = writeln!(out, "| Hotspots | {v} |");
383        }
384        if let Some(v) = vs.circular_dep_count {
385            let _ = writeln!(out, "| Circular Deps | {v} |");
386        }
387        if let Some(v) = vs.unused_dep_count {
388            let _ = writeln!(out, "| Unused Deps | {v} |");
389        }
390        out.push('\n');
391    }
392
393    if report.findings.is_empty()
394        && report.file_scores.is_empty()
395        && report.hotspots.is_empty()
396        && report.targets.is_empty()
397    {
398        if report.vital_signs.is_none() {
399            let _ = write!(
400                out,
401                "## Fallow: no functions exceed complexity thresholds\n\n\
402                 **{}** functions analyzed (max cyclomatic: {}, max cognitive: {})\n",
403                report.summary.functions_analyzed,
404                report.summary.max_cyclomatic_threshold,
405                report.summary.max_cognitive_threshold,
406            );
407        }
408        return out;
409    }
410
411    if !report.findings.is_empty() {
412        let count = report.summary.functions_above_threshold;
413        let shown = report.findings.len();
414        if shown < count {
415            let _ = write!(
416                out,
417                "## Fallow: {count} high complexity function{} ({shown} shown)\n\n",
418                if count == 1 { "" } else { "s" },
419            );
420        } else {
421            let _ = write!(
422                out,
423                "## Fallow: {count} high complexity function{}\n\n",
424                if count == 1 { "" } else { "s" },
425            );
426        }
427
428        out.push_str("| File | Function | Cyclomatic | Cognitive | Lines |\n");
429        out.push_str("|:-----|:---------|:-----------|:----------|:------|\n");
430
431        for finding in &report.findings {
432            let file_str = rel(&finding.path);
433            let cyc_marker = if finding.cyclomatic > report.summary.max_cyclomatic_threshold {
434                " **!**"
435            } else {
436                ""
437            };
438            let cog_marker = if finding.cognitive > report.summary.max_cognitive_threshold {
439                " **!**"
440            } else {
441                ""
442            };
443            let _ = writeln!(
444                out,
445                "| `{file_str}:{line}` | `{name}` | {cyc}{cyc_marker} | {cog}{cog_marker} | {lines} |",
446                line = finding.line,
447                name = escape_backticks(&finding.name),
448                cyc = finding.cyclomatic,
449                cog = finding.cognitive,
450                lines = finding.line_count,
451            );
452        }
453
454        let s = &report.summary;
455        let _ = write!(
456            out,
457            "\n**{files}** files, **{funcs}** functions analyzed \
458             (thresholds: cyclomatic > {cyc}, cognitive > {cog})\n",
459            files = s.files_analyzed,
460            funcs = s.functions_analyzed,
461            cyc = s.max_cyclomatic_threshold,
462            cog = s.max_cognitive_threshold,
463        );
464    }
465
466    // File health scores table
467    if !report.file_scores.is_empty() {
468        out.push('\n');
469        let _ = writeln!(
470            out,
471            "### File Health Scores ({} files)\n",
472            report.file_scores.len(),
473        );
474        out.push_str("| File | MI | Fan-in | Fan-out | Dead Code | Density |\n");
475        out.push_str("|:-----|:---|:-------|:--------|:----------|:--------|\n");
476
477        for score in &report.file_scores {
478            let file_str = rel(&score.path);
479            let _ = writeln!(
480                out,
481                "| `{file_str}` | {mi:.1} | {fi} | {fan_out} | {dead:.0}% | {density:.2} |",
482                mi = score.maintainability_index,
483                fi = score.fan_in,
484                fan_out = score.fan_out,
485                dead = score.dead_code_ratio * 100.0,
486                density = score.complexity_density,
487            );
488        }
489
490        if let Some(avg) = report.summary.average_maintainability {
491            let _ = write!(out, "\n**Average maintainability index:** {avg:.1}/100\n");
492        }
493    }
494
495    // Hotspot table
496    if !report.hotspots.is_empty() {
497        out.push('\n');
498        let header = if let Some(ref summary) = report.hotspot_summary {
499            format!(
500                "### Hotspots ({} files, since {})\n",
501                report.hotspots.len(),
502                summary.since,
503            )
504        } else {
505            format!("### Hotspots ({} files)\n", report.hotspots.len())
506        };
507        let _ = writeln!(out, "{header}");
508        out.push_str("| File | Score | Commits | Churn | Density | Fan-in | Trend |\n");
509        out.push_str("|:-----|:------|:--------|:------|:--------|:-------|:------|\n");
510
511        for entry in &report.hotspots {
512            let file_str = rel(&entry.path);
513            let _ = writeln!(
514                out,
515                "| `{file_str}` | {score:.1} | {commits} | {churn} | {density:.2} | {fi} | {trend} |",
516                score = entry.score,
517                commits = entry.commits,
518                churn = entry.lines_added + entry.lines_deleted,
519                density = entry.complexity_density,
520                fi = entry.fan_in,
521                trend = entry.trend,
522            );
523        }
524
525        if let Some(ref summary) = report.hotspot_summary
526            && summary.files_excluded > 0
527        {
528            let _ = write!(
529                out,
530                "\n*{} file{} excluded (< {} commits)*\n",
531                summary.files_excluded,
532                if summary.files_excluded == 1 { "" } else { "s" },
533                summary.min_commits,
534            );
535        }
536    }
537
538    // Refactoring targets
539    if !report.targets.is_empty() {
540        let _ = write!(
541            out,
542            "\n### Refactoring Targets ({})\n\n",
543            report.targets.len()
544        );
545        out.push_str("| Priority | Category | Effort | File | Recommendation |\n");
546        out.push_str("|----------|----------|--------|------|----------------|\n");
547        for target in &report.targets {
548            let file_str = normalize_uri(&relative_path(&target.path, root).display().to_string());
549            let category = target.category.label();
550            let effort = target.effort.label();
551            let _ = writeln!(
552                out,
553                "| {:.1} | {category} | {effort} | `{file_str}` | {} |",
554                target.priority, target.recommendation,
555            );
556        }
557    }
558
559    // Metric legend — explains abbreviations used in the tables above
560    let has_scores = !report.file_scores.is_empty();
561    let has_hotspots = !report.hotspots.is_empty();
562    let has_targets = !report.targets.is_empty();
563    if has_scores || has_hotspots || has_targets {
564        out.push_str("\n---\n\n<details><summary>Metric definitions</summary>\n\n");
565        if has_scores {
566            out.push_str("- **MI** — Maintainability Index (0\u{2013}100, higher is better)\n");
567            out.push_str("- **Fan-in** — files that import this file (blast radius)\n");
568            out.push_str("- **Fan-out** — files this file imports (coupling)\n");
569            out.push_str("- **Dead Code** — % of value exports with zero references\n");
570            out.push_str("- **Density** — cyclomatic complexity / lines of code\n");
571        }
572        if has_hotspots {
573            out.push_str(
574                "- **Score** — churn \u{00d7} complexity (0\u{2013}100, higher = riskier)\n",
575            );
576            out.push_str("- **Commits** — commits in the analysis window\n");
577            out.push_str("- **Churn** — total lines added + deleted\n");
578            out.push_str("- **Trend** — accelerating / stable / cooling\n");
579        }
580        if has_targets {
581            out.push_str("- **Priority** — weighted refactoring urgency (0\u{2013}100, higher = more urgent)\n");
582            out.push_str("- **Category** — recommendation type (churn+complexity, high impact, dead code, complexity, coupling, circular dep)\n");
583            out.push_str("- **Effort** — estimated effort (low / medium / high) based on file size, function count, and fan-in\n");
584        }
585        out.push_str("\n[Full metric reference](https://docs.fallow.tools/explanations/metrics)\n\n</details>\n");
586    }
587
588    out
589}
590
591#[cfg(test)]
592mod tests {
593    use super::*;
594    use fallow_core::duplicates::{
595        CloneFamily, CloneGroup, CloneInstance, DuplicationReport, DuplicationStats,
596        RefactoringKind, RefactoringSuggestion,
597    };
598    use fallow_core::extract::MemberKind;
599    use fallow_core::results::*;
600    use std::path::PathBuf;
601
602    /// Helper: build an `AnalysisResults` populated with one issue of every type.
603    fn sample_results(root: &Path) -> AnalysisResults {
604        let mut r = AnalysisResults::default();
605
606        r.unused_files.push(UnusedFile {
607            path: root.join("src/dead.ts"),
608        });
609        r.unused_exports.push(UnusedExport {
610            path: root.join("src/utils.ts"),
611            export_name: "helperFn".to_string(),
612            is_type_only: false,
613            line: 10,
614            col: 4,
615            span_start: 120,
616            is_re_export: false,
617        });
618        r.unused_types.push(UnusedExport {
619            path: root.join("src/types.ts"),
620            export_name: "OldType".to_string(),
621            is_type_only: true,
622            line: 5,
623            col: 0,
624            span_start: 60,
625            is_re_export: false,
626        });
627        r.unused_dependencies.push(UnusedDependency {
628            package_name: "lodash".to_string(),
629            location: DependencyLocation::Dependencies,
630            path: root.join("package.json"),
631            line: 5,
632        });
633        r.unused_dev_dependencies.push(UnusedDependency {
634            package_name: "jest".to_string(),
635            location: DependencyLocation::DevDependencies,
636            path: root.join("package.json"),
637            line: 5,
638        });
639        r.unused_enum_members.push(UnusedMember {
640            path: root.join("src/enums.ts"),
641            parent_name: "Status".to_string(),
642            member_name: "Deprecated".to_string(),
643            kind: MemberKind::EnumMember,
644            line: 8,
645            col: 2,
646        });
647        r.unused_class_members.push(UnusedMember {
648            path: root.join("src/service.ts"),
649            parent_name: "UserService".to_string(),
650            member_name: "legacyMethod".to_string(),
651            kind: MemberKind::ClassMethod,
652            line: 42,
653            col: 4,
654        });
655        r.unresolved_imports.push(UnresolvedImport {
656            path: root.join("src/app.ts"),
657            specifier: "./missing-module".to_string(),
658            line: 3,
659            col: 0,
660            specifier_col: 0,
661        });
662        r.unlisted_dependencies.push(UnlistedDependency {
663            package_name: "chalk".to_string(),
664            imported_from: vec![ImportSite {
665                path: root.join("src/cli.ts"),
666                line: 2,
667                col: 0,
668            }],
669        });
670        r.duplicate_exports.push(DuplicateExport {
671            export_name: "Config".to_string(),
672            locations: vec![
673                DuplicateLocation {
674                    path: root.join("src/config.ts"),
675                    line: 15,
676                    col: 0,
677                },
678                DuplicateLocation {
679                    path: root.join("src/types.ts"),
680                    line: 30,
681                    col: 0,
682                },
683            ],
684        });
685        r.type_only_dependencies.push(TypeOnlyDependency {
686            package_name: "zod".to_string(),
687            path: root.join("package.json"),
688            line: 8,
689        });
690        r.circular_dependencies.push(CircularDependency {
691            files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
692            length: 2,
693            line: 3,
694            col: 0,
695        });
696
697        r
698    }
699
700    #[test]
701    fn markdown_empty_results_no_issues() {
702        let root = PathBuf::from("/project");
703        let results = AnalysisResults::default();
704        let md = build_markdown(&results, &root);
705        assert_eq!(md, "## Fallow: no issues found\n");
706    }
707
708    #[test]
709    fn markdown_contains_header_with_count() {
710        let root = PathBuf::from("/project");
711        let results = sample_results(&root);
712        let md = build_markdown(&results, &root);
713        assert!(md.starts_with(&format!(
714            "## Fallow: {} issues found\n",
715            results.total_issues()
716        )));
717    }
718
719    #[test]
720    fn markdown_contains_all_sections() {
721        let root = PathBuf::from("/project");
722        let results = sample_results(&root);
723        let md = build_markdown(&results, &root);
724
725        assert!(md.contains("### Unused files (1)"));
726        assert!(md.contains("### Unused exports (1)"));
727        assert!(md.contains("### Unused type exports (1)"));
728        assert!(md.contains("### Unused dependencies (1)"));
729        assert!(md.contains("### Unused devDependencies (1)"));
730        assert!(md.contains("### Unused enum members (1)"));
731        assert!(md.contains("### Unused class members (1)"));
732        assert!(md.contains("### Unresolved imports (1)"));
733        assert!(md.contains("### Unlisted dependencies (1)"));
734        assert!(md.contains("### Duplicate exports (1)"));
735        assert!(md.contains("### Type-only dependencies"));
736        assert!(md.contains("### Circular dependencies (1)"));
737    }
738
739    #[test]
740    fn markdown_unused_file_format() {
741        let root = PathBuf::from("/project");
742        let mut results = AnalysisResults::default();
743        results.unused_files.push(UnusedFile {
744            path: root.join("src/dead.ts"),
745        });
746        let md = build_markdown(&results, &root);
747        assert!(md.contains("- `src/dead.ts`"));
748    }
749
750    #[test]
751    fn markdown_unused_export_grouped_by_file() {
752        let root = PathBuf::from("/project");
753        let mut results = AnalysisResults::default();
754        results.unused_exports.push(UnusedExport {
755            path: root.join("src/utils.ts"),
756            export_name: "helperFn".to_string(),
757            is_type_only: false,
758            line: 10,
759            col: 4,
760            span_start: 120,
761            is_re_export: false,
762        });
763        let md = build_markdown(&results, &root);
764        assert!(md.contains("- `src/utils.ts`"));
765        assert!(md.contains(":10 `helperFn`"));
766    }
767
768    #[test]
769    fn markdown_re_export_tagged() {
770        let root = PathBuf::from("/project");
771        let mut results = AnalysisResults::default();
772        results.unused_exports.push(UnusedExport {
773            path: root.join("src/index.ts"),
774            export_name: "reExported".to_string(),
775            is_type_only: false,
776            line: 1,
777            col: 0,
778            span_start: 0,
779            is_re_export: true,
780        });
781        let md = build_markdown(&results, &root);
782        assert!(md.contains("(re-export)"));
783    }
784
785    #[test]
786    fn markdown_unused_dep_format() {
787        let root = PathBuf::from("/project");
788        let mut results = AnalysisResults::default();
789        results.unused_dependencies.push(UnusedDependency {
790            package_name: "lodash".to_string(),
791            location: DependencyLocation::Dependencies,
792            path: root.join("package.json"),
793            line: 5,
794        });
795        let md = build_markdown(&results, &root);
796        assert!(md.contains("- `lodash`"));
797    }
798
799    #[test]
800    fn markdown_circular_dep_format() {
801        let root = PathBuf::from("/project");
802        let mut results = AnalysisResults::default();
803        results.circular_dependencies.push(CircularDependency {
804            files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
805            length: 2,
806            line: 3,
807            col: 0,
808        });
809        let md = build_markdown(&results, &root);
810        assert!(md.contains("`src/a.ts`"));
811        assert!(md.contains("`src/b.ts`"));
812        assert!(md.contains("\u{2192}"));
813    }
814
815    #[test]
816    fn markdown_strips_root_prefix() {
817        let root = PathBuf::from("/project");
818        let mut results = AnalysisResults::default();
819        results.unused_files.push(UnusedFile {
820            path: PathBuf::from("/project/src/deep/nested/file.ts"),
821        });
822        let md = build_markdown(&results, &root);
823        assert!(md.contains("`src/deep/nested/file.ts`"));
824        assert!(!md.contains("/project/"));
825    }
826
827    #[test]
828    fn markdown_single_issue_no_plural() {
829        let root = PathBuf::from("/project");
830        let mut results = AnalysisResults::default();
831        results.unused_files.push(UnusedFile {
832            path: root.join("src/dead.ts"),
833        });
834        let md = build_markdown(&results, &root);
835        assert!(md.starts_with("## Fallow: 1 issue found\n"));
836    }
837
838    #[test]
839    fn markdown_type_only_dep_format() {
840        let root = PathBuf::from("/project");
841        let mut results = AnalysisResults::default();
842        results.type_only_dependencies.push(TypeOnlyDependency {
843            package_name: "zod".to_string(),
844            path: root.join("package.json"),
845            line: 8,
846        });
847        let md = build_markdown(&results, &root);
848        assert!(md.contains("### Type-only dependencies"));
849        assert!(md.contains("- `zod`"));
850    }
851
852    #[test]
853    fn markdown_escapes_backticks_in_export_names() {
854        let root = PathBuf::from("/project");
855        let mut results = AnalysisResults::default();
856        results.unused_exports.push(UnusedExport {
857            path: root.join("src/utils.ts"),
858            export_name: "foo`bar".to_string(),
859            is_type_only: false,
860            line: 1,
861            col: 0,
862            span_start: 0,
863            is_re_export: false,
864        });
865        let md = build_markdown(&results, &root);
866        assert!(md.contains("foo\\`bar"));
867        assert!(!md.contains("foo`bar`"));
868    }
869
870    #[test]
871    fn markdown_escapes_backticks_in_package_names() {
872        let root = PathBuf::from("/project");
873        let mut results = AnalysisResults::default();
874        results.unused_dependencies.push(UnusedDependency {
875            package_name: "pkg`name".to_string(),
876            location: DependencyLocation::Dependencies,
877            path: root.join("package.json"),
878            line: 5,
879        });
880        let md = build_markdown(&results, &root);
881        assert!(md.contains("pkg\\`name"));
882    }
883
884    // ── Duplication markdown ──
885
886    #[test]
887    fn duplication_markdown_empty() {
888        let report = DuplicationReport::default();
889        let root = PathBuf::from("/project");
890        let md = build_duplication_markdown(&report, &root);
891        assert_eq!(md, "## Fallow: no code duplication found\n");
892    }
893
894    #[test]
895    fn duplication_markdown_contains_groups() {
896        let root = PathBuf::from("/project");
897        let report = DuplicationReport {
898            clone_groups: vec![CloneGroup {
899                instances: vec![
900                    CloneInstance {
901                        file: root.join("src/a.ts"),
902                        start_line: 1,
903                        end_line: 10,
904                        start_col: 0,
905                        end_col: 0,
906                        fragment: String::new(),
907                    },
908                    CloneInstance {
909                        file: root.join("src/b.ts"),
910                        start_line: 5,
911                        end_line: 14,
912                        start_col: 0,
913                        end_col: 0,
914                        fragment: String::new(),
915                    },
916                ],
917                token_count: 50,
918                line_count: 10,
919            }],
920            clone_families: vec![],
921            stats: DuplicationStats {
922                total_files: 10,
923                files_with_clones: 2,
924                total_lines: 500,
925                duplicated_lines: 20,
926                total_tokens: 2500,
927                duplicated_tokens: 100,
928                clone_groups: 1,
929                clone_instances: 2,
930                duplication_percentage: 4.0,
931            },
932        };
933        let md = build_duplication_markdown(&report, &root);
934        assert!(md.contains("**Clone group 1**"));
935        assert!(md.contains("`src/a.ts:1-10`"));
936        assert!(md.contains("`src/b.ts:5-14`"));
937        assert!(md.contains("4.0% duplication"));
938    }
939
940    #[test]
941    fn duplication_markdown_contains_families() {
942        let root = PathBuf::from("/project");
943        let report = DuplicationReport {
944            clone_groups: vec![CloneGroup {
945                instances: vec![CloneInstance {
946                    file: root.join("src/a.ts"),
947                    start_line: 1,
948                    end_line: 5,
949                    start_col: 0,
950                    end_col: 0,
951                    fragment: String::new(),
952                }],
953                token_count: 30,
954                line_count: 5,
955            }],
956            clone_families: vec![CloneFamily {
957                files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
958                groups: vec![],
959                total_duplicated_lines: 20,
960                total_duplicated_tokens: 100,
961                suggestions: vec![RefactoringSuggestion {
962                    kind: RefactoringKind::ExtractFunction,
963                    description: "Extract shared utility function".to_string(),
964                    estimated_savings: 15,
965                }],
966            }],
967            stats: DuplicationStats {
968                clone_groups: 1,
969                clone_instances: 1,
970                duplication_percentage: 2.0,
971                ..Default::default()
972            },
973        };
974        let md = build_duplication_markdown(&report, &root);
975        assert!(md.contains("### Clone Families"));
976        assert!(md.contains("**Family 1**"));
977        assert!(md.contains("Extract shared utility function"));
978        assert!(md.contains("~15 lines saved"));
979    }
980
981    // ── Health markdown ──
982
983    #[test]
984    fn health_markdown_empty_no_findings() {
985        let root = PathBuf::from("/project");
986        let report = crate::health_types::HealthReport {
987            findings: vec![],
988            summary: crate::health_types::HealthSummary {
989                files_analyzed: 10,
990                functions_analyzed: 50,
991                functions_above_threshold: 0,
992                max_cyclomatic_threshold: 20,
993                max_cognitive_threshold: 15,
994                files_scored: None,
995                average_maintainability: None,
996            },
997            vital_signs: None,
998            file_scores: vec![],
999            hotspots: vec![],
1000            hotspot_summary: None,
1001            targets: vec![],
1002        };
1003        let md = build_health_markdown(&report, &root);
1004        assert!(md.contains("no functions exceed complexity thresholds"));
1005        assert!(md.contains("**50** functions analyzed"));
1006    }
1007
1008    #[test]
1009    fn health_markdown_table_format() {
1010        let root = PathBuf::from("/project");
1011        let report = crate::health_types::HealthReport {
1012            findings: vec![crate::health_types::HealthFinding {
1013                path: root.join("src/utils.ts"),
1014                name: "parseExpression".to_string(),
1015                line: 42,
1016                col: 0,
1017                cyclomatic: 25,
1018                cognitive: 30,
1019                line_count: 80,
1020                exceeded: crate::health_types::ExceededThreshold::Both,
1021            }],
1022            summary: crate::health_types::HealthSummary {
1023                files_analyzed: 10,
1024                functions_analyzed: 50,
1025                functions_above_threshold: 1,
1026                max_cyclomatic_threshold: 20,
1027                max_cognitive_threshold: 15,
1028                files_scored: None,
1029                average_maintainability: None,
1030            },
1031            vital_signs: None,
1032            file_scores: vec![],
1033            hotspots: vec![],
1034            hotspot_summary: None,
1035            targets: vec![],
1036        };
1037        let md = build_health_markdown(&report, &root);
1038        assert!(md.contains("## Fallow: 1 high complexity function\n"));
1039        assert!(md.contains("| File | Function |"));
1040        assert!(md.contains("`src/utils.ts:42`"));
1041        assert!(md.contains("`parseExpression`"));
1042        assert!(md.contains("25 **!**"));
1043        assert!(md.contains("30 **!**"));
1044        assert!(md.contains("| 80 |"));
1045    }
1046
1047    #[test]
1048    fn health_markdown_no_marker_when_below_threshold() {
1049        let root = PathBuf::from("/project");
1050        let report = crate::health_types::HealthReport {
1051            findings: vec![crate::health_types::HealthFinding {
1052                path: root.join("src/utils.ts"),
1053                name: "helper".to_string(),
1054                line: 10,
1055                col: 0,
1056                cyclomatic: 15,
1057                cognitive: 20,
1058                line_count: 30,
1059                exceeded: crate::health_types::ExceededThreshold::Cognitive,
1060            }],
1061            summary: crate::health_types::HealthSummary {
1062                files_analyzed: 5,
1063                functions_analyzed: 20,
1064                functions_above_threshold: 1,
1065                max_cyclomatic_threshold: 20,
1066                max_cognitive_threshold: 15,
1067                files_scored: None,
1068                average_maintainability: None,
1069            },
1070            vital_signs: None,
1071            file_scores: vec![],
1072            hotspots: vec![],
1073            hotspot_summary: None,
1074            targets: vec![],
1075        };
1076        let md = build_health_markdown(&report, &root);
1077        // Cyclomatic 15 is below threshold 20, no marker
1078        assert!(md.contains("| 15 |"));
1079        // Cognitive 20 exceeds threshold 15, has marker
1080        assert!(md.contains("20 **!**"));
1081    }
1082
1083    #[test]
1084    fn health_markdown_with_targets() {
1085        use crate::health_types::*;
1086
1087        let root = PathBuf::from("/project");
1088        let report = HealthReport {
1089            findings: vec![],
1090            summary: HealthSummary {
1091                files_analyzed: 10,
1092                functions_analyzed: 50,
1093                functions_above_threshold: 0,
1094                max_cyclomatic_threshold: 20,
1095                max_cognitive_threshold: 15,
1096                files_scored: None,
1097                average_maintainability: None,
1098            },
1099            vital_signs: None,
1100            file_scores: vec![],
1101            hotspots: vec![],
1102            hotspot_summary: None,
1103            targets: vec![
1104                RefactoringTarget {
1105                    path: PathBuf::from("/project/src/complex.ts"),
1106                    priority: 82.5,
1107                    recommendation: "Split high-impact file".into(),
1108                    category: RecommendationCategory::SplitHighImpact,
1109                    effort: crate::health_types::EffortEstimate::High,
1110                    factors: vec![ContributingFactor {
1111                        metric: "fan_in",
1112                        value: 25.0,
1113                        threshold: 10.0,
1114                        detail: "25 files depend on this".into(),
1115                    }],
1116                    evidence: None,
1117                },
1118                RefactoringTarget {
1119                    path: PathBuf::from("/project/src/legacy.ts"),
1120                    priority: 45.0,
1121                    recommendation: "Remove 5 unused exports".into(),
1122                    category: RecommendationCategory::RemoveDeadCode,
1123                    effort: crate::health_types::EffortEstimate::Low,
1124                    factors: vec![],
1125                    evidence: None,
1126                },
1127            ],
1128        };
1129        let md = build_health_markdown(&report, &root);
1130
1131        // Should have refactoring targets section
1132        assert!(
1133            md.contains("Refactoring Targets"),
1134            "should contain targets heading"
1135        );
1136        assert!(
1137            md.contains("src/complex.ts"),
1138            "should contain target file path"
1139        );
1140        assert!(md.contains("82.5"), "should contain priority score");
1141        assert!(
1142            md.contains("Split high-impact file"),
1143            "should contain recommendation"
1144        );
1145        assert!(md.contains("src/legacy.ts"), "should contain second target");
1146    }
1147}