gitai/core/
context.rs

1use serde::Serialize;
2use std::collections::HashMap;
3use std::fmt;
4
5use crate::Config;
6use crate::core::semantic_similarity::SemanticSimilarity;
7use crate::core::token_optimizer::TokenOptimizer;
8
9#[derive(Serialize, Debug, Clone)]
10pub struct CommitContext {
11    pub branch: String,
12    pub recent_commits: Vec<RecentCommit>,
13    pub staged_files: Vec<StagedFile>,
14    pub user_name: String,
15    pub user_email: String,
16    pub author_history: Vec<String>,
17}
18
19#[derive(Serialize, Debug, Clone)]
20pub struct RecentCommit {
21    pub hash: String,
22    pub message: String,
23    pub author: String,
24    pub timestamp: String,
25}
26
27#[derive(Serialize, Debug, Clone)]
28pub struct StagedFile {
29    pub path: String,
30    pub change_type: ChangeType,
31    pub diff: String,
32    pub content: Option<String>,
33    pub content_excluded: bool,
34}
35
36#[derive(Serialize, Debug, Clone, PartialEq, Eq)]
37pub enum ChangeType {
38    Added,
39    Modified,
40    Deleted,
41}
42
43impl fmt::Display for ChangeType {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        match self {
46            Self::Added => write!(f, "Added"),
47            Self::Modified => write!(f, "Modified"),
48            Self::Deleted => write!(f, "Deleted"),
49        }
50    }
51}
52
53/// Fixed-size buffer with const generic size parameter
54#[derive(Debug, Clone)]
55pub struct FixedSizeBuffer<T, const N: usize> {
56    data: [T; N],
57    size: usize, // Current number of elements in the buffer
58}
59
60impl<T: Clone + Default, const N: usize> FixedSizeBuffer<T, N> {
61    /// Create a new buffer with all elements initialized to default values
62    pub fn new() -> Self {
63        Self {
64            data: [(); N].map(|()| T::default()),
65            size: 0,
66        }
67    }
68
69    /// Add an element to the buffer
70    /// Returns true if the element was added, false if the buffer is full
71    pub fn push(&mut self, item: T) -> bool {
72        if self.size < N {
73            self.data[self.size] = item;
74            self.size += 1;
75            true
76        } else {
77            false // Buffer is full
78        }
79    }
80
81    /// Get an element by index
82    pub fn get(&self, index: usize) -> Option<&T> {
83        if index < self.size {
84            Some(&self.data[index])
85        } else {
86            None
87        }
88    }
89
90    /// Get the number of elements currently in the buffer
91    pub fn len(&self) -> usize {
92        self.size
93    }
94
95    /// Check if the buffer is empty
96    pub fn is_empty(&self) -> bool {
97        self.size == 0
98    }
99
100    /// Check if the buffer is full
101    pub fn is_full(&self) -> bool {
102        self.size == N
103    }
104
105    /// Get the maximum capacity of the buffer
106    pub fn capacity(&self) -> usize {
107        N
108    }
109
110    /// Clear the buffer
111    pub fn clear(&mut self) {
112        self.size = 0;
113    }
114
115    /// Iterate over the elements in the buffer
116    pub fn iter(&self) -> impl Iterator<Item = &T> {
117        self.data.iter().take(self.size)
118    }
119}
120
121impl<T: Clone + Default, const N: usize> Default for FixedSizeBuffer<T, N> {
122    fn default() -> Self {
123        Self::new()
124    }
125}
126
127impl CommitContext {
128    pub fn new(
129        branch: String,
130        recent_commits: Vec<RecentCommit>,
131        staged_files: Vec<StagedFile>,
132        user_name: String,
133        user_email: String,
134        author_history: Vec<String>,
135    ) -> Self {
136        Self {
137            branch,
138            recent_commits,
139            staged_files,
140            user_name,
141            user_email,
142            author_history,
143        }
144    }
145
146    pub async fn optimize(&mut self, max_tokens: usize, config: &Config) {
147        let optimizer = TokenOptimizer::new(max_tokens, config.clone()).expect(
148            "Failed to initialize token optimizer. Ensure the tokenizer data is available.",
149        );
150
151        let _ = optimizer.optimize_context(self).await;
152    }
153
154    /// Get semantically similar historical commits based on current changes
155    pub fn get_similar_history(&self, max_similar: usize) -> Vec<String> {
156        if self.author_history.is_empty() {
157            return Vec::new();
158        }
159
160        let similarity_calculator = SemanticSimilarity::new();
161        let change_keywords = similarity_calculator.extract_keywords(&self.staged_files);
162        let similarities =
163            similarity_calculator.calculate_similarities(&change_keywords, &self.author_history);
164
165        similarities
166            .into_iter()
167            .take(max_similar)
168            .map(|(idx, _)| self.author_history[idx].clone())
169            .collect()
170    }
171
172    /// Detect common commit message conventions from history
173    pub fn detect_conventions(&self) -> HashMap<String, usize> {
174        let mut conventions = HashMap::new();
175
176        for msg in &self.author_history {
177            if let Some(first_word) = msg.split_whitespace().next() {
178                // Check for conventional commit patterns
179                if first_word.ends_with(':') {
180                    let convention = first_word.to_lowercase();
181                    *conventions.entry(convention).or_insert(0) += 1;
182                }
183                // Check for imperative verbs
184                else if is_imperative_verb(first_word) {
185                    *conventions.entry("imperative".to_string()).or_insert(0) += 1;
186                }
187            }
188        }
189
190        conventions
191    }
192
193    /// Get enhanced author history with semantic filtering
194    pub fn get_enhanced_history(&self, max_history: usize) -> Vec<String> {
195        let similar_history = self.get_similar_history(max_history / 2);
196        let mut enhanced_history = similar_history;
197
198        // Add some recent history for recency
199        let recent_count = (max_history / 2).min(self.author_history.len());
200        for i in 0..recent_count {
201            if let Some(msg) = self.author_history.get(i)
202                && !enhanced_history.contains(msg)
203            {
204                enhanced_history.push(msg.clone());
205            }
206        }
207
208        enhanced_history.truncate(max_history);
209        enhanced_history
210    }
211}
212
213/// Check if a word is an imperative verb commonly used in commit messages
214fn is_imperative_verb(word: &str) -> bool {
215    let imperative_verbs = [
216        "add",
217        "update",
218        "fix",
219        "remove",
220        "refactor",
221        "improve",
222        "change",
223        "modify",
224        "create",
225        "delete",
226        "merge",
227        "revert",
228        "implement",
229        "optimize",
230        "clean",
231        "rename",
232        "move",
233        "extract",
234        "introduce",
235        "enhance",
236        "simplify",
237        "document",
238    ];
239
240    imperative_verbs.contains(&word.to_lowercase().as_str())
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246
247    #[test]
248    fn test_fixed_size_buffer() {
249        // Create a buffer of size 3
250        let mut buffer: FixedSizeBuffer<i32, 3> = FixedSizeBuffer::new();
251
252        // Initially empty
253        assert_eq!(buffer.len(), 0);
254        assert!(buffer.is_empty());
255        assert_eq!(buffer.capacity(), 3);
256
257        // Add elements
258        assert!(buffer.push(1)); // Should succeed
259        assert!(buffer.push(2)); // Should succeed
260        assert!(buffer.push(3)); // Should succeed
261        assert!(!buffer.push(4)); // Should fail - buffer is full
262
263        // Check length and capacity
264        assert_eq!(buffer.len(), 3);
265        assert!(!buffer.is_empty());
266        assert!(buffer.is_full());
267
268        // Check elements
269        assert_eq!(buffer.get(0), Some(&1));
270        assert_eq!(buffer.get(1), Some(&2));
271        assert_eq!(buffer.get(2), Some(&3));
272        assert_eq!(buffer.get(3), None); // Out of bounds
273
274        // Test iteration
275        let collected: Vec<&i32> = buffer.iter().collect();
276        assert_eq!(collected, vec![&1, &2, &3]);
277
278        // Clear the buffer
279        buffer.clear();
280        assert_eq!(buffer.len(), 0);
281        assert!(buffer.is_empty());
282        assert_eq!(buffer.get(0), None);
283    }
284
285    #[test]
286    fn test_const_generic_different_sizes() {
287        let buffer_5: FixedSizeBuffer<u8, 5> = FixedSizeBuffer::new();
288        let buffer_10: FixedSizeBuffer<u8, 10> = FixedSizeBuffer::new();
289
290        assert_eq!(buffer_5.capacity(), 5);
291        assert_eq!(buffer_10.capacity(), 10);
292    }
293}