tree2md 0.14.0

Like the tree command, but outputs in Markdown. Optimized for AI agents.
//! Hot spots: how often each file changed in recent git history.
//!
//! The history comes from one `git log --numstat` run over the target
//! directory. Counts are keyed by the path relative to the target, the same
//! form as a node's `display_path`, and are restricted to the files the
//! tree's filters show: a file that is filtered out (a safety-preset secret,
//! `-X`, gitignore) or deleted since never shows up, whatever the history
//! says.

mod git;
mod heat;
mod rank;

pub use heat::{FileHeat, HeatMap};
pub use rank::{visible_files, HotSpots};

use clap::ValueEnum;
use std::path::Path;

/// Commits that touch more files than this (inside the target) are skipped:
/// mass reformatting, renames and vendoring would otherwise make every file
/// they touch look hot.
pub const BULK_COMMIT_FILES: usize = 50;

/// How many files the "Hot spots" ranking lists (and the TTY tree marks),
/// unless `--hot-top` says otherwise.
pub const TOP_N: usize = 10;

/// Under the recency metric a commit's weight halves every this many days.
pub const RECENCY_HALF_LIFE_DAYS: f64 = 30.0;

/// File names whose churn is bookkeeping, not editing: lockfiles and
/// changelogs change with nearly every release or dependency bump.
const NOISE_FILE_NAMES: &[&str] = &[
    "Cargo.lock",
    "package-lock.json",
    "npm-shrinkwrap.json",
    "yarn.lock",
    "pnpm-lock.yaml",
    "bun.lock",
    "bun.lockb",
    "poetry.lock",
    "Pipfile.lock",
    "uv.lock",
    "pdm.lock",
    "Gemfile.lock",
    "composer.lock",
    "go.sum",
    "flake.lock",
    "mix.lock",
    "Podfile.lock",
    "Package.resolved",
    "pubspec.lock",
    "gradle.lockfile",
    "packages.lock.json",
];

/// Changelog stems, compared case-insensitively (`CHANGELOG.md`, `changes.rst`).
const NOISE_STEMS: &[&str] = &["changelog", "changes"];

/// A history window such as `90d`, given as a number and a unit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Span {
    pub days: u32,
    /// Normalized form for display, e.g. `90d`.
    pub label: String,
}

impl Default for Span {
    fn default() -> Self {
        Self {
            days: 90,
            label: "90d".to_string(),
        }
    }
}

/// Parse `<N><unit>` with unit `d` (days), `w` (weeks), `m` (30-day months)
/// or `y` (365-day years). Used as a clap value parser.
pub fn parse_span(s: &str) -> Result<Span, String> {
    let s = s.trim();
    let usage =
        "expected a number and a unit: d (days), w (weeks), m (months), y (years), e.g. 90d or 6m";
    let unit = s.chars().last().ok_or(usage)?;
    let per_unit = match unit.to_ascii_lowercase() {
        'd' => 1,
        'w' => 7,
        'm' => 30,
        'y' => 365,
        _ => return Err(usage.to_string()),
    };
    let n: u32 = s[..s.len() - unit.len_utf8()]
        .parse()
        .map_err(|_| usage.to_string())?;
    if n == 0 {
        return Err("the window must be at least one day".to_string());
    }
    let days = n
        .checked_mul(per_unit)
        .filter(|d| *d <= 100 * 365)
        .ok_or("the window must be at most 100 years")?;
    Ok(Span {
        days,
        label: format!("{}{}", n, unit.to_ascii_lowercase()),
    })
}

/// What makes a file hot.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, ValueEnum)]
pub enum Metric {
    /// Number of commits
    #[default]
    Commits,
    /// Commits weighted by age: a commit's weight halves every 30 days
    Recency,
    /// Lines added + deleted
    Churn,
    /// Lines changed × file size: big files that keep changing
    Risk,
}

/// Read the change history of `dir` from git.
///
/// Fails when `dir` is not a directory in a git work tree, when git is
/// missing, or when the repository has no commits yet.
pub fn collect(dir: &Path, span: &Span) -> Result<HeatMap, String> {
    let (log, shallow) = git::read_log(dir, span.days)?;
    Ok(HeatMap::new(span.clone(), log, shallow, now()))
}

/// Whether a file's changes are bookkeeping (lockfiles, changelogs) rather
/// than editing.
pub fn is_noise(path: &Path) -> bool {
    let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
        return false;
    };
    if NOISE_FILE_NAMES.contains(&name) {
        return true;
    }
    let stem = path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or_default()
        .to_ascii_lowercase();
    NOISE_STEMS.contains(&stem.as_str())
}

/// Human-friendly age of a commit: `today`, `12d ago`, `3mo ago`, `2y ago`.
pub fn format_age(commit_time: i64, now: i64) -> String {
    let days = (now - commit_time).max(0) / 86_400;
    match days {
        0 => "today".to_string(),
        1..=29 => format!("{}d ago", days),
        30..=364 => format!("{}mo ago", days / 30),
        _ => format!("{}y ago", days / 365),
    }
}

/// Current time in Unix seconds.
pub fn now() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_span_units() {
        assert_eq!(parse_span("90d").unwrap().days, 90);
        assert_eq!(parse_span("2w").unwrap().days, 14);
        assert_eq!(parse_span("6m").unwrap().days, 180);
        assert_eq!(parse_span("1y").unwrap().days, 365);
        assert_eq!(parse_span("3M").unwrap().label, "3m");
        assert_eq!(parse_span(" 30d ").unwrap().label, "30d");
    }

    #[test]
    fn parse_span_rejects_bad_input() {
        for bad in [
            "", "d", "90", "abc", "0d", "-3d", "1.5m", "90x", "101y", "日",
        ] {
            assert!(parse_span(bad).is_err(), "{:?} should be rejected", bad);
        }
    }

    #[test]
    fn noise_detection() {
        assert!(is_noise(Path::new("Cargo.lock")));
        assert!(is_noise(Path::new("a/b/yarn.lock")));
        assert!(is_noise(Path::new("CHANGELOG.md")));
        assert!(is_noise(Path::new("docs/changes.rst")));
        assert!(!is_noise(Path::new("src/changelog_parser.rs")));
        assert!(!is_noise(Path::new("Cargo.toml")));
    }

    #[test]
    fn age_formatting() {
        let day = 86_400;
        let now = 1_000 * day;
        assert_eq!(format_age(now - 3_600, now), "today");
        assert_eq!(format_age(now - 2 * day, now), "2d ago");
        assert_eq!(format_age(now - 95 * day, now), "3mo ago");
        assert_eq!(format_age(now - 800 * day, now), "2y ago");
        assert_eq!(format_age(now + day, now), "today");
    }
}