Skip to main content

lean_ctx/tools/
ctx_heatmap.rs

1use crate::core::gain::GainEngine;
2use crate::core::heatmap;
3
4pub fn handle(action: &str, _path: Option<&str>) -> String {
5    let engine = GainEngine::load();
6
7    match action {
8        "directory" | "dirs" => heatmap::format_directory_summary(&engine.heatmap),
9        "cold" => {
10            let all = collect_project_files(_path);
11            let cold = engine.heatmap.cold_files(&all, 20);
12            if cold.is_empty() {
13                "No cold files found (all files have been accessed).".to_string()
14            } else {
15                let mut lines = vec![format!(
16                    "Cold files (never accessed, {} total):",
17                    cold.len()
18                )];
19                for f in &cold {
20                    lines.push(format!("  {f}"));
21                }
22                lines.join("\n")
23            }
24        }
25        "json" => {
26            serde_json::to_string_pretty(&engine.heatmap).unwrap_or_else(|_| "{}".to_string())
27        }
28        _ => heatmap::format_heatmap_status(&engine.heatmap, 20),
29    }
30}
31
32fn collect_project_files(path: Option<&str>) -> Vec<String> {
33    let root = path.unwrap_or(".");
34    let mut files = Vec::new();
35    let walker = walkdir::WalkDir::new(root)
36        .max_depth(5)
37        .into_iter()
38        .filter_entry(|e| {
39            let name = e.file_name().to_string_lossy();
40            !name.starts_with('.')
41                && name != "node_modules"
42                && name != "target"
43                && name != "dist"
44                && name != "__pycache__"
45                && name != ".git"
46        });
47    for entry in walker.flatten() {
48        if entry.file_type().is_file()
49            && let Some(ext) = entry.path().extension().and_then(|e| e.to_str())
50            && is_source_ext(ext)
51        {
52            files.push(entry.path().to_string_lossy().to_string());
53        }
54    }
55    files
56}
57
58fn is_source_ext(ext: &str) -> bool {
59    matches!(
60        ext,
61        "rs" | "ts"
62            | "tsx"
63            | "js"
64            | "jsx"
65            | "py"
66            | "go"
67            | "java"
68            | "c"
69            | "cpp"
70            | "h"
71            | "rb"
72            | "cs"
73            | "kt"
74            | "swift"
75            | "php"
76            | "svelte"
77            | "vue"
78    )
79}