How a revert to wrong merge can mess your code in Git?

git-tutorial_branching-mergingYou can’t really imagine working on a project without using a version control system. Git is the best bet for me. This is an interesting story of how a wrong merge and then revert messed our codebase.

How did this problem arise?

I am working on a product of ours. The stable code stays in the master branch. We, however, have a few variations or customized versions of the product. To maintain this customized version, we have created a separate branch for each such customized version which is branched off from the master. This branch contains only some customized modifications of their own while it will have all new features or updates that happen to master. So these branches are regularly synchronized with the master by merging the master branch in it and hence taking latest features.

Well, one of my team members, mistakenly, merge one of these customized version’s branch with master and hence taking all customized features to master. As he realized this mistake, he reverted the merge and pushed it to master. After a few days, while I was trying to sync one of my customized branches with the master, I merge it with the master. Luckily I took a peek in the code and realized, *poof* the customized code is gone and this special branch is similar to master branch now!

Why did this happen?

As I said earlier, my colleague had mistakenly merged this branch with master and then reverted the merge. So this revert commit has caused removal of all specialized code that came to master because of the wrong merge. So for the code history, this was a new commit and difference. So when I merged master into this special branch, it also applied the patch of this revert and removed the customized code from this branch also.

So, how to fix this?

Well, this sounds scary to lose all changes of a custom branch but the fix is pretty simple. You need to revert the revert of the wrong merge that happened, in your customization branch. Not to confuse you, putting it simply, follow these steps:

  • Find out the sha1 of the commit which was created while reverting the wrong merge that happened while merging your specialized branch into master.
  • Checkout your branch with customization where you have lost your changes
  • Use this sha1 to revert the commit by using `git revert {sha1}`
  • Fix conflicts if any and just quickly skim through your code to see if everything is fine
  • Done!

I hope this will help someone from having a shock in this situation.

Feel free to ask any doubts in comments. Do not forget to tell me if you’ve been in this situation too. ;-)

Published by

ksg91

Kishan is a tech-enthusiast, Software Developer and a Gadget lover. He loves Adventure, Photography and Solving Problems.

Leave a Reply

Your email address will not be published. Required fields are marked *