gitai/core/
commit_cache.rs

1use anyhow::Result;
2use serde::{Deserialize, Serialize};
3use std::collections::HashMap;
4use std::fs;
5use std::path::PathBuf;
6
7/// Represents a cached commit message with metadata
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct CachedCommitMessage {
10    pub message: String,
11    pub timestamp: String,
12    pub hash: String,
13}
14
15/// Cache for commit messages organized by author and repository
16#[derive(Debug, Serialize, Deserialize)]
17pub struct CommitMessageCache {
18    /// Maps `"author_email:repo_path"` -> list of commit messages
19    cache: HashMap<String, Vec<CachedCommitMessage>>,
20    cache_dir: PathBuf,
21}
22
23impl CommitMessageCache {
24    /// Create a new cache instance
25    pub fn new() -> Result<Self> {
26        let cache_dir = Self::get_cache_dir()?;
27        fs::create_dir_all(&cache_dir)?;
28
29        let cache_file = cache_dir.join("commit_messages.json");
30        let cache = if cache_file.exists() {
31            let content = fs::read_to_string(&cache_file)?;
32            serde_json::from_str(&content).unwrap_or_default()
33        } else {
34            HashMap::new()
35        };
36
37        Ok(Self { cache, cache_dir })
38    }
39
40    /// Get the cache directory path
41    fn get_cache_dir() -> Result<PathBuf> {
42        let mut cache_dir = dirs::cache_dir()
43            .ok_or_else(|| anyhow::anyhow!("Could not determine cache directory"))?;
44        cache_dir.push("gitsw");
45        cache_dir.push("commit_cache");
46        Ok(cache_dir)
47    }
48
49    /// Get commit messages for a specific author and repository
50    pub fn get_commit_messages(
51        &self,
52        author_email: &str,
53        repo_path: &str,
54    ) -> Vec<CachedCommitMessage> {
55        let key = format!("{author_email}:{repo_path}");
56        self.cache.get(&key).cloned().unwrap_or_default()
57    }
58
59    /// Add commit messages for a specific author and repository
60    pub fn add_commit_messages(
61        &mut self,
62        author_email: &str,
63        repo_path: &str,
64        messages: Vec<CachedCommitMessage>,
65    ) {
66        const MAX_MESSAGES_PER_AUTHOR_REPO: usize = 1000;
67
68        let key = format!("{author_email}:{repo_path}");
69        let existing = self.cache.entry(key).or_default();
70        existing.extend(messages);
71
72        // Keep only the most recent messages (limit to prevent unbounded growth)
73        if existing.len() > MAX_MESSAGES_PER_AUTHOR_REPO {
74            // Sort by timestamp (most recent first) and keep only the latest
75            existing.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
76            existing.truncate(MAX_MESSAGES_PER_AUTHOR_REPO);
77        }
78    }
79
80    /// Save the cache to disk
81    pub fn save(&self) -> Result<()> {
82        let cache_file = self.cache_dir.join("commit_messages.json");
83        let content = serde_json::to_string_pretty(&self.cache)?;
84        fs::write(cache_file, content)?;
85        Ok(())
86    }
87
88    /// Get all cached authors for a repository
89    pub fn get_authors_for_repo(&self, repo_path: &str) -> Vec<String> {
90        self.cache
91            .keys()
92            .filter(|key| key.split(':').nth(1) == Some(repo_path))
93            .map(|key| key.split(':').next().unwrap_or("").to_string())
94            .collect()
95    }
96
97    /// Clear cache for a specific repository
98    pub fn clear_repo_cache(&mut self, repo_path: &str) {
99        self.cache
100            .retain(|key, _| key.split(':').nth(1) != Some(repo_path));
101    }
102
103    /// Get cache statistics
104    pub fn get_stats(&self) -> CacheStats {
105        let total_messages = self.cache.values().map(Vec::len).sum();
106        let total_authors = self.cache.len();
107        let repos: std::collections::HashSet<_> = self
108            .cache
109            .keys()
110            .map(|key| key.split(':').nth(1).unwrap_or(""))
111            .collect();
112        let total_repos = repos.len();
113
114        CacheStats {
115            total_messages,
116            total_authors,
117            total_repos,
118        }
119    }
120}
121
122/// Statistics about the cache
123#[derive(Debug)]
124pub struct CacheStats {
125    pub total_messages: usize,
126    pub total_authors: usize,
127    pub total_repos: usize,
128}