churnloom 0.1.0

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

use serde::Serialize;

#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
/// How a source file contributes to a Cargo package.
pub enum SourceKind {
    /// Shipped library or executable code.
    Production,
    /// A dedicated unit-test source or inline test-only code.
    UnitTest,
    /// A Cargo integration-test target or file under `tests/`.
    IntegrationTest,
    /// A Cargo benchmark target or file under `benches/`.
    Bench,
    /// A Cargo example target or file under `examples/`.
    Example,
    /// A Cargo build script.
    Build,
    /// Recognized source that does not fit another category.
    #[default]
    Other,
}

impl SourceKind {
    #[must_use]
    pub(crate) const fn label(self) -> &'static str {
        match self {
            Self::Production => "prod",
            Self::UnitTest => "unit",
            Self::IntegrationTest => "integ",
            Self::Bench => "bench",
            Self::Example => "example",
            Self::Build => "build",
            Self::Other => "other",
        }
    }

    #[must_use]
    pub(crate) const fn is_test(self) -> bool {
        matches!(self, Self::UnitTest | Self::IntegrationTest | Self::Bench)
    }
}

#[derive(Clone, Copy, Debug, Default, Serialize)]
/// Physical line counts for one source or an aggregate.
pub struct LineStats {
    /// Lines containing code.
    pub code: usize,
    /// Comment-only lines.
    pub comments: usize,
    /// Blank lines.
    pub blanks: usize,
}

impl LineStats {
    #[must_use]
    /// Returns code, comment, and blank lines combined.
    pub const fn lines(self) -> usize {
        self.code + self.comments + self.blanks
    }

    pub(crate) fn add_assign(&mut self, other: Self) {
        self.code += other.code;
        self.comments += other.comments;
        self.blanks += other.blanks;
    }
}

#[derive(Clone, Copy, Debug, Default, Serialize)]
/// Git additions and deletions for a time window.
pub struct Churn {
    /// Added lines.
    pub added: u64,
    /// Deleted lines.
    pub deleted: u64,
}

impl Churn {
    #[must_use]
    /// Returns additions and deletions combined.
    pub const fn changed(self) -> u64 {
        self.added + self.deleted
    }

    pub(crate) fn add(&mut self, added: u64, deleted: u64) {
        self.added += added;
        self.deleted += deleted;
    }
}

#[derive(Clone, Debug, Default, Serialize)]
/// Lightweight structural signals collected from a source file.
pub struct StructureMetrics {
    /// Count of recognized control-flow tokens.
    pub control_tokens: usize,
    /// Maximum observed brace nesting depth.
    pub max_brace_depth: usize,
    /// Line length of the longest recognized function.
    pub max_function_lines: usize,
    /// Number of recognized functions.
    pub function_count: usize,
    /// Unnormalized structural-complexity value.
    pub complexity_raw: f64,
    /// Unnormalized context-cost value.
    pub context_cost_raw: f64,
}

#[derive(Clone, Debug, Serialize)]
/// Metrics and ranking signals for one analyzed file.
pub struct FileMetrics {
    /// Project-relative path using forward slashes.
    pub path: String,
    /// Language name reported by tokei.
    pub language: String,
    /// Owning Cargo package, when one was discovered.
    pub crate_name: Option<String>,
    /// Cargo/source classification.
    pub kind: SourceKind,
    /// Physical line counts for the complete file.
    pub lines: LineStats,
    /// Inline Rust code that is compiled only for tests.
    pub inline_test_lines: LineStats,
    /// Churn inside the configured short window.
    pub churn_short: Churn,
    /// Churn inside the configured long window.
    pub churn_long: Churn,
    /// Lightweight structural signals.
    pub structure: StructureMetrics,
    /// Normalized Churnloom hotspot score.
    pub hotspot_score: f64,
}

impl FileMetrics {
    #[must_use]
    /// Returns production code lines after subtracting inline test-only code.
    pub fn production_code(&self) -> usize {
        if self.kind == SourceKind::Production {
            self.lines.code.saturating_sub(self.inline_test_lines.code)
        } else {
            0
        }
    }

    #[must_use]
    /// Returns whole-file and inline test code lines combined.
    pub fn test_code(&self) -> usize {
        let whole_file = usize::from(self.kind.is_test()) * self.lines.code;
        whole_file + self.inline_test_lines.code
    }
}

