Last week, I deleted a git branch that had a number of local commits. In fact, there were many occasions in the past where I thought I lost a lot of work, due to a faulty git command. Each time, the
git reflog was always there to prevent disaster. If you know how to use Git Reflog, you too may save yourself from disaster.
How Git Reflog Saved Me Last Week
I normally work on multiple features and therefore have multiple branches at one time. I also love to keep my workstation clean by removing all branches that I am done with.
Last week, I accidentally committed some of my new work onto an old branch.
After my normal cleanup process, I realized I just deleted hours' worth of work.
This is where
git reflog comes in.
This git command displays a history of every point the reference at HEAD changed. More importantly, it has a record of my lost commits.
From there I was able to cherry-pick the commits I needed and revive them on a different branch.
How You Can Use Git Reflog
If you find yourself in a similar situation where you deleted the wrong branch or
reset --hard the wrong commit, git reflog is by your side.
In my case, I checked out a new branch.
Then, cherry-picked my commits.
If you are unfamiliar with the
git-cherry-pick command, basically what it does is take a commit from somewhere else, and "play it back" wherever you are right now. Because this introduces the same change with a different parent, Git builds a new commit with a different ID.
Looking at my
git log output, my commits were back. I was safe.
Working with something as volatile as code can be a scary thing. So befriend
git reflog because it will always have your back, save you from losing hours of hard work and headaches.