tree2md 0.14.0

Like the tree command, but outputs in Markdown. Optimized for AI agents.
//! Ranking hot spots and applying them to the tree.

use super::heat::{FileHeat, HeatMap};
use super::Metric;
use crate::cli::LocMode;
use crate::fs_tree::{LocCounter, Node};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

/// A file or directory in the ranking.
#[derive(Debug, Clone)]
pub struct Ranked {
    pub path: PathBuf,
    pub heat: FileHeat,
    /// Line count, for the risk metric (files only).
    pub loc: Option<usize>,
    pub score: f64,
}

/// The hot spots of a tree: its change history ranked by a metric.
#[derive(Debug)]
pub struct HotSpots {
    pub map: HeatMap,
    pub metric: Metric,
    /// Every changed file, hottest first.
    pub files: Vec<Ranked>,
    /// How many files the ranking lists and the tree marks.
    pub limit: usize,
    file_scores: HashMap<PathBuf, f64>,
    dir_scores: HashMap<PathBuf, f64>,
    marked_files: HashSet<PathBuf>,
    marked_dirs: HashSet<PathBuf>,
}

impl HotSpots {
    /// Rank the history in `map`. `root` is the target directory the paths
    /// are relative to, for counting lines under the risk metric.
    pub fn new(map: HeatMap, metric: Metric, limit: usize, root: &Path) -> Self {
        let lines = LocCounter::new(LocMode::Fast);
        let files = rank(map.files(), |path, heat| {
            let loc = (metric == Metric::Risk)
                .then(|| lines.count_lines(&root.join(path)))
                .flatten();
            (loc, score(metric, heat, loc))
        });
        // Directories have no size of their own: risk ranks them by churn.
        let dir_metric = match metric {
            Metric::Risk => Metric::Churn,
            m => m,
        };
        let dirs = rank(map.dirs(), |_, heat| (None, score(dir_metric, heat, None)));

        Self {
            file_scores: scores(&files),
            dir_scores: scores(&dirs),
            marked_files: top_paths(&files, limit),
            marked_dirs: top_paths(&dirs, limit),
            map,
            metric,
            files,
            limit,
        }
    }

    /// The files the ranking lists, hottest first.
    pub fn top(&self) -> &[Ranked] {
        &self.files[..self.files.len().min(self.limit)]
    }

    /// Whether the file at `rel_path` is in the ranking.
    pub fn is_marked_file(&self, rel_path: &Path) -> bool {
        self.marked_files.contains(rel_path)
    }

    /// Whether the directory at `rel_path` is among the `limit` hottest.
    pub fn is_marked_dir(&self, rel_path: &Path) -> bool {
        self.marked_dirs.contains(rel_path)
    }

    /// Prune `tree` to the ranked files and the directories leading to them.
    pub fn keep_top(&self, tree: &mut Node) {
        retain_files(tree, &|path| self.marked_files.contains(path));
    }

    /// Order each directory's children hottest first: directories before
    /// files as usual, unchanged entries last, ties by name.
    pub fn sort_tree(&self, node: &mut Node) {
        let key = |n: &Node| {
            let scores = if n.is_dir {
                &self.dir_scores
            } else {
                &self.file_scores
            };
            scores
                .get(&n.display_path)
                .copied()
                .unwrap_or(f64::NEG_INFINITY)
        };
        node.children.sort_by(|a, b| {
            b.is_dir
                .cmp(&a.is_dir)
                .then_with(|| key(b).total_cmp(&key(a)))
                .then_with(|| a.name.cmp(&b.name))
        });
        for child in node.children.iter_mut().filter(|c| c.is_dir) {
            self.sort_tree(child);
        }
    }
}

fn score(metric: Metric, heat: &FileHeat, loc: Option<usize>) -> f64 {
    match metric {
        Metric::Commits => heat.commits as f64,
        Metric::Recency => heat.recency,
        Metric::Churn => heat.churn() as f64,
        Metric::Risk => heat.churn() as f64 * loc.unwrap_or(0) as f64,
    }
}

/// Sort entries hottest first: score, then commits, then lines changed, then path.
fn rank<'a>(
    entries: impl Iterator<Item = (&'a PathBuf, &'a FileHeat)>,
    measure: impl Fn(&Path, &FileHeat) -> (Option<usize>, f64),
) -> Vec<Ranked> {
    let mut ranked: Vec<Ranked> = entries
        .map(|(path, heat)| {
            let (loc, score) = measure(path, heat);
            Ranked {
                path: path.clone(),
                heat: *heat,
                loc,
                score,
            }
        })
        .collect();
    ranked.sort_by(|a, b| {
        b.score
            .total_cmp(&a.score)
            .then_with(|| b.heat.commits.cmp(&a.heat.commits))
            .then_with(|| b.heat.churn().cmp(&a.heat.churn()))
            .then_with(|| a.path.cmp(&b.path))
    });
    ranked
}

fn scores(ranked: &[Ranked]) -> HashMap<PathBuf, f64> {
    ranked.iter().map(|r| (r.path.clone(), r.score)).collect()
}

fn top_paths(ranked: &[Ranked], limit: usize) -> HashSet<PathBuf> {
    ranked.iter().take(limit).map(|r| r.path.clone()).collect()
}

/// Display paths of every file in `tree`.
pub fn visible_files(tree: &Node) -> HashSet<PathBuf> {
    fn walk(node: &Node, out: &mut HashSet<PathBuf>) {
        for child in &node.children {
            if child.is_dir {
                walk(child, out);
            } else {
                out.insert(child.display_path.clone());
            }
        }
    }
    let mut out = HashSet::new();
    walk(tree, &mut out);
    out
}

/// Keep the files `keep` accepts; drop directories left without any.
fn retain_files(node: &mut Node, keep: &dyn Fn(&Path) -> bool) {
    node.children.retain_mut(|child| {
        if child.is_dir {
            retain_files(child, keep);
            !child.children.is_empty()
        } else {
            keep(&child.display_path)
        }
    });
}

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

    fn hot(commits: &[(i64, &[&str])], metric: Metric, limit: usize) -> HotSpots {
        let map = HeatMap::new(Span::default(), parse_log(&log_bytes(commits)), false, 10);
        HotSpots::new(map, metric, limit, Path::new("/nonexistent"))
    }

    fn paths(ranked: &[Ranked]) -> Vec<&str> {
        ranked.iter().map(|r| r.path.to_str().unwrap()).collect()
    }

    const LOG: &[(i64, &[&str])] = &[
        (10, &["1\t0\tsrc/often.rs"]),
        (9, &["1\t0\tsrc/often.rs"]),
        (8, &["1\t0\tsrc/often.rs"]),
        (2, &["400\t100\tsrc/big.rs"]),
        (1, &["1\t0\tdocs/a.md"]),
    ];

    #[test]
    fn ranks_by_metric() {
        let by_commits = hot(LOG, Metric::Commits, 10);
        assert_eq!(
            paths(&by_commits.files),
            ["src/often.rs", "src/big.rs", "docs/a.md"]
        );

        let by_churn = hot(LOG, Metric::Churn, 10);
        assert_eq!(paths(&by_churn.files)[0], "src/big.rs");
    }

    #[test]
    fn limit_bounds_the_ranking_and_marks() {
        let h = hot(LOG, Metric::Commits, 1);
        assert_eq!(paths(h.top()), ["src/often.rs"]);
        assert!(h.is_marked_file(Path::new("src/often.rs")));
        assert!(!h.is_marked_file(Path::new("src/big.rs")));
        assert!(h.is_marked_dir(Path::new("src")));
        assert!(!h.is_marked_dir(Path::new("docs")));
    }

    fn node(path: &str, is_dir: bool, children: Vec<Node>) -> Node {
        let name = Path::new(path).file_name().unwrap().to_string_lossy();
        let mut n = Node::new(name.to_string(), PathBuf::from(path), is_dir)
            .with_display_path(PathBuf::from(path));
        n.children = children;
        n
    }

    fn tree() -> Node {
        node(
            "root",
            true,
            vec![
                node("docs", true, vec![node("docs/a.md", false, vec![])]),
                node(
                    "src",
                    true,
                    vec![
                        node("src/big.rs", false, vec![]),
                        node("src/cold.rs", false, vec![]),
                        node("src/often.rs", false, vec![]),
                    ],
                ),
                node("README.md", false, vec![]),
            ],
        )
    }

    fn names(node: &Node) -> Vec<&str> {
        node.children.iter().map(|c| c.name.as_str()).collect()
    }

    #[test]
    fn sort_tree_puts_hot_entries_first() {
        let h = hot(LOG, Metric::Commits, 10);
        let mut t = tree();
        h.sort_tree(&mut t);
        assert_eq!(names(&t), ["src", "docs", "README.md"]);
        assert_eq!(names(&t.children[0]), ["often.rs", "big.rs", "cold.rs"]);
    }

    #[test]
    fn keep_top_prunes_to_ranked_files() {
        let h = hot(LOG, Metric::Commits, 2);
        let mut t = tree();
        h.keep_top(&mut t);
        assert_eq!(names(&t), ["src"]);
        assert_eq!(names(&t.children[0]), ["big.rs", "often.rs"]);
    }

    #[test]
    fn visible_files_lists_every_file() {
        let files = visible_files(&tree());
        assert_eq!(files.len(), 5);
        assert!(files.contains(Path::new("src/cold.rs")));
        assert!(!files.contains(Path::new("src")));
    }
}