Skip to content

Commit

Permalink
fix: Enhance commit existence checks in GitRepository (#23)
Browse files Browse the repository at this point in the history
- Added a new method `commitExistsLocally` to verify if a commit exists in the local repository.
- Updated the `IsAncestor` method to check for local commit existence before attempting to fetch, improving reliability in ancestor checks.
- Ensured that the fetch operation is only attempted if necessary, and added error handling for cases where commits are still not found after fetching.

These changes improve the robustness of commit comparisons in the Git repository management.

Signed-off-by: Alessandro De Blasis <alex@deblasis.net>
  • Loading branch information
deblasis authored Dec 11, 2024
1 parent d4dee0b commit 4aea4b3
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions internal/git/compare.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,29 @@ const (
CommitsDiverged CommitComparisonResult = 2
)

// commitExistsLocally checks if a commit exists in the local repository
func (r *GitRepository) commitExistsLocally(ctx context.Context, commit string) bool {
_, err := r.executor.ExecuteCommand(ctx, "git", "cat-file", "-e", commit)
return err == nil
}

// IsAncestor checks if commitA is an ancestor of commitB
func (r *GitRepository) IsAncestor(ctx context.Context, commitA, commitB string) (bool, error) {
// Check if commits exist locally
for _, commit := range []string{commitA, commitB} {
if !r.commitExistsLocally(ctx, commit) {
// Commit not found locally, try fetching
if err := r.Fetch(ctx); err != nil {
return false, fmt.Errorf("failed to fetch after missing commit %s: %w", commit, err)
}
// Verify commit exists after fetch
if !r.commitExistsLocally(ctx, commit) {
return false, fmt.Errorf("commit %s not found even after fetch", commit)
}
break // Only need to fetch once
}
}

_, err := r.executor.ExecuteCommand(ctx, "git", "-C", r.cfg.GitDir, "merge-base", "--is-ancestor", commitA, commitB)
if err != nil {
var exitErr *exec.ExitError
Expand Down

0 comments on commit 4aea4b3

Please sign in to comment.