Skip to content

git: worktree, fix successive branch checkouts from same commit. Fixes #2124#2127

Open
AriehSchneier wants to merge 1 commit into
go-git:mainfrom
AriehSchneier:fix-issue-2124-checkout-preserves-files
Open

git: worktree, fix successive branch checkouts from same commit. Fixes #2124#2127
AriehSchneier wants to merge 1 commit into
go-git:mainfrom
AriehSchneier:fix-issue-2124-checkout-preserves-files

Conversation

@AriehSchneier

Copy link
Copy Markdown
Contributor

Summary

Fixes #2124 - When checking out multiple branches from the same base commit with Force:true, files from previous iterations were incorrectly preserved in the worktree.

Root Cause

Checkout() updated HEAD before calling Reset(), so when Reset() captured the "previous" tree via headTree(), it got the tree from the NEW commit (just set by Checkout) rather than the OLD commit (where the worktree actually was). This caused resetWorktreeToTree to diff the same tree against itself, resulting in no changes.

Solution

Capture the current tree BEFORE updating HEAD in Checkout(), and pass it to Reset() via a new internal field in ResetOptions. This ensures HardReset and KeepReset properly diff from the actual previous state.

Changes

  • Added internal fromTree field to ResetOptions
  • Modified Checkout() to capture tree before updating HEAD
  • Modified Reset() to use provided fromTree when available
  • Added comprehensive regression test TestCheckoutSuccessiveBranchesFromSameCommit

Testing

AI Disclosure

This contribution was assisted by Claude Sonnet 4.5 as documented in the Assisted-by: commit trailer, in accordance with the AI Contribution Policy.

@AriehSchneier AriehSchneier requested a review from pjbgf May 15, 2026 07:03
…go-git#2124

When checking out multiple branches from the same base commit with
Force:true, files from previous iterations were incorrectly preserved
in the worktree.

Root cause: Checkout() updated HEAD before calling Reset(), so when
Reset() captured the "previous" tree via headTree(), it got the tree
from the NEW commit (just set by Checkout) rather than the OLD commit
(where the worktree actually was). This caused resetWorktreeToTree to
diff the same tree against itself, resulting in no changes.

Fix: Capture the current tree BEFORE updating HEAD in Checkout(), and
pass it to Reset() via a new internal field in ResetOptions. This
ensures HardReset and KeepReset properly diff from the actual previous
state.

Assisted-by: Claude Sonnet 4.5 <[email protected]>
Signed-off-by: Arieh Schneier <[email protected]>
@AriehSchneier AriehSchneier force-pushed the fix-issue-2124-checkout-preserves-files branch from 3304cfe to 1515c02 Compare May 16, 2026 09:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Successive Branches Retain Commits from Previous Iterations

1 participant