Skip to main content

lean_ctx_ext/core/
git_cache.rs

1// SPDX-License-Identifier: Apache-2.0
2//! TTL-based cache for git command results.
3//!
4//! Prevents redundant git invocations within the same session by caching
5//! results with a configurable time-to-live (default 10s for status/diff, 60s for log).
6
7use std::collections::HashMap;
8use std::sync::Mutex;
9use std::time::{Duration, Instant};
10
11static CACHE: std::sync::LazyLock<Mutex<GitCache>> =
12    std::sync::LazyLock::new(|| Mutex::new(GitCache::new()));
13
14struct CacheEntry {
15    output: String,
16    inserted: Instant,
17    ttl: Duration,
18}
19
20struct GitCache {
21    entries: HashMap<String, CacheEntry>,
22}
23
24impl GitCache {
25    fn new() -> Self {
26        Self {
27            entries: HashMap::new(),
28        }
29    }
30
31    fn get(&self, key: &str) -> Option<&str> {
32        let now = Instant::now();
33        if let Some(entry) = self.entries.get(key)
34            && now.duration_since(entry.inserted) < entry.ttl
35        {
36            return Some(&entry.output);
37        }
38        None
39    }
40
41    fn prune_expired(&mut self) {
42        let now = Instant::now();
43        self.entries
44            .retain(|_, e| now.duration_since(e.inserted) < e.ttl);
45    }
46
47    fn insert(&mut self, key: String, output: String, ttl: Duration) {
48        if self.entries.len() > 100 {
49            self.prune_expired();
50            // Hard cap: if still over after expiry-pruning (>100 distinct live keys
51            // within the TTL window), evict oldest by insertion time. Dropping a live
52            // entry is safe — it just forces a git re-run on next access.
53            if self.entries.len() >= 100 {
54                let mut by_age: Vec<(String, Instant)> = self
55                    .entries
56                    .iter()
57                    .map(|(k, e)| (k.clone(), e.inserted))
58                    .collect();
59                by_age.sort_by_key(|(_, inserted)| *inserted);
60                let to_drop = self.entries.len() + 1 - 100;
61                for (k, _) in by_age.into_iter().take(to_drop) {
62                    self.entries.remove(&k);
63                }
64            }
65        }
66        self.entries.insert(
67            key,
68            CacheEntry {
69                output,
70                inserted: Instant::now(),
71                ttl,
72            },
73        );
74    }
75}
76
77/// Run a git command with TTL caching. Returns cached result if available.
78pub fn git_cached(args: &[&str], cwd: &str, ttl: Duration) -> Option<String> {
79    let key = format!("{cwd}:{}", args.join(" "));
80
81    if let Ok(cache) = CACHE.lock()
82        && let Some(cached) = cache.get(&key)
83    {
84        return Some(cached.to_string());
85    }
86
87    let output = std::process::Command::new("git")
88        .args(args)
89        .current_dir(cwd)
90        .output()
91        .ok()?;
92
93    if !output.status.success() {
94        return None;
95    }
96
97    let result = String::from_utf8_lossy(&output.stdout).to_string();
98
99    if let Ok(mut cache) = CACHE.lock() {
100        cache.insert(key, result.clone(), ttl);
101    }
102
103    Some(result)
104}
105
106/// Short-TTL (10s) for frequently-changing git data (status, diff).
107pub fn git_status_cached(cwd: &str) -> Option<String> {
108    git_cached(&["status", "--porcelain"], cwd, Duration::from_secs(10))
109}
110
111/// Short-TTL (10s) for git diff.
112pub fn git_diff_cached(args: &[&str], cwd: &str) -> Option<String> {
113    let mut full_args = vec!["diff"];
114    full_args.extend_from_slice(args);
115    git_cached(&full_args, cwd, Duration::from_secs(10))
116}
117
118/// Longer-TTL (60s) for git log (rarely changes within a session).
119pub fn git_log_cached(args: &[&str], cwd: &str) -> Option<String> {
120    let mut full_args = vec!["log"];
121    full_args.extend_from_slice(args);
122    git_cached(&full_args, cwd, Duration::from_mins(1))
123}
124
125/// Invalidate all cached entries for a given directory.
126pub fn invalidate(cwd: &str) {
127    if let Ok(mut cache) = CACHE.lock() {
128        cache.entries.retain(|k, _| !k.starts_with(cwd));
129    }
130}
131
132#[cfg(test)]
133pub mod tests {
134    use super::*;
135
136    #[test]
137    fn cache_insert_and_retrieve() {
138        let mut cache = GitCache::new();
139        cache.insert(
140            "test:key".to_string(),
141            "output".to_string(),
142            Duration::from_mins(1),
143        );
144        assert_eq!(cache.get("test:key"), Some("output"));
145    }
146
147    #[test]
148    fn cache_miss_on_unknown_key() {
149        let cache = GitCache::new();
150        assert_eq!(cache.get("unknown"), None);
151    }
152
153    #[test]
154    fn cache_evicts_when_full() {
155        let mut cache = GitCache::new();
156        for i in 0..105 {
157            cache.insert(
158                format!("key:{i}"),
159                "val".to_string(),
160                Duration::from_mins(1),
161            );
162        }
163        assert!(cache.entries.len() <= 105);
164    }
165}