gitai/features/commit/
service.rs

1use super::prompt::{create_system_prompt, create_user_prompt};
2use super::types::GeneratedMessage;
3use crate::config::Config;
4use crate::core::context::CommitContext;
5use crate::core::llm;
6use crate::core::token_optimizer::TokenOptimizer;
7use crate::git::{CommitResult, GitRepo};
8
9use anyhow::Result;
10use log::debug;
11use std::path::Path;
12use std::sync::Arc;
13use tokio::sync::{RwLock, mpsc};
14
15/// Service for handling Git commit operations with AI assistance
16pub struct CommitService {
17    config: Config,
18    repo: Arc<GitRepo>,
19    provider_name: String,
20    verify: bool,
21    cached_context: Arc<RwLock<Option<CommitContext>>>,
22}
23
24impl CommitService {
25    /// Create a new `CommitService` instance
26    ///
27    /// # Arguments
28    ///
29    /// * `config` - The configuration for the service
30    /// * `repo_path` - The path to the Git repository (unused but kept for API compatibility)
31    /// * `provider_name` - The name of the LLM provider to use
32    /// * `verify` - Whether to verify commits
33    /// * `git_repo` - An existing `GitRepo` instance
34    ///
35    /// # Returns
36    ///
37    /// A Result containing the new `CommitService` instance or an error
38    pub fn new(
39        config: Config,
40        _repo_path: &Path,
41        provider_name: &str,
42        verify: bool,
43        git_repo: GitRepo,
44    ) -> Result<Self> {
45        Ok(Self {
46            config,
47            repo: Arc::new(git_repo),
48            provider_name: provider_name.to_string(),
49            verify,
50            cached_context: Arc::new(RwLock::new(None)),
51        })
52    }
53
54    /// Check if the repository is remote
55    pub fn is_remote_repository(&self) -> bool {
56        self.repo.is_remote()
57    }
58
59    /// Check the environment for necessary prerequisites
60    pub fn check_environment(&self) -> Result<()> {
61        self.config.check_environment()
62    }
63
64    /// Get Git information for the current repository
65    pub async fn get_git_info(&self) -> Result<CommitContext> {
66        {
67            let cached_context = self.cached_context.read().await;
68            if let Some(context) = &*cached_context {
69                return Ok(context.clone());
70            }
71        }
72
73        let context = self.repo.get_git_info(&self.config).await?;
74
75        {
76            let mut cached_context = self.cached_context.write().await;
77            *cached_context = Some(context.clone());
78        }
79        Ok(context)
80    }
81
82    /// Get Git information including unstaged changes
83    pub async fn get_git_info_with_unstaged(
84        &self,
85        include_unstaged: bool,
86    ) -> Result<CommitContext> {
87        if !include_unstaged {
88            return self.get_git_info().await;
89        }
90
91        {
92            // Only use cached context if we're not including unstaged changes
93            // because unstaged changes might have changed since we last checked
94            let cached_context = self.cached_context.read().await;
95            if let Some(context) = &*cached_context
96                && !include_unstaged
97            {
98                return Ok(context.clone());
99            }
100        }
101
102        let context = self
103            .repo
104            .get_git_info_with_unstaged(&self.config, include_unstaged)
105            .await?;
106
107        // Don't cache the context with unstaged changes since they can be constantly changing
108        if !include_unstaged {
109            let mut cached_context = self.cached_context.write().await;
110            *cached_context = Some(context.clone());
111        }
112
113        Ok(context)
114    }
115
116    /// Get Git information for a specific commit
117    #[allow(clippy::unused_async)]
118    pub async fn get_git_info_for_commit(&self, commit_id: &str) -> Result<CommitContext> {
119        debug!("Getting git info for commit: {}", commit_id);
120
121        let context = self.repo.get_git_info_for_commit(&self.config, commit_id)?;
122
123        // We don't cache commit-specific contexts
124        Ok(context)
125    }
126
127    /// Private helper method to handle common token optimization logic
128    ///
129    /// # Arguments
130    ///
131    /// * `config_clone` - Configuration with preset and instructions
132    /// * `system_prompt` - The system prompt to use
133    /// * `context` - The commit context
134    /// * `create_user_prompt_fn` - A function that creates a user prompt from a context
135    ///
136    /// # Returns
137    ///
138    /// A tuple containing the optimized context and final user prompt
139    async fn optimize_prompt<F>(
140        &self,
141        config_clone: &Config,
142        system_prompt: &str,
143        mut context: CommitContext,
144        create_user_prompt_fn: F,
145    ) -> (CommitContext, String)
146    where
147        F: Fn(&CommitContext) -> String,
148    {
149        // Get the token limit for the provider from config or default value
150        let token_limit = config_clone
151            .providers
152            .get(&self.provider_name)
153            .and_then(|p| p.token_limit)
154            .unwrap_or({
155                match self.provider_name.as_str() {
156                    "openai" => 16_000,
157                    "anthropic" => 100_000,
158                    "groq" | "openrouter" => 32_000,
159                    "google" => 1_000_000,
160                    _ => 8_000,
161                }
162            });
163
164        // Create a token optimizer to count tokens
165        let optimizer = TokenOptimizer::for_counting().expect("Failed to create TokenOptimizer");
166        let system_tokens = optimizer.count_tokens(system_prompt);
167
168        debug!("Token limit: {}", token_limit);
169        debug!("System prompt tokens: {}", system_tokens);
170
171        // Reserve tokens for system prompt and some buffer for formatting
172        // 1000 token buffer provides headroom for model responses and formatting
173        let context_token_limit = token_limit.saturating_sub(system_tokens + 1000);
174        debug!("Available tokens for context: {}", context_token_limit);
175
176        // Count tokens before optimization
177        let user_prompt_before = create_user_prompt_fn(&context);
178        let total_tokens_before = system_tokens + optimizer.count_tokens(&user_prompt_before);
179        debug!("Total tokens before optimization: {}", total_tokens_before);
180
181        // Optimize the context with remaining token budget
182        context.optimize(context_token_limit, config_clone).await;
183
184        let user_prompt = create_user_prompt_fn(&context);
185        let user_tokens = optimizer.count_tokens(&user_prompt);
186        let total_tokens = system_tokens + user_tokens;
187
188        debug!("User prompt tokens after optimization: {}", user_tokens);
189        debug!("Total tokens after optimization: {}", total_tokens);
190
191        // If we're still over the limit, truncate the user prompt directly
192        // 100 token safety buffer ensures we stay under the limit
193        let final_user_prompt = if total_tokens > token_limit {
194            debug!(
195                "Total tokens {} still exceeds limit {}, truncating user prompt",
196                total_tokens, token_limit
197            );
198            let max_user_tokens = token_limit.saturating_sub(system_tokens + 100);
199            optimizer
200                .truncate_string(&user_prompt, max_user_tokens)
201                .expect("Failed to truncate user prompt")
202        } else {
203            user_prompt
204        };
205
206        let final_tokens = system_tokens + optimizer.count_tokens(&final_user_prompt);
207        debug!(
208            "Final total tokens after potential truncation: {}",
209            final_tokens
210        );
211
212        (context, final_user_prompt)
213    }
214
215    /// Generate a commit message using AI
216    ///
217    /// # Arguments
218    ///
219    /// * `preset` - The instruction preset to use
220    /// * `instructions` - Custom instructions for the AI
221    ///
222    /// # Returns
223    ///
224    /// A Result containing the generated commit message or an error
225    pub async fn generate_message(&self, instructions: &str) -> anyhow::Result<GeneratedMessage> {
226        let mut config_clone = self.config.clone();
227
228        config_clone.instructions = instructions.to_string();
229
230        let context = self.get_git_info().await?;
231
232        // Create system prompt
233        let system_prompt = create_system_prompt(&config_clone)?;
234
235        // Use the shared optimization logic
236        let (_, final_user_prompt) = self
237            .optimize_prompt(&config_clone, &system_prompt, context, create_user_prompt)
238            .await;
239
240        let generated_message = llm::get_message::<GeneratedMessage>(
241            &config_clone,
242            &self.provider_name,
243            &system_prompt,
244            &final_user_prompt,
245        )
246        .await?;
247
248        Ok(generated_message)
249    }
250
251    /// Generate a PR description for a commit range
252    ///
253    /// # Arguments
254    ///
255    /// * `preset` - The instruction preset to use
256    /// * `instructions` - Custom instructions for the AI
257    /// * `from` - The starting Git reference (exclusive)
258    /// * `to` - The ending Git reference (inclusive)
259    ///
260    /// # Returns
261    ///
262    /// A Result containing the generated PR description or an error
263    pub async fn generate_pr_for_commit_range(
264        &self,
265        instructions: &str,
266        from: &str,
267        to: &str,
268    ) -> anyhow::Result<super::types::GeneratedPullRequest> {
269        let mut config_clone = self.config.clone();
270
271        config_clone.instructions = instructions.to_string();
272
273        // Get context for the commit range
274        let context = self
275            .repo
276            .get_git_info_for_commit_range(&self.config, from, to)?;
277
278        // Get commit messages for the PR
279        let commit_messages = self.repo.get_commits_for_pr(from, to)?;
280
281        // Create system prompt
282        let system_prompt = super::prompt::create_pr_system_prompt(&config_clone)?;
283
284        // Use the shared optimization logic
285        let (_, final_user_prompt) = self
286            .optimize_prompt(&config_clone, &system_prompt, context, |ctx| {
287                super::prompt::create_pr_user_prompt(ctx, &commit_messages)
288            })
289            .await;
290
291        let generated_pr = llm::get_message::<super::types::GeneratedPullRequest>(
292            &config_clone,
293            &self.provider_name,
294            &system_prompt,
295            &final_user_prompt,
296        )
297        .await?;
298
299        Ok(generated_pr)
300    }
301
302    /// Generate a PR description for branch comparison
303    ///
304    /// # Arguments
305    ///
306    /// * `preset` - The instruction preset to use
307    /// * `instructions` - Custom instructions for the AI
308    /// * `base_branch` - The base branch (e.g., "main")
309    /// * `target_branch` - The target branch (e.g., "feature-branch")
310    ///
311    /// # Returns
312    ///
313    /// A Result containing the generated PR description or an error
314    pub async fn generate_pr_for_branch_diff(
315        &self,
316        instructions: &str,
317        base_branch: &str,
318        target_branch: &str,
319    ) -> anyhow::Result<super::types::GeneratedPullRequest> {
320        let mut config_clone = self.config.clone();
321
322        config_clone.instructions = instructions.to_string();
323
324        // Get context for the branch comparison
325        let context =
326            self.repo
327                .get_git_info_for_branch_diff(&self.config, base_branch, target_branch)?;
328
329        // Get commit messages for the PR (commits in target_branch not in base_branch)
330        let commit_messages = self.repo.get_commits_for_pr(base_branch, target_branch)?;
331
332        // Create system prompt
333        let system_prompt = super::prompt::create_pr_system_prompt(&config_clone)?;
334
335        // Use the shared optimization logic
336        let (_, final_user_prompt) = self
337            .optimize_prompt(&config_clone, &system_prompt, context, |ctx| {
338                super::prompt::create_pr_user_prompt(ctx, &commit_messages)
339            })
340            .await;
341
342        let generated_pr = llm::get_message::<super::types::GeneratedPullRequest>(
343            &config_clone,
344            &self.provider_name,
345            &system_prompt,
346            &final_user_prompt,
347        )
348        .await?;
349
350        Ok(generated_pr)
351    }
352
353    /// Performs a commit with the given message.
354    ///
355    /// # Arguments
356    ///
357    /// * `message` - The commit message.
358    ///
359    /// # Returns
360    ///
361    /// A Result containing the `CommitResult` or an error.
362    pub fn perform_commit(
363        &self,
364        message: &str,
365        amend: bool,
366        commit_ref: Option<&str>,
367    ) -> Result<CommitResult> {
368        // Check if this is a remote repository
369        if self.is_remote_repository() {
370            return Err(anyhow::anyhow!("Cannot commit to a remote repository"));
371        }
372
373        debug!(
374            "Performing commit with message: {}, amend: {}, commit_ref: {:?}",
375            message, amend, commit_ref
376        );
377
378        if !self.verify {
379            debug!("Skipping pre-commit hook (verify=false)");
380            if amend {
381                return self
382                    .repo
383                    .amend_commit(message, commit_ref.unwrap_or("HEAD"));
384            }
385            return self.repo.commit(message);
386        }
387
388        // Execute pre-commit hook
389        debug!("Executing pre-commit hook");
390        if let Err(e) = self.repo.execute_hook("pre-commit") {
391            debug!("Pre-commit hook failed: {}", e);
392            return Err(e);
393        }
394        debug!("Pre-commit hook executed successfully");
395
396        // Perform the commit
397        let commit_result = if amend {
398            self.repo
399                .amend_commit(message, commit_ref.unwrap_or("HEAD"))
400        } else {
401            self.repo.commit(message)
402        };
403
404        match commit_result {
405            Ok(result) => {
406                // Execute post-commit hook
407                debug!("Executing post-commit hook");
408                if let Err(e) = self.repo.execute_hook("post-commit") {
409                    debug!("Post-commit hook failed: {}", e);
410                    // We don't fail the commit if post-commit hook fails
411                }
412                debug!("Commit performed successfully");
413                Ok(result)
414            }
415            Err(e) => {
416                debug!("Commit failed: {}", e);
417                Err(e)
418            }
419        }
420    }
421
422    /// Execute the pre-commit hook if verification is enabled
423    pub fn pre_commit(&self) -> Result<()> {
424        // Skip pre-commit hook for remote repositories
425        if self.is_remote_repository() {
426            debug!("Skipping pre-commit hook for remote repository");
427            return Ok(());
428        }
429
430        if self.verify {
431            self.repo.execute_hook("pre-commit")
432        } else {
433            Ok(())
434        }
435    }
436
437    /// Create a channel for message generation
438    pub fn create_message_channel(
439        &self,
440    ) -> (
441        mpsc::Sender<Result<GeneratedMessage>>,
442        mpsc::Receiver<Result<GeneratedMessage>>,
443    ) {
444        mpsc::channel(1)
445    }
446}