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