Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is git checkout implemented?

When running git checkout, the mergebase of the old HEAD and the new HEAD can be arbitrarily far back. The naïve implementation would be to linearly apply each diff, yet the operation runs instantly.

I have a hunch it might be implemented with something kind of skiplisty for intermediate diff caching, but that's just a guess.

Does anybody know how it's implemented? Thanks! :)

like image 262
brettwines Avatar asked Jan 28 '15 08:01

brettwines


1 Answers

You have a good example on how a checkout is (in principle) implemented in the javascript implementation of Git (as an exercise) Gitlet by Mary Rose Cook.

See the annotated source code

For a checkout, the steps are:

  • checkout() changes the index, working copy and HEAD to reflect the content of ref.
    ref might be a branch name or a commit hash.
  • Get the hash of the commit to check out.
  • Abort if ref cannot be found.
  • Abort if the hash to check out points to an object that is a not a commit.
  • Abort if ref is the name of the branch currently checked out. Abort if head is detached, ref is a commit hash and HEAD is pointing at that hash.
  • Get a list of files changed in the working copy.
    Get a list of the files that are different in the head commit and the commit to check out.
    If any files appear in both lists then abort.
  • Otherwise, perform the checkout.
  • If the ref is in the objects directory, it must be a hash and so this checkout is detaching the head.
  • Get the list of differences between the current commit and the commit to check out. Write them to the working copy.
  • Write the commit being checked out to HEAD.
    If the head is being detached, the commit hash is written directly to the HEAD file.
    If the head is not being detached, the branch being checked out is written to HEAD.
  • Set the index to the contents of the commit being checked out.
  • Report the result of the checkout.

Again, it is a simplification (compared to the actual Git code), but gives a good idea on how a checkout is supposed to work.

For more, you can listen the GitMinutes #31: Mary Rose Cook on Gitlet podcast episode by Thomas Ferris Nicolaisen.

like image 152
VonC Avatar answered Oct 28 '22 20:10

VonC