DEV Community

Guillaume Gautreau
Guillaume Gautreau

Posted on • Originally published at ghusse.com

Git tip: get back to work after a revert on master

Git diagram

Shit happens.

Sometimes, a sneaky bug hid itself into the beautiful change you worked on. It even flew below unit tests' radars and tiptoed without being noticed during manual tests.

Now, this nasty bug is live in production and EVERYONE notices it, you have to revert your changes from master. 😒

↩ The revert

Ok, this is the time where you revert your code:

# Assuming that you have to create a PR
# for the revert
git checkout master
git pull
git checkout -b fix/revert-superb-change
git revert HASH-OF-MERGE-COMMIT
git push -u origin fix/revert-superb-change
Enter fullscreen mode Exit fullscreen mode

Once your PR gets approved, your revert just cancelled everything that was in your cool change.

πŸ‘· Work on a fix

At this point, the easiest thing to do is to just make a fix on the branch containing all your changes.

git checkout feat/superb-change
# Work on a fix
# ...
# ...
# ...
git commit -a -m "fix: sneaky bug"
git push
Enter fullscreen mode Exit fullscreen mode

😨 OMG, if I merge master on my branch, I lose almost all my work

That's it, if you want to prepare your branch to be merged again on master, you'll face another problem:

Master contains a commit that removes the work from your branch.

If you merge master into your feature branch as usual, it will actually remove a large proportion of your changes on your branch. 🀯

πŸš’ Merge mastery to the rescue

This is the trick: you can tell git that a particular commit had been merged without actually merging it.

git checkout feat/superb-change

# This will allow you to apply all 
# changes between your first merge 
# and the revert, if any
#
# ⚠ It's important to carefully choose
# the commit JUST BEFORE the revert commit
git merge HASH-OF-COMMIT-JUST-BEFORE-REVERT

# This is how you tell git to merge
# without really merging the revert
git merge HASH-OF-REVERT-COMMIT --strategy=ours
Enter fullscreen mode Exit fullscreen mode

The option --strategy=ours tells git to keep all our current changes when merging.

It means that it will only record the merge without changing anything in your branch.

It's important to note that you should first merge all changes made before the revert in order to correctly apply them. This way, only the revert will be merged without changes on your code.

Once everything had been done, you can proceed as usual:

# Will merge all changes made after the revert
git merge master
git push
Enter fullscreen mode Exit fullscreen mode

And now, your branch is ready to be merged into master, with all your changes!


Thanks to @bryanbraun for his awesome git diagram template.

Top comments (0)