When something goes terribly wrong, git reference log history comes to the rescue.

That’s probably not something new to an experienced developer like you, but still wanted to write quick article to share.

Merge conflict

Sometimes when we are merging our branch to a main one, we can experience a merge conflict. Without going into the details, it’s basically a situation when we have changed the same line of code on our code branch as the other developer, but their change was merged into the main branch before we and now git cannot automatically resolve which one is the proper change.

Resolving conflict

In that case, we need to solve the merge conflict by our own. We can do it with various diffing tools or simply in our IDE. Now, let’s imagine that our branch is touching some multiple areas of code, we have gone through the changes, resolved each one of them, saved file and finally commit. Finished resolving the merge conflict, but we noticed issue. If we noticed that during the process, until finished, we can abort the merge by: git merge --abort or git rebase --abort, but in the case that I want to describe, we noticed the issue after we finished and closed the process.

The problem

After our merge or a rebase and resolving merge conflicts, we have noticed, that we have picked bad changes during resolving the conflict and now our branch is merged or rebased with a totally bad code. Usually, the easiest thing to do is to get back to the changes before we even started a merge or a rebase. Luckily, there’s a tool in git for it!

The solution

We can get back to the git state before our merging/rebasing process started, so we can try one more time to resolve the conflicts properly.

To do so, we need to open the terminal and type: git reflog, it should spit out something similar to this:

git reflog command output.

git reflog command output.

now, we need to find a place in the the reference log history, which reflects the state before our attempt to do a merge or a rebase. After we find our desirable place in the ref log, we can do this by typing: git reset --hard HEAD@{5} - HEAD@{5} is our desired place to revert back to.

hint: you may have to do it for your local branch and a branch that you were targeting for, for example: main.

I hope that it helped. For me, it saved me 2 days of hard work😅

Thanks for reading, until next time!👋