So heres the scenario, You’re working late into the night trying to finish that bug for this project that needs to be released the next day. You’ve got this stubborn bug on the staging server which you just can’t fix. You have to make commits and keep pushing up the the server in a vein attempt to fix the issue.
After 5 tries, It finally works. Horah! Lets go out and Celebrate. But wait, Now you’ve got a bunch of commits which just documents tonights frustrations and failures. If, at this point you don’t know what I’m talking about, commit logs from last night will shine some light on the situation.
So how can you get rid of those pesky commits, cleaning your history and pretending you got straight to the answer and didn’t spend 3 hours debugging only to find you were missing a semicolon?
Enter Git rebase.
A practical example
Heres a really simple example to demonstrate.
So we’d really like to erase commit 5 to 7 from the face of the planet. It would be so much better without them.
So how does git rebase help?
With git interactive rebase (using the -i flag) you can pick and choose which commits you want to keep, which need rewording and which to delete. Its super handy.
So here we drop (delete) commits 5 to 7 and amend the commit message for commit 8. Save and quit.
At this point, You should be all done. Git will delete the commits and create new commits for any commits upstream (this is important to know. See Commit 8a below).
But I’ve got Merge errors!
Ok, sometimes things aren’t that simple. But its not the end of the world.
You’ll get an error message similar to the one above which says whats the problem and explains what you can do to fix it. Skipping it will not apply your changes that are causing the conflict and abort will stop the rebase process completely.
To continue you have to fix your merge errors, save and commit. This will be the commit message for commit 8a. You will see this one in the git log.
Once you’ve committed, continue the rebase and the changed will be finalised.
Thats it. Job done.
Rebasing isn’t all that hard. It just seems scary when you haven’t done it before. I’m not advising you do this every time you run into issues, but it helps when you have chains of angry commits.
Hope this helps.
You may also like my post about git push set-upstream