Recovering lost git commits

Yesterday it happened to me that a local git commit that I didn’t push to origin because it was still work in progress got deleted accidentally. How? It was a misusage of CMake’s testing functionality. I was configuring a new dashboard for the project and executed “make Nightly”. It is really important to know that the Nightly build target resets (–hard) the local master to origin/master. This makes sense for a buildbot, but on the development machine it’s really bad. So my last commit was lost. Really? No. Git doesn’t really delete the commits until you call “git gc”, they just not referenced anymore.

Git has a nice feature for restoring such lost commits – the git reflog. Git tracks all commits that you are adding to this reflog. So restoring the lost commit was easy.

1.) git reflog -> Shows all commits also the unreferenced ones

2.) git checkout <SHA> -> use the SHA from the reflog to checkout the lost commit. You will see a warning that the current HEAD is in detached mode, which means it is not referenced by any branch, tag, etc.

3.) git checkout -b “backup” -> This creates a new branch for the current commit and checks it out. So we are no longer detached.

From here you can use the normal git tools, to merge or rebase this commit to master.

Git rocks!


0 Responses to “Recovering lost git commits”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: