Thursday, August 11, 2011

Git (no branch) lost my changes on checkout

Branching and merging is the fun part of Git repositories. But, because it is so quick and efficient at merging, you often forget about all the complicated operations, it is doing behind the scenes.

If you are rebasing your codebase while merging (which I do all the time to get a nice & clean timeline), you can often land your self at a 'detached head' , which means that your repository is referencing a commit (using its unique SHA1) and not a branch. At this point in time git will respond with '(no branch)' when asked for current branch name.

While on a no-branch, if you happen to checkout another branch, like I did this morning, you will discover (soon enough) that all your changes are lost! But are they really?

git reflog to your rescue. This command shows the log of your git repository operations. It will simply list out all the commits you have done in recent past with their SHA1 ids.
fdf246b HEAD@{0}: checkout: moving from 4c8f4d86690ca7e7e3b0c9e8ea91abfde2eae265 to product_searching
4c8f4d8 HEAD@{1}: commit (amend):
372ad3e HEAD@{2}: commit: ..........................
fd747eb HEAD@{3}: commit: ..........................
0326d13 HEAD@{4}: commit: ..........................
7ca63e8 HEAD@{5}: commit: ..........................
Just find out the last commit you did while you were on no-branch (unknowingly sometimes) and merge it into the branch of your choice.

git merge 4c8f4d8

Presto! you have brought your lost commits back into a known branch!

Note: This will not work very well if you have performed 'git gc'

Alternative: 'git fsck' can be used to find out the dangling objects in repo with '--lost-found' option and then use merge operation using the SHA1 id of missing commits.

git fsck --lost-found


Good luck hunting the lost commits!

At 36zeroes we produce amazing applications. If you need an experienced Rails team for your project, Contact us.

1 comment:

  1. Thanks a million, I did not want to rewrite all that code from scratch!

    ReplyDelete