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
21pub struct GitRepo {
23 repo_path: PathBuf,
24 #[allow(dead_code)] temp_dir: Option<TempDir>,
27 is_remote: bool,
29 remote_url: Option<String>,
31 gitignore_matcher: GitIgnoreMatcher,
33}
34
35impl GitRepo {
36 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 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(¤t_dir)
70 }
71 }
72
73 pub fn clone_remote_repository(url: &str) -> Result<Self> {
83 debug!("Cloning remote repository from URL: {url}");
84
85 let _ = Url::parse(url).map_err(|e| anyhow!("Invalid repository URL: {e}"))?;
87
88 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 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 pub fn open_repo(&self) -> Result<Repository, git2::Error> {
119 Repository::open(&self.repo_path)
120 }
121
122 pub fn is_remote(&self) -> bool {
124 self.is_remote
125 }
126
127 pub fn get_remote_url(&self) -> Option<&str> {
129 self.remote_url.as_deref()
130 }
131
132 pub fn repo_path(&self) -> &PathBuf {
134 &self.repo_path
135 }
136
137 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 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 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 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 debug!("No HEAD found (fresh repository), defaulting to 'main'");
180 Ok("main".to_string())
181 }
182 }
183
184 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 let repo_workdir = repo
208 .workdir()
209 .context("Repository has no working directory")?;
210 debug!("Repository working directory: {}", repo_workdir.display());
211
212 let mut command = Command::new(&hook_path);
214 command
215 .current_dir(repo_workdir) .env("GIT_DIR", repo.path()) .env("GIT_WORK_TREE", repo_workdir) .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 pub fn get_repo_root() -> Result<PathBuf> {
257 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 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 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 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 pub fn extract_files_info(&self, include_unstaged: bool) -> Result<RepoFilesInfo> {
333 let repo = self.open_repo()?;
334
335 let branch = self.get_current_branch()?;
337 let recent_commits = self.get_recent_commits(5)?;
338
339 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 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 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 fn create_commit_context(
377 &self,
378 branch: String,
379 recent_commits: Vec<RecentCommit>,
380 staged_files: Vec<StagedFile>,
381 ) -> Result<CommitContext> {
382 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 let author_history = self.get_author_commit_history(&user_email, 10)?;
389
390 Ok(CommitContext::new(
392 branch,
393 recent_commits,
394 staged_files,
395 user_name,
396 user_email,
397 author_history,
398 ))
399 }
400
401 fn enhance_context_with_cache(
403 &self,
404 context: &mut CommitContext,
405 _config: &Config,
406 ) -> Result<()> {
407 let cache = CommitMessageCache::new()?;
408
409 let cached_messages =
411 cache.get_commit_messages(&context.user_email, &self.repo_path.to_string_lossy());
412
413 let cached_history: Vec<String> =
415 cached_messages.into_iter().map(|msg| msg.message).collect();
416
417 let mut enhanced_history = context.author_history.clone();
419 enhanced_history.extend(cached_history);
420
421 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 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 #[allow(clippy::unused_async)]
450 pub async fn get_git_info(&self, config: &Config) -> Result<CommitContext> {
451 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 let mut context = self.create_commit_context(branch, recent_commits, staged_files)?;
461
462 self.enhance_context_with_cache(&mut context, config)?;
464
465 Ok(context)
466 }
467
468 #[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 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 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 let mut context = self.create_commit_context(branch, recent_commits, staged_files)?;
505
506 self.enhance_context_with_cache(&mut context, config)?;
508
509 Ok(context)
510 }
511
512 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 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 let branch_files = commit::get_branch_diff_files(
542 &repo,
543 base_branch,
544 target_branch,
545 &self.gitignore_matcher,
546 )?;
547
548 self.create_commit_context(display_branch, recent_commits, branch_files)
550 }
551
552 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 let (display_range, recent_commits, _) =
574 commit::extract_commit_range_info(&repo, from, to, &self.gitignore_matcher)?;
575
576 let range_files = commit::get_commit_range_files(&repo, from, to, &self.gitignore_matcher)?;
578
579 self.create_commit_context(display_range, recent_commits, range_files)
581 }
582
583 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 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 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 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 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 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 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 cached_messages.push(CachedCommitMessage {
675 message: message.clone(),
676 timestamp,
677 hash,
678 });
679
680 commit_messages.push(message);
682 }
683 }
684
685 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 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 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 let branch = self.get_current_branch()?;
752
753 let commit_info = commit::extract_commit_info(&repo, commit_id, &branch)?;
755
756 let commit_files = commit::get_commit_files(&repo, commit_id, &self.gitignore_matcher)?;
758
759 self.create_commit_context(commit_info.branch, vec![commit_info.commit], commit_files)
761 }
762
763 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 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 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 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 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 pub fn is_inside_work_tree() -> Result<bool> {
806 is_inside_work_tree()
807 }
808
809 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 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 if self.is_remote {
826 debug!(
827 "Cleaning up temporary repository at {}",
828 self.repo_path.display()
829 );
830 }
831 }
832}