How to recover a git commit that is reset or discarded
Calm down! You can get it back!
--
We can make all kinds of mistakes when we write code. It is normal to make mistakes, but we should know how to solve the problem efficiently. In this article, I will show you an efficient way to recover a git commit that is reset or discarded accidentally.
When we write code, sometimes we may use git reset HEAD~1
to reset the HEAD of our feature branch. As we know, HEAD is the last commit of the current branch and thus HEAD~1 means the second to last commit of the current branch. With this command, the HEAD is set to the second to last commit and the original last commit is discarded. This command is useful if you want to re-organize your last commit, for example, to split it into several ones.
By default, the --mixed
option is used for git reset HEAD~1
, which means to move the changes made in the last commit from the local repository to the working directory. This is the behavior we normally want. Besides the default--mixed
option, there are two other options that can be used. The first one is --soft
, which moves the changes from the local repository to the staging area. The other one is --hard
which discards the changes from the local repository, the staging area and also the working directory. This is where the danger comes from.
You may ask, why the hell would you use the --hard
option? Well, that can happen, and has happened to me multiple times. This can happen due to a mistake, or you may think the last commit was not needed any more. If this ever happens to you, don’t panic, you will learn how to recover that commit in this article.
It turns out the commit that is discarded can be found by the git reflog
command and can be recovered with the git cherry-pick
command. Let me demonstrate how to do it step by step.
- Let’s check the commits of the current branch:
$ git log --oneline
c69a281 (HEAD -> git-demo-reflog) Update gitlab pipeline for pushing tags
b9de1dc Add a GitLab CICD pipeline to the repo
dbd121b Change num_pages in quotes.py from 10 to 20
300c819 (tag: v0.2) Merge branch 'release/v0.2' into main
2. Let’s assume that we don’t need the changes made in the last commit, namely c69a281. We…