churnloom 0.1.0

Fast codebase health reports woven from churn, LOC, structure, and Cargo ownership
Documentation
use std::fmt::Write;

use anyhow::Result;

use crate::model::{AnalysisReport, CrateSummary, LanguageSummary, ThroughputSummary};

pub fn print_text(report: &AnalysisReport, top: usize, show_daily: bool) {
    println!("{}", render_text(report, top, show_daily));
}

pub fn print_json(report: &AnalysisReport, top: usize) -> Result<()> {
    println!("{}", render_json(report, top)?);
    Ok(())
}

fn render_json(report: &AnalysisReport, top: usize) -> Result<String> {
    if top == 0 || top >= report.files.len() {
        return Ok(serde_json::to_string_pretty(report)?);
    }

    let mut bounded = report.clone();
    bounded.files.truncate(top);
    Ok(serde_json::to_string_pretty(&bounded)?)
}

pub fn render_text(report: &AnalysisReport, top: usize, show_daily: bool) -> String {
    let mut output = String::new();
    let summary = &report.summary;
    let _ = writeln!(output, "Churnloom — {}", report.project_root);
    let _ = writeln!(
        output,
        "files={} crates={} code={} comments={} blanks={} lines={}",
        summary.files,
        summary.crates,
        summary.lines.code,
        summary.lines.comments,
        summary.lines.blanks,
        summary.lines.lines()
    );
    let test_ratio = percentage(
        summary.test_code,
        summary.production_code + summary.test_code,
    );
    let _ = writeln!(
        output,
        "Cargo code: production={} test={} ({test_ratio:.1}% test)",
        summary.production_code, summary.test_code
    );
    let _ = writeln!(output);
    render_throughput(&mut output, "recent", &report.throughput_short);
    render_throughput(&mut output, "long  ", &report.throughput_long);
    if show_daily {
        render_daily(&mut output, report);
    }

    if !report.languages.is_empty() {
        let _ = writeln!(output, "\nLanguages");
        let _ = writeln!(
            output,
            "  language                 files       code   comments     blanks"
        );
        let mut languages = report.languages.iter().collect::<Vec<_>>();
        languages.sort_by_key(|(_, summary)| std::cmp::Reverse(summary.lines.code));
        for (name, language) in languages {
            render_language(&mut output, name, language);
        }
    }

    if !report.crates.is_empty() {
        let _ = writeln!(output, "\nCargo crates");
        let _ = writeln!(
            output,
            "  crate                    total      prod      unit     integ   bench   example   build   churn"
        );
        for summary in &report.crates {
            render_crate(&mut output, summary);
        }
    }

    let displayed = if top == 0 {
        report.files.len()
    } else {
        top.min(report.files.len())
    };
    let _ = writeln!(output, "\nHotspots (top {displayed})");
    let _ = writeln!(
        output,
        "  rank   score  churn_s  churn_l    code  max_fn  depth  kind   path"
    );
    for (index, file) in report.files.iter().take(displayed).enumerate() {
        let _ = writeln!(
            output,
            "  {:>4}  {:>6.3}  {:>7}  {:>7}  {:>6}  {:>6}  {:>5}  {:<5}  {}",
            index + 1,
            file.hotspot_score,
            file.churn_short.changed(),
            file.churn_long.changed(),
            file.lines.code,
            file.structure.max_function_lines,
            file.structure.max_brace_depth,
            file.kind.label(),
            file.path
        );
    }
    let _ = writeln!(
        output,
        "\nscore = complexity × (1 + 0.9×normalized recent churn + 0.35×normalized long churn) + 0.25×normalized context"
    );
    for warning in &report.warnings {
        let _ = writeln!(output, "warning: {warning}");
    }
    output.trim_end().to_string()
}

fn render_daily(output: &mut String, report: &AnalysisReport) {
    let _ = writeln!(output, "\nDaily throughput (long window):");
    let _ = writeln!(output, "  date        changed    add    del  commits");
    for day in &report.daily_long {
        let _ = writeln!(
            output,
            "  {}  {:>7}  {:>5}  {:>5}  {:>7}",
            day.date, day.changed, day.added, day.deleted, day.commits
        );
    }
}

fn render_throughput(output: &mut String, label: &str, summary: &ThroughputSummary) {
    let average = summary.changed as f64 / f64::from(summary.days);
    let _ = writeln!(
        output,
        "{label} churn ({:>3}d): changed={} (+{} -{}) commits={} active_days={} avg/day={average:.1}",
        summary.days,
        summary.changed,
        summary.added,
        summary.deleted,
        summary.commits,
        summary.active_days
    );
}

fn render_language(output: &mut String, name: &str, summary: &LanguageSummary) {
    let _ = writeln!(
        output,
        "  {:<24} {:>5} {:>10} {:>10} {:>10}",
        name, summary.files, summary.lines.code, summary.lines.comments, summary.lines.blanks
    );
}

fn render_crate(output: &mut String, summary: &CrateSummary) {
    let _ = writeln!(
        output,
        "  {:<24} {:>7} {:>9} {:>9} {:>9} {:>7} {:>9} {:>7} {:>7}",
        summary.name,
        summary.total_code(),
        summary.production_code,
        summary.unit_test_code,
        summary.integration_test_code,
        summary.bench_code,
        summary.example_code,
        summary.build_code,
        summary.churn_long
    );
}

fn percentage(part: usize, total: usize) -> f64 {
    if total == 0 {
        0.0
    } else {
        part as f64 * 100.0 / total as f64
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use crate::model::{
        AnalysisReport, Churn, FileMetrics, LineStats, ProjectSummary, SourceKind,
        StructureMetrics, ThroughputSummary,
    };

    use super::render_json;

    #[test]
    fn json_top_bounds_ranked_files_without_changing_the_summary() {
        let file = |path: &str| FileMetrics {
            path: path.to_string(),
            language: "Rust".to_string(),
            crate_name: None,
            kind: SourceKind::Production,
            lines: LineStats::default(),
            inline_test_lines: LineStats::default(),
            churn_short: Churn::default(),
            churn_long: Churn::default(),
            structure: StructureMetrics::default(),
            hotspot_score: 0.0,
        };
        let report = AnalysisReport {
            schema_version: 1,
            project_root: "/project".to_string(),
            git_root: Some("/project".to_string()),
            short_days: 7,
            long_days: 30,
            summary: ProjectSummary {
                files: 2,
                ..ProjectSummary::default()
            },
            throughput_short: ThroughputSummary::default(),
            throughput_long: ThroughputSummary::default(),
            daily_long: Vec::new(),
            languages: BTreeMap::new(),
            crates: Vec::new(),
            files: vec![file("src/lib.rs"), file("src/main.rs")],
            warnings: Vec::new(),
        };

        let rendered = render_json(&report, 1).expect("render bounded JSON");
        let value: serde_json::Value = serde_json::from_str(&rendered).expect("valid JSON");

        assert_eq!(value["summary"]["files"], 2);
        assert_eq!(value["files"].as_array().map(Vec::len), Some(1));
        assert_eq!(report.files.len(), 2);
    }
}