tree2md 0.14.0

Like the tree command, but outputs in Markdown. Optimized for AI agents.
//! Per-file and per-directory change history within the window.

use super::git::{CommitMeta, FileLog, Log};
use super::{Span, RECENCY_HALF_LIFE_DAYS};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// Change history of a file or directory within the window.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct FileHeat {
    /// Commits that touched it (for a directory: anything beneath it).
    pub commits: u32,
    /// Distinct authors of those commits.
    pub authors: u32,
    pub added: u64,
    pub deleted: u64,
    /// Committer time of the most recent commit, in Unix seconds.
    pub last_commit: i64,
    /// Commits weighted by age: each counts `0.5^(age / half-life)`.
    pub recency: f64,
}

impl FileHeat {
    pub fn churn(&self) -> u64 {
        self.added + self.deleted
    }
}

/// Change history of a target directory, keyed by paths relative to it (the
/// form of a node's `display_path`).
#[derive(Debug, Clone)]
pub struct HeatMap {
    pub span: Span,
    /// Commits left out because they touched more than `BULK_COMMIT_FILES` files.
    pub skipped_bulk: usize,
    /// The repository is a shallow clone, so older history may be missing.
    pub shallow: bool,
    now: i64,
    commits: Vec<CommitMeta>,
    logs: HashMap<PathBuf, FileLog>,
    files: HashMap<PathBuf, FileHeat>,
    dirs: HashMap<PathBuf, FileHeat>,
}

impl HeatMap {
    /// Summarize `log`; recency is measured from `now` (Unix seconds).
    pub fn new(span: Span, log: Log, shallow: bool, now: i64) -> Self {
        let mut map = Self {
            span,
            skipped_bulk: log.skipped_bulk,
            shallow,
            now,
            commits: log.commits,
            logs: log.files,
            files: HashMap::new(),
            dirs: HashMap::new(),
        };
        map.summarize();
        map
    }

    /// History of the file at `rel_path`, if it changed within the window.
    pub fn get(&self, rel_path: &Path) -> Option<FileHeat> {
        self.files.get(rel_path).copied()
    }

    /// History of everything beneath the directory at `rel_path`, if any of
    /// it changed within the window. A commit that touched several files
    /// beneath it counts once.
    pub fn get_dir(&self, rel_path: &Path) -> Option<FileHeat> {
        self.dirs.get(rel_path).copied()
    }

    pub fn files(&self) -> impl Iterator<Item = (&PathBuf, &FileHeat)> {
        self.files.iter()
    }

    pub fn dirs(&self) -> impl Iterator<Item = (&PathBuf, &FileHeat)> {
        self.dirs.iter()
    }

    /// Keep only the files `keep` accepts, and recompute directory totals
    /// from them. Used to drop files the tree's filters exclude.
    pub fn retain_files(&mut self, keep: impl Fn(&Path) -> bool) {
        self.logs.retain(|path, _| keep(path));
        self.summarize();
    }

    fn summarize(&mut self) {
        let mut dir_logs: HashMap<PathBuf, FileLog> = HashMap::new();
        for (path, log) in &self.logs {
            for dir in path.ancestors().skip(1) {
                if dir.as_os_str().is_empty() {
                    break;
                }
                let dir_log = dir_logs.entry(dir.to_path_buf()).or_default();
                dir_log.commits.extend_from_slice(&log.commits);
                dir_log.added += log.added;
                dir_log.deleted += log.deleted;
            }
        }
        for log in dir_logs.values_mut() {
            log.commits.sort_unstable();
            log.commits.dedup();
        }

        self.files = self
            .logs
            .iter()
            .map(|(path, log)| (path.clone(), self.heat_of(log)))
            .collect();
        self.dirs = dir_logs
            .iter()
            .map(|(path, log)| (path.clone(), self.heat_of(log)))
            .collect();
    }

    fn heat_of(&self, log: &FileLog) -> FileHeat {
        let mut heat = FileHeat {
            commits: log.commits.len() as u32,
            added: log.added,
            deleted: log.deleted,
            ..FileHeat::default()
        };
        let mut authors = Vec::with_capacity(log.commits.len());
        for &id in &log.commits {
            let commit = self.commits[id as usize];
            heat.last_commit = heat.last_commit.max(commit.time);
            let age_days = (self.now - commit.time).max(0) as f64 / 86_400.0;
            heat.recency += 0.5f64.powf(age_days / RECENCY_HALF_LIFE_DAYS);
            authors.push(commit.author);
        }
        authors.sort_unstable();
        authors.dedup();
        heat.authors = authors.len() as u32;
        heat
    }
}

