go-git icon indicating copy to clipboard operation
go-git copied to clipboard

git: worktree, Optimize Checkout for same tree

Open cedric-appdirect opened this issue 2 months ago • 3 comments

Add fast-path optimization to Checkout() that skips expensive worktree scanning when target commit has the same tree as current HEAD.

This matches git CLI behavior which only updates files when trees differ. When creating a new branch from current HEAD (same tree), this eliminates unnecessary file enumeration and hashing that can take seconds on large repositories.

Implementation:

  • Add canSkipWorktreeUpdate() helper that compares tree hashes
  • Fast path applies when: !Force && !Keep && no sparse directories
  • Falls back to existing Reset() logic for different trees
  • Graceful error handling with fallback to slow path

Testing:

  • Added unit tests for fast path scenarios
  • Added benchmarks demonstrating improvement
  • All existing checkout tests pass
  • No breaking changes to API

cedric-appdirect avatar Nov 20 '25 22:11 cedric-appdirect

This showed has a real issue for one of the repository I use which has over 30k files in them. Benchmark will still show the speedup with less file. It does mimics how git cli work as far as I could figure out. I have left documentation inside the function just to make sure it doesn't get accidentally removed.

cedric-appdirect avatar Nov 20 '25 22:11 cedric-appdirect

Sorry, for the first run with some tests issues. I had not noticed that some of them should have passed locally. For some reason, some of the main branch tests are failing on my computer. If it is not expected, I can look at fixing those too in a separate PR.

cedric-appdirect avatar Nov 21 '25 01:11 cedric-appdirect

Sorry took me long to come back to this. Let me know if there is anything else that I should improve.

cedric-appdirect avatar Dec 10 '25 17:12 cedric-appdirect