#[derive(Clone, Debug, Default, Serialize)]
/// Aggregate line counts for one detected language.
pub struct LanguageSummary {
    /// Number of files detected in the language.
    pub files: usize,
    /// Aggregate physical line counts.
    pub lines: LineStats,
}

#[derive(Clone, Debug, Default, Serialize)]
/// Aggregate code and churn metrics for one Cargo package.
pub struct CrateSummary {
    /// Cargo package name.
    pub name: String,
    /// Number of recognized files owned by the package.
    pub files: usize,
    /// Production code lines.
    pub production_code: usize,
    /// Inline and dedicated unit-test code lines.
    pub unit_test_code: usize,
    /// Integration-test code lines.
    pub integration_test_code: usize,
    /// Benchmark code lines.
    pub bench_code: usize,
    /// Example code lines.
    pub example_code: usize,
    /// Build-script code lines.
    pub build_code: usize,
    /// Recognized code lines that do not fit another category.
    pub other_code: usize,
    /// Aggregate churn in the configured short window.
    pub churn_short: u64,
    /// Aggregate churn in the configured long window.
    pub churn_long: u64,
}

impl CrateSummary {
    #[must_use]
    /// Returns unit-test, integration-test, and benchmark code combined.
    pub const fn test_code(&self) -> usize {
        self.unit_test_code + self.integration_test_code + self.bench_code
    }

    #[must_use]
    /// Returns all classified code lines owned by the package.
    pub const fn total_code(&self) -> usize {
        self.production_code
            + self.test_code()
            + self.example_code
            + self.build_code
            + self.other_code
    }
}

#[derive(Clone, Debug, Default, Serialize)]
/// Aggregate Git throughput for one configured time window.
pub struct ThroughputSummary {
    /// Calendar-day width of the window.
    pub days: u32,
    /// Added lines in eligible current files.
    pub added: u64,
    /// Deleted lines in eligible current files.
    pub deleted: u64,
    /// Added and deleted lines combined.
    pub changed: u64,
    /// Commits touching eligible current files.
    pub commits: usize,
    /// Calendar days containing at least one eligible change.
    pub active_days: usize,
}

#[derive(Clone, Debug, Default, Serialize)]
/// Git throughput for one calendar day.
pub struct DailyThroughput {
    /// ISO 8601 calendar date.
    pub date: String,
    /// Added lines.
    pub added: u64,
    /// Deleted lines.
    pub deleted: u64,
    /// Added and deleted lines combined.
    pub changed: u64,
    /// Commits touching eligible current files.
    pub commits: usize,
}

impl DailyThroughput {
    pub(crate) fn add(&mut self, added: u64, deleted: u64) {
        self.added += added;
        self.deleted += deleted;
        self.changed += added + deleted;
    }
}

#[derive(Clone, Debug, Default, Serialize)]
/// Top-level size and Cargo-code totals for an analysis.
pub struct ProjectSummary {
    /// Number of recognized files.
    pub files: usize,
    /// Number of discovered Cargo packages.
    pub crates: usize,
    /// Aggregate physical line counts.
    pub lines: LineStats,
    /// Production code lines across Cargo packages.
    pub production_code: usize,
    /// Test and benchmark code lines across Cargo packages.
    pub test_code: usize,
}

#[derive(Clone, Debug, Serialize)]
/// Complete structured result returned by [`crate::analyze`].
pub struct AnalysisReport {
    /// Version of the serialized JSON schema.
    pub schema_version: u32,
    /// Canonical path of the analyzed project.
    pub project_root: String,
    /// Canonical containing Git repository path, when found.
    pub git_root: Option<String>,
    /// Configured recent churn window in days.
    pub short_days: u32,
    /// Configured longer churn window in days.
    pub long_days: u32,
    /// Top-level project totals.
    pub summary: ProjectSummary,
    /// Git throughput inside the short window.
    pub throughput_short: ThroughputSummary,
    /// Git throughput inside the long window.
    pub throughput_long: ThroughputSummary,
    /// Per-day Git throughput inside the long window.
    pub daily_long: Vec<DailyThroughput>,
    /// Totals keyed by detected language name.
    pub languages: BTreeMap<String, LanguageSummary>,
    /// Cargo package totals, sorted by total code descending.
    pub crates: Vec<CrateSummary>,
    /// Ranked per-file metrics, highest hotspot score first.
    pub files: Vec<FileMetrics>,
    /// Non-fatal Cargo or Git analysis problems.
    pub warnings: Vec<String>,
}