Recovering Commits from a Failed Git Rebase

By Edmund Gorski - May 22, 2017

Recovering Commits from a Failed Git Rebase
May 22, 2017 By Edmund Gorski

Recovering Commits from a Failed Git Rebase

So, let's lay out a little situation here.  You have a few local Git commits that you have been working on locally but have not yet pushed to the remote.  Before your push, you fetch/pull the latest from a remote Git repository and, like a good, team-oriented developer should, you perform a rebase instead of a merge on the changes.   But there is a problem during the rebase, maybe it's your internet, maybe it's a weird file permission issue or maybe there are gremlins....  

Working through the issue, you try to pull again, but get prompted to either continue or abandon your rebase.  You decide to continue and you pull normally.  But, what's this?!?  All your previous commits that you have not pushed are GONE from your history!  

This is a weird little bug we've encountered in Git that seems to reset the HEAD to a commit upstream and "forgets" about your previous commits.  So how do we fix it?


Git Reflog to the Rescue   

The Git Reflog is an ordered list of the commits that HEAD has pointed to locally.  It is not part of the repository and is not included in any pulls, pushes, fetches or clones, therefore it will not be messed up by our current problem.  Simply put, consider the reflog as your personal undo history for your repository.  Even though our current git log does not have the commits we are missing, the reflog will.  To see those "lost" commits, open up a command line, navigate to your repository folder and run:

> git reflog

Now, from the list, find the id of the latest commit that you want to recover (e.g. HEAD@)  and run:

> git reset --hard HEAD@

Your commit history should be restored and HEAD should now be reset to your last lost commit!

Happy coding!