gitai/git/
repository.rs

1use crate::config::Config;
2use crate::core::commit_cache::{CachedCommitMessage, CommitMessageCache};
3use crate::core::context::{CommitContext, RecentCommit, StagedFile};
4
5use crate::git::commit::{self, CommitResult};
6use crate::git::files::{RepoFilesInfo, get_file_statuses, get_unstaged_file_statuses};
7use crate::git::utils::is_inside_work_tree;
8use anyhow::{Context as AnyhowContext, Result, anyhow};
9use git2::{Repository, Tree};
10use std::collections::HashSet;
11use std::env;
12use std::path::{Path, PathBuf};
13use std::process::{Command, Stdio};
14
15use log::debug;
16use tempfile::TempDir;
17use url::Url;
18
19use super::ignore_matcher::GitIgnoreMatcher;
20
21/// Represents a Git repository and provides methods for interacting with it.
22pub struct GitRepo {
23    repo_path: PathBuf,
24    /// Optional temporary directory for cloned repositories
25    #[allow(dead_code)] // This field is needed to maintain ownership of temp directories
26    temp_dir: Option<TempDir>,
27    /// Whether this is a remote repository
28    is_remote: bool,
29    /// Original remote URL if this is a cloned repository
30    remote_url: Option<String>,
31    /// `GitIgnore` matcher for file exclusion
32    gitignore_matcher: GitIgnoreMatcher,
33}
34
35impl GitRepo {
36    /// Creates a new `GitRepo` instance from a local path.
37    ///
38    /// # Arguments
39    ///
40    /// * `repo_path` - The path to the Git repository.
41    ///
42    /// # Returns
43    ///
44    /// A Result containing the `GitRepo` instance or an error.
45    pub fn new(repo_path: &Path) -> Result<Self> {
46        Ok(Self {
47            repo_path: repo_path.to_path_buf(),
48            temp_dir: None,
49            is_remote: false,
50            remote_url: None,
51            gitignore_matcher: GitIgnoreMatcher::new(repo_path),
52        })
53    }
54
55    /// Creates a new `GitRepo` instance, handling both local and remote repositories.
56    ///
57    /// # Arguments
58    ///
59    /// * `repository_url` - Optional URL for a remote repository.
60    ///
61    /// # Returns
62    ///
63    /// A Result containing the `GitRepo` instance or an error.
64    pub fn new_from_url(repository_url: Option<String>) -> Result<Self> {
65        if let Some(url) = repository_url {
66            Self::clone_remote_repository(&url)
67        } else {
68            let current_dir = env::current_dir()?;
69            Self::new(&current_dir)
70        }
71    }
72
73    /// Clones a remote repository and creates a `GitRepo` instance for it.
74    ///
75    /// # Arguments
76    ///
77    /// * `url` - The URL of the remote repository to clone.
78    ///
79    /// # Returns
80    ///
81    /// A Result containing the `GitRepo` instance or an error.
82    pub fn clone_remote_repository(url: &str) -> Result<Self> {
83        debug!("Cloning remote repository from URL: {url}");
84
85        // Validate URL
86        let _ = Url::parse(url).map_err(|e| anyhow!("Invalid repository URL: {e}"))?;
87
88        // Create a temporary directory for the clone
89        let temp_dir = TempDir::new()?;
90        let temp_path_buf = temp_dir.path().to_path_buf();
91
92        debug!(
93            "Created temporary directory for clone: {}",
94            temp_path_buf.display()
95        );
96
97        // Clone the repository into the temporary directory
98        let repo = match Repository::clone(url, &temp_path_buf) {
99            Ok(repo) => repo,
100            Err(e) => return Err(anyhow!("Failed to clone repository: {e}")),
101        };
102
103        debug!(
104            "Successfully cloned repository to {}",
105            repo.path().display()
106        );
107
108        Ok(Self {
109            repo_path: temp_path_buf.clone(),
110            temp_dir: Some(temp_dir),
111            is_remote: true,
112            remote_url: Some(url.to_string()),
113            gitignore_matcher: GitIgnoreMatcher::new(&temp_path_buf),
114        })
115    }
116
117    /// Open the repository at the stored path
118    pub fn open_repo(&self) -> Result<Repository, git2::Error> {
119        Repository::open(&self.repo_path)
120    }
121
122    /// Returns whether this `GitRepo` instance is working with a remote repository
123    pub fn is_remote(&self) -> bool {
124        self.is_remote
125    }
126
127    /// Returns the original remote URL if this is a cloned repository
128    pub fn get_remote_url(&self) -> Option<&str> {
129        self.remote_url.as_deref()
130    }
131
132    /// Returns the repository path
133    pub fn repo_path(&self) -> &PathBuf {
134        &self.repo_path
135    }
136
137    /// Updates the remote repository by fetching the latest changes
138    pub fn update_remote(&self) -> Result<()> {
139        if !self.is_remote {
140            return Err(anyhow!("Not a remote repository"));
141        }
142
143        debug!("Updating remote repository");
144        let repo = self.open_repo()?;
145
146        // Find the default remote (usually "origin")
147        let remotes = repo.remotes()?;
148        let remote_name = remotes
149            .iter()
150            .flatten()
151            .next()
152            .ok_or_else(|| anyhow!("No remote found"))?;
153
154        // Fetch updates from the remote
155        let mut remote = repo.find_remote(remote_name)?;
156        remote.fetch(&["master", "main"], None, None)?;
157
158        debug!("Successfully updated remote repository");
159        Ok(())
160    }
161
162    /// Retrieves the current branch name.
163    ///
164    /// # Arguments
165    ///
166    /// * `count` - The number of recent commits to retrieve.
167    ///
168    /// # Returns
169    ///
170    /// A Result containing the branch name as a String or an error.
171    pub fn get_current_branch(&self) -> Result<String> {
172        let repo = self.open_repo()?;
173        if let Ok(head) = repo.head() {
174            let branch_name = head.shorthand().unwrap_or("HEAD detached").to_string();
175            debug!("Current branch: {branch_name}");
176            Ok(branch_name)
177        } else {
178            // For fresh repos with no commits, default to "main"
179            debug!("No HEAD found (fresh repository), defaulting to 'main'");
180            Ok("main".to_string())
181        }
182    }
183
184    /// Executes a Git hook.
185    ///
186    /// # Arguments
187    ///
188    /// * `hook_name` - The name of the hook to execute.
189    ///
190    /// # Returns
191    ///
192    /// A Result indicating success or an error.
193    pub fn execute_hook(&self, hook_name: &str) -> Result<()> {
194        if self.is_remote {
195            debug!("Skipping hook execution for remote repository");
196            return Ok(());
197        }
198
199        let repo = self.open_repo()?;
200        let hook_path = repo.path().join("hooks").join(hook_name);
201
202        if hook_path.exists() {
203            debug!("Executing hook: {hook_name}");
204            debug!("Hook path: {}", hook_path.display());
205
206            // Get the repository's working directory (top level)
207            let repo_workdir = repo
208                .workdir()
209                .context("Repository has no working directory")?;
210            debug!("Repository working directory: {}", repo_workdir.display());
211
212            // Create a command with the proper environment and working directory
213            let mut command = Command::new(&hook_path);
214            command
215                .current_dir(repo_workdir) // Use the repository's working directory, not .git
216                .env("GIT_DIR", repo.path()) // Set GIT_DIR to the .git directory
217                .env("GIT_WORK_TREE", repo_workdir) // Set GIT_WORK_TREE to the working directory
218                .stdout(Stdio::piped())
219                .stderr(Stdio::piped());
220
221            debug!("Executing hook command: {command:?}");
222
223            let mut child = command.spawn()?;
224
225            let stdout = child.stdout.take().context("Could not get stdout")?;
226            let stderr = child.stderr.take().context("Could not get stderr")?;
227
228            std::thread::spawn(move || {
229                std::io::copy(&mut std::io::BufReader::new(stdout), &mut std::io::stdout())
230                    .expect("Failed to copy data to stdout");
231            });
232            std::thread::spawn(move || {
233                std::io::copy(&mut std::io::BufReader::new(stderr), &mut std::io::stderr())
234                    .expect("Failed to copy data to stderr");
235            });
236
237            let status = child.wait()?;
238
239            if !status.success() {
240                return Err(anyhow!(
241                    "Hook '{}' failed with exit code: {:?}",
242                    hook_name,
243                    status.code()
244                ));
245            }
246
247            debug!("Hook '{hook_name}' executed successfully");
248        } else {
249            debug!("Hook '{}' not found at {}", hook_name, hook_path.display());
250        }
251
252        Ok(())
253    }
254
255    /// Get the root directory of the current git repository
256    pub fn get_repo_root() -> Result<PathBuf> {
257        // Check if we're in a git repository
258        if !is_inside_work_tree()? {
259            return Err(anyhow!(
260                "Not in a Git repository. Please run this command from within a Git repository."
261            ));
262        }
263
264        // Use git2 to find the repository root
265        let repo = Repository::discover(".").context("Failed to discover git repository")?;
266        let workdir = repo
267            .workdir()
268            .context("Repository has no working directory")?;
269        Ok(workdir.to_path_buf())
270    }
271
272    /// Retrieves the README content at a specific commit.
273    ///
274    /// # Arguments
275    ///
276    /// * `commit_ish` - A string that resolves to a commit.
277    ///
278    /// # Returns
279    ///
280    /// A Result containing an `Option<String>` with the README content or an error.
281    pub fn get_readme_at_commit(&self, commit_ish: &str) -> Result<Option<String>> {
282        let repo = self.open_repo()?;
283        let obj = repo.revparse_single(commit_ish)?;
284        let tree = obj.peel_to_tree()?;
285
286        Self::find_readme_in_tree(&repo, &tree)
287            .context("Failed to find and read README at specified commit")
288    }
289
290    /// Finds a README file in the given tree.
291    ///
292    /// # Arguments
293    ///
294    /// * `tree` - A reference to a Git tree.
295    ///
296    /// # Returns
297    ///
298    /// A Result containing an `Option<String>` with the README content or an error.
299    fn find_readme_in_tree(repo: &Repository, tree: &Tree) -> Result<Option<String>> {
300        debug!("Searching for README file in the repository");
301
302        let readme_patterns = [
303            "README.md",
304            "README.markdown",
305            "README.txt",
306            "README",
307            "Readme.md",
308            "readme.md",
309        ];
310
311        for entry in tree {
312            let name = entry.name().unwrap_or("");
313            if readme_patterns
314                .iter()
315                .any(|&pattern| name.eq_ignore_ascii_case(pattern))
316            {
317                let object = entry.to_object(repo)?;
318                if let Some(blob) = object.as_blob()
319                    && let Ok(content) = std::str::from_utf8(blob.content())
320                {
321                    debug!("README file found: {name}");
322                    return Ok(Some(content.to_string()));
323                }
324            }
325        }
326
327        debug!("No README file found");
328        Ok(None)
329    }
330
331    /// Extract files info without crossing async boundaries
332    pub fn extract_files_info(&self, include_unstaged: bool) -> Result<RepoFilesInfo> {
333        let repo = self.open_repo()?;
334
335        // Get basic repo info
336        let branch = self.get_current_branch()?;
337        let recent_commits = self.get_recent_commits(5)?;
338
339        // Get staged and unstaged files
340        let mut staged_files = get_file_statuses(&repo, &self.gitignore_matcher)?;
341        if include_unstaged {
342            let unstaged_files = self.get_unstaged_files()?;
343            staged_files.extend(unstaged_files);
344            debug!("Combined {} files (staged + unstaged)", staged_files.len());
345        }
346
347        // Extract file paths for metadata
348        let file_paths: Vec<String> = staged_files.iter().map(|file| file.path.clone()).collect();
349
350        Ok(RepoFilesInfo {
351            branch,
352            recent_commits,
353            staged_files,
354            file_paths,
355        })
356    }
357
358    /// Gets unstaged file changes from the repository
359    pub fn get_unstaged_files(&self) -> Result<Vec<StagedFile>> {
360        let repo = self.open_repo()?;
361        get_unstaged_file_statuses(&repo, &self.gitignore_matcher)
362    }
363
364    /// Helper method for creating `CommitContext`
365    ///
366    /// # Arguments
367    ///
368    /// * `branch` - Branch name
369    /// * `recent_commits` - List of recent commits
370    /// * `staged_files` - List of staged files
371    /// * `project_metadata` - Project metadata
372    ///
373    /// # Returns
374    ///
375    /// A Result containing the `CommitContext` or an error.
376    fn create_commit_context(
377        &self,
378        branch: String,
379        recent_commits: Vec<RecentCommit>,
380        staged_files: Vec<StagedFile>,
381    ) -> Result<CommitContext> {
382        // Get user info
383        let repo = self.open_repo()?;
384        let user_name = repo.config()?.get_string("user.name").unwrap_or_default();
385        let user_email = repo.config()?.get_string("user.email").unwrap_or_default();
386
387        // Get author's commit history (last 10 commits)
388        let author_history = self.get_author_commit_history(&user_email, 10)?;
389
390        // Create and return the context
391        Ok(CommitContext::new(
392            branch,
393            recent_commits,
394            staged_files,
395            user_name,
396            user_email,
397            author_history,
398        ))
399    }
400
401    /// Enhance context with cached commit messages from other repositories
402    fn enhance_context_with_cache(
403        &self,
404        context: &mut CommitContext,
405        _config: &Config,
406    ) -> Result<()> {
407        let cache = CommitMessageCache::new()?;
408
409        // Get cached messages for this author
410        let cached_messages =
411            cache.get_commit_messages(&context.user_email, &self.repo_path.to_string_lossy());
412
413        // Convert cached messages to strings for the context
414        let cached_history: Vec<String> =
415            cached_messages.into_iter().map(|msg| msg.message).collect();
416
417        // Merge with existing history
418        let mut enhanced_history = context.author_history.clone();
419        enhanced_history.extend(cached_history);
420
421        // Remove duplicates and limit size
422        let mut unique_history = Vec::new();
423        let mut seen = HashSet::new();
424        for msg in enhanced_history {
425            if seen.insert(msg.clone()) {
426                unique_history.push(msg);
427            }
428        }
429
430        // Keep only the most recent 100 messages to avoid context overflow
431        if unique_history.len() > 100 {
432            unique_history = unique_history.into_iter().take(100).collect();
433        }
434
435        context.author_history = unique_history;
436
437        Ok(())
438    }
439
440    /// Get Git information including unstaged changes
441    ///
442    /// # Arguments
443    ///
444    /// * `config` - The configuration object.
445    ///
446    /// # Returns
447    ///
448    /// A Result containing the `CommitContext` or an error.
449    #[allow(clippy::unused_async)]
450    pub async fn get_git_info(&self, config: &Config) -> Result<CommitContext> {
451        // Get data that doesn't cross async boundaries
452        let repo = self.open_repo()?;
453        debug!("Getting git info for repo path: {}", repo.path().display());
454
455        let branch = self.get_current_branch()?;
456        let recent_commits = self.get_recent_commits(5)?;
457        let staged_files = get_file_statuses(&repo, &self.gitignore_matcher)?;
458
459        // Create and return the context
460        let mut context = self.create_commit_context(branch, recent_commits, staged_files)?;
461
462        // Enhance with cached commit messages
463        self.enhance_context_with_cache(&mut context, config)?;
464
465        Ok(context)
466    }
467
468    /// Get Git information including unstaged changes
469    ///
470    /// # Arguments
471    ///
472    /// * `config` - The configuration object.
473    /// * `include_unstaged` - Whether to include unstaged changes.
474    ///
475    /// # Returns
476    ///
477    /// A Result containing the `CommitContext` or an error.
478    #[allow(clippy::unused_async)]
479    pub async fn get_git_info_with_unstaged(
480        &self,
481        config: &Config,
482        include_unstaged: bool,
483    ) -> Result<CommitContext> {
484        // Get data that doesn't cross async boundaries
485        let repo = self.open_repo()?;
486        debug!(
487            "Getting git info for repo path: {}, include_unstaged: {}",
488            repo.path().display(),
489            include_unstaged
490        );
491
492        let branch = self.get_current_branch()?;
493        let recent_commits = self.get_recent_commits(5)?;
494        let mut staged_files = get_file_statuses(&repo, &self.gitignore_matcher)?;
495
496        // Add unstaged files if requested
497        if include_unstaged {
498            let unstaged_files = get_unstaged_file_statuses(&repo, &self.gitignore_matcher)?;
499            staged_files.extend(unstaged_files);
500            debug!("Combined {} files (staged + unstaged)", staged_files.len());
501        }
502
503        // Create and return the context
504        let mut context = self.create_commit_context(branch, recent_commits, staged_files)?;
505
506        // Enhance with cached commit messages
507        self.enhance_context_with_cache(&mut context, config)?;
508
509        Ok(context)
510    }
511
512    /// Get Git information for comparing two branches
513    ///
514    /// # Arguments
515    ///
516    /// * `config` - The configuration object
517    /// * `base_branch` - The base branch (e.g., "main")
518    /// * `target_branch` - The target branch (e.g., "feature-branch")
519    ///
520    /// # Returns
521    ///
522    /// A Result containing the `CommitContext` for the branch comparison or an error.
523    pub fn get_git_info_for_branch_diff(
524        &self,
525        _config: &Config,
526        base_branch: &str,
527        target_branch: &str,
528    ) -> Result<CommitContext> {
529        debug!("Getting git info for branch diff: {base_branch} -> {target_branch}");
530        let repo = self.open_repo()?;
531
532        // Extract branch diff info
533        let (display_branch, recent_commits, _) = commit::extract_branch_diff_info(
534            &repo,
535            base_branch,
536            target_branch,
537            &self.gitignore_matcher,
538        )?;
539
540        // Get the actual file changes
541        let branch_files = commit::get_branch_diff_files(
542            &repo,
543            base_branch,
544            target_branch,
545            &self.gitignore_matcher,
546        )?;
547
548        // Create and return the context
549        self.create_commit_context(display_branch, recent_commits, branch_files)
550    }
551
552    /// Get Git information for a commit range (for PR descriptions)
553    ///
554    /// # Arguments
555    ///
556    /// * `config` - The configuration object
557    /// * `from` - The starting Git reference (exclusive)
558    /// * `to` - The ending Git reference (inclusive)
559    ///
560    /// # Returns
561    ///
562    /// A Result containing the `CommitContext` for the commit range or an error.
563    pub fn get_git_info_for_commit_range(
564        &self,
565        _config: &Config,
566        from: &str,
567        to: &str,
568    ) -> Result<CommitContext> {
569        debug!("Getting git info for commit range: {from} -> {to}");
570        let repo = self.open_repo()?;
571
572        // Extract commit range info
573        let (display_range, recent_commits, _) =
574            commit::extract_commit_range_info(&repo, from, to, &self.gitignore_matcher)?;
575
576        // Get the actual file changes
577        let range_files = commit::get_commit_range_files(&repo, from, to, &self.gitignore_matcher)?;
578
579        // Create and return the context
580        self.create_commit_context(display_range, recent_commits, range_files)
581    }
582
583    /// Get commits for PR description between two references
584    pub fn get_commits_for_pr(&self, from: &str, to: &str) -> Result<Vec<String>> {
585        let repo = self.open_repo()?;
586        commit::get_commits_for_pr(&repo, from, to)
587    }
588
589    /// Get files changed in a commit range
590    pub fn get_commit_range_files(&self, from: &str, to: &str) -> Result<Vec<StagedFile>> {
591        let repo = self.open_repo()?;
592        commit::get_commit_range_files(&repo, from, to, &self.gitignore_matcher)
593    }
594
595    /// Retrieves recent commits.
596    ///
597    /// # Arguments
598    ///
599    /// * `count` - The number of recent commits to retrieve.
600    ///
601    /// # Returns
602    ///
603    /// A Result containing a Vec of `RecentCommit` objects or an error.
604    pub fn get_recent_commits(&self, count: usize) -> Result<Vec<RecentCommit>> {
605        let repo = self.open_repo()?;
606        debug!("Fetching {count} recent commits");
607        let mut revwalk = repo.revwalk()?;
608
609        // For fresh repos with no commits, push_head() will fail, so return empty vec
610        if revwalk.push_head().is_err() {
611            debug!("No HEAD found (fresh repository), returning empty recent commits");
612            return Ok(Vec::new());
613        }
614
615        let commits = revwalk
616            .take(count)
617            .map(|oid| {
618                let oid = oid?;
619                let commit = repo.find_commit(oid)?;
620                let author = commit.author();
621                Ok(RecentCommit {
622                    hash: oid.to_string(),
623                    message: commit.message().unwrap_or_default().to_string(),
624                    author: author.name().unwrap_or_default().to_string(),
625                    timestamp: commit.time().seconds().to_string(),
626                })
627            })
628            .collect::<Result<Vec<_>>>()?;
629
630        debug!("Retrieved {} recent commits", commits.len());
631        Ok(commits)
632    }
633
634    /// Retrieves the author's recent commit messages.
635    ///
636    /// # Arguments
637    ///
638    /// * `author_email` - The email of the author to filter by.
639    /// * `count` - The number of recent commits to retrieve.
640    ///
641    /// # Returns
642    ///
643    /// A Result containing a Vec of commit message strings or an error.
644    pub fn get_author_commit_history(
645        &self,
646        author_email: &str,
647        count: usize,
648    ) -> Result<Vec<String>> {
649        let repo = self.open_repo()?;
650        debug!("Fetching {count} recent commits for author: {author_email}");
651        let mut revwalk = repo.revwalk()?;
652
653        // For fresh repos with no commits, push_head() will fail, so return empty vec
654        if revwalk.push_head().is_err() {
655            debug!("No HEAD found (fresh repository), returning empty author history");
656            return Ok(Vec::new());
657        }
658
659        let mut cached_messages = Vec::new();
660        let mut commit_messages = Vec::new();
661
662        for oid_result in revwalk.take(count) {
663            let oid = oid_result?;
664            let commit = repo.find_commit(oid)?;
665            let author = commit.author();
666
667            // Filter by author email
668            if author.email() == Some(author_email) {
669                let message = commit.message().unwrap_or_default().to_string();
670                let timestamp = commit.time().seconds().to_string();
671                let hash = format!("{oid}");
672
673                // Store for caching
674                cached_messages.push(CachedCommitMessage {
675                    message: message.clone(),
676                    timestamp,
677                    hash,
678                });
679
680                // Store for return
681                commit_messages.push(message);
682            }
683        }
684
685        // Cache the retrieved messages
686        if !cached_messages.is_empty() {
687            let mut cache = CommitMessageCache::new()?;
688            let repo_path = self.repo_path.to_string_lossy().to_string();
689            cache.add_commit_messages(author_email, &repo_path, cached_messages);
690            cache.save()?;
691        }
692
693        debug!(
694            "Retrieved {} commits for author {}",
695            commit_messages.len(),
696            author_email
697        );
698        Ok(commit_messages)
699    }
700
701    /// Commits changes and verifies the commit.
702    ///
703    /// # Arguments
704    ///
705    /// * `message` - The commit message.
706    ///
707    /// # Returns
708    ///
709    /// A Result containing the `CommitResult` or an error.
710    pub fn commit_and_verify(&self, message: &str) -> Result<CommitResult> {
711        if self.is_remote {
712            return Err(anyhow!(
713                "Cannot commit to a remote repository in read-only mode"
714            ));
715        }
716
717        let repo = self.open_repo()?;
718        match commit::commit(&repo, message, self.is_remote) {
719            Ok(result) => {
720                if let Err(e) = self.execute_hook("post-commit") {
721                    debug!("Post-commit hook failed: {e}");
722                }
723                Ok(result)
724            }
725            Err(e) => {
726                debug!("Commit failed: {e}");
727                Err(e)
728            }
729        }
730    }
731
732    /// Get Git information for a specific commit
733    ///
734    /// # Arguments
735    ///
736    /// * `config` - The configuration object
737    /// * `commit_id` - The ID of the commit to analyze
738    ///
739    /// # Returns
740    ///
741    /// A Result containing the `CommitContext` or an error.
742    pub fn get_git_info_for_commit(
743        &self,
744        _config: &Config,
745        commit_id: &str,
746    ) -> Result<CommitContext> {
747        debug!("Getting git info for commit: {commit_id}");
748        let repo = self.open_repo()?;
749
750        // Get branch name
751        let branch = self.get_current_branch()?;
752
753        // Extract commit info
754        let commit_info = commit::extract_commit_info(&repo, commit_id, &branch)?;
755
756        // Get the files from commit after async boundary
757        let commit_files = commit::get_commit_files(&repo, commit_id, &self.gitignore_matcher)?;
758
759        // Create and return the context
760        self.create_commit_context(commit_info.branch, vec![commit_info.commit], commit_files)
761    }
762
763    /// Get the commit date for a reference
764    pub fn get_commit_date(&self, commit_ish: &str) -> Result<String> {
765        let repo = self.open_repo()?;
766        commit::get_commit_date(&repo, commit_ish)
767    }
768
769    /// Get commits between two references with a callback
770    pub fn get_commits_between_with_callback<T, F>(
771        &self,
772        from: &str,
773        to: &str,
774        callback: F,
775    ) -> Result<Vec<T>>
776    where
777        F: FnMut(&RecentCommit) -> Result<T>,
778    {
779        let repo = self.open_repo()?;
780        commit::get_commits_between_with_callback(&repo, from, to, callback)
781    }
782
783    /// Stream commits between two references with a callback
784    pub fn get_commits_between_stream<F>(&self, from: &str, to: &str, callback: F) -> Result<()>
785    where
786        F: FnMut(&RecentCommit) -> Result<()>,
787    {
788        let repo = self.open_repo()?;
789        commit::get_commits_between_stream(&repo, from, to, callback)
790    }
791
792    /// Commit changes to the repository
793    pub fn commit(&self, message: &str) -> Result<CommitResult> {
794        let repo = self.open_repo()?;
795        commit::commit(&repo, message, self.is_remote)
796    }
797
798    /// Amend a commit with a new message
799    pub fn amend_commit(&self, message: &str, commit_ref: &str) -> Result<CommitResult> {
800        let repo = self.open_repo()?;
801        commit::amend_commit(&repo, message, commit_ref, self.is_remote)
802    }
803
804    /// Check if inside a working tree
805    pub fn is_inside_work_tree() -> Result<bool> {
806        is_inside_work_tree()
807    }
808
809    /// Get the files changed in a specific commit
810    pub fn get_commit_files(&self, commit_id: &str) -> Result<Vec<StagedFile>> {
811        let repo = self.open_repo()?;
812        commit::get_commit_files(&repo, commit_id, &self.gitignore_matcher)
813    }
814
815    /// Get just the file paths for a specific commit
816    pub fn get_file_paths_for_commit(&self, commit_id: &str) -> Result<Vec<String>> {
817        let repo = self.open_repo()?;
818        commit::get_file_paths_for_commit(&repo, commit_id)
819    }
820}
821
822impl Drop for GitRepo {
823    fn drop(&mut self) {
824        // The TempDir will be automatically cleaned up when dropped
825        if self.is_remote {
826            debug!(
827                "Cleaning up temporary repository at {}",
828                self.repo_path.display()
829            );
830        }
831    }
832}