Git Rebase: My Favourite Git Command

Thursday, September 24, 2020

I love git rebase.

If we have ever talked programming and git, I've probably mentioned git rebase to you.

Rebase has had a bad rep over the years but I can't git without it.

I like to illustrate the power and simplicity of the rebase command with an illustration:

Imagine you are working on a new feature on a separate branch alongside your stable branch. You are finally done with your work but your teammates have committed changes to the stable branch which you do not have on your own branch.

One way to solve this is to merge your feature branch into the stable branch, resolve any conflicts, create a commit that resolved the conflict (possibly with a "Merge conflicts" message).

If you are a commit log freak like me, seeing merge conflict commits irk you too. Firstly, it clogs up the commit log and secondly, it doesn't give a linear succession of commits.

I like to resolve the scenario illustrated above with git rebase.

git rebase will rewind the HEAD pointer to the last common commit between the source branch (your feature branch) and the target branch (the stable branch) and replay the changes on your feature branch iteratively for every commit missing from the source branch. If there is a conflict, you can fix the conflict, and do a git rebase --continue to commit your changes without any extra "Merge conflict" messages. Or if you are no longer interested in continuing the rebase process, you can easily abort with git rebase --abort.

One thing to note is that git rebase rewrites git history and if many people are working on the same branch, if can cause weird issues to happen. And I will admit that git rebase in the hands of someone who doesn't properly understand git can cause painful problems so please use with caution.

All in all, git rebase is one command in my git toolbox I find myself reaching for over and over again.

This isn't even all.

There was a scenario I had a few days ago that git rebase was fantastic for.

I had created a release branch by cherry-picking all the commits that I thought were going into production. After sharing the release branch with my colleagues, I received feedback that one commit I had cherry-pick wasn't cleared to go into production. I had to remove that commit from the release branch; Git rebase to the rescue. But this time, I used the interactive version git rebase -i ${commit-hash-before-main-commit-you-wanna-remove}.

When you use git rebase -i, an editor opens up with a list of all the commits and there are a handful of commands you can use to rewrite the git history; pick, drop, squash, reword, fixup, break, merge and so on. For my case, I needed to append the drop command in front of the commit I wanted to remove on the release branch. Save and the history will be rewritten and the dropped commit will be no more!

The git rebase command is one you should have in your git toolbox.

Powered By Swish