#[cfg(test)]
mod tests {
    use super::super::git::{
        parse_log,
        tests::{log_bytes, log_bytes_by},
    };
    use super::*;

    const DAY: i64 = 86_400;

    fn map(commits: &[(i64, &[&str])], now: i64) -> HeatMap {
        HeatMap::new(Span::default(), parse_log(&log_bytes(commits)), false, now)
    }

    #[test]
    fn file_heat_sums_commits_and_lines() {
        let m = map(
            &[
                (300, &["5\t2\tsrc/a.rs", "1\t0\tsrc/b.rs"]),
                (200, &["3\t3\tsrc/a.rs"]),
            ],
            300,
        );
        let a = m.get(Path::new("src/a.rs")).unwrap();
        assert_eq!(
            (a.commits, a.added, a.deleted, a.last_commit),
            (2, 8, 5, 300)
        );
        assert!(m.get(Path::new("src/c.rs")).is_none());
    }

    #[test]
    fn directory_heat_counts_each_commit_once() {
        let m = map(
            &[
                (3, &["1\t0\tsrc/a.rs", "1\t0\tsrc/render/b.rs"]),
                (2, &["1\t0\tsrc/render/b.rs", "1\t0\tsrc/render/c.rs"]),
                (1, &["1\t0\tREADME.md"]),
            ],
            3,
        );
        let src = m.get_dir(Path::new("src")).unwrap();
        assert_eq!((src.commits, src.added, src.last_commit), (2, 4, 3));
        assert_eq!(m.get_dir(Path::new("src/render")).unwrap().commits, 2);
        // The root is not a directory entry of the tree.
        assert!(m.get_dir(Path::new("")).is_none());
        assert_eq!(m.dirs().count(), 2);
    }

    #[test]
    fn recency_halves_every_half_life() {
        let now = 1_000 * DAY;
        let half_life = RECENCY_HALF_LIFE_DAYS as i64 * DAY;
        let m = map(
            &[
                (now, &["1\t0\tnew.rs"]),
                (now - half_life, &["1\t0\told.rs"]),
                (now - 2 * half_life, &["1\t0\told.rs"]),
            ],
            now,
        );
        assert!((m.get(Path::new("new.rs")).unwrap().recency - 1.0).abs() < 1e-9);
        assert!((m.get(Path::new("old.rs")).unwrap().recency - 0.75).abs() < 1e-9);
    }

    #[test]
    fn authors_are_counted_per_file_and_directory() {
        let log = parse_log(&log_bytes_by(&[
            (3, "a@x", &["1\t0\tsrc/a.rs"]),
            (2, "b@x", &["1\t0\tsrc/a.rs", "1\t0\tsrc/b.rs"]),
            (1, "a@x", &["1\t0\tsrc/b.rs"]),
        ]));
        let m = HeatMap::new(Span::default(), log, false, 3);
        assert_eq!(m.get(Path::new("src/a.rs")).unwrap().authors, 2);
        assert_eq!(m.get(Path::new("src/b.rs")).unwrap().authors, 2);
        assert_eq!(m.get_dir(Path::new("src")).unwrap().authors, 2);

        let solo = map(&[(2, &["1\t0\tx.rs"]), (1, &["1\t0\tx.rs"])], 2);
        assert_eq!(solo.get(Path::new("x.rs")).unwrap().authors, 1);
    }

    #[test]
    fn retain_files_recomputes_directories() {
        let mut m = map(
            &[
                (2, &["1\t0\tsrc/a.rs", "1\t0\tsrc/.env"]),
                (1, &["1\t0\tsrc/.env"]),
            ],
            2,
        );
        assert_eq!(m.get_dir(Path::new("src")).unwrap().commits, 2);

        m.retain_files(|p| p != Path::new("src/.env"));
        assert!(m.get(Path::new("src/.env")).is_none());
        let src = m.get_dir(Path::new("src")).unwrap();
        assert_eq!((src.commits, src.added), (1, 1));
    }
}