I’ve heard a few people say you should avoid using git rebase
. That’s crazy! Like many commands, it has a use case and is actually pretty awesome. Rebase allows you to modify your git history and move or update commits. Just some of the ways to use git rebase
:
Keeping branches up to date without merge commits
Merge commits can make your history look a little janky. A very simple rebase can keep pesky merge commits out of your PRs and history. The occasional one isn’t awful, but if a branch is worked on by multiple people over several months, the number of merge commits can become unruly.
Let’s say you’re working on a branch based off of master and want to pull in some changes. Usually that’s done via git pull origin master
. Instead, git rebase origin/master
gets the updated version of master and applies your changes one-by-one at the end. High-five! Now you’re up to date. :raised_hands:
Never fear overwriting anything. Merge conflicts can be resolved as part of the rebase process.
Changing the source branch
Sometimes you’ll need to move commits between branches without a merge. For a single commit, cherry-pick
is the way to go, but moving a bunch of commits is better handled through rebasing. The git book has a great example of rebasing onto other branches.
And, if you’re interested in grabbing a particular range of commits, there’s a way to do that too.
Making better commits
You should be committing early and often, which means you may end up with nonsensical commit messages like: “Did a thing,” “Made it work,” and “Whoops.”
That’s fine! Rebasing allows you to change these commit messages to something actually useful. You can even squash them into fewer, more logical commits. :tada:
PRs with fewer commits are easier to review and keep your history clean. That said, don’t go squash-happy and make every project a single commit.
When not to use rebase
Rebasing is awesome, but tread carefully. Avoid rebasing on branches that represent production (like release branches), or ones that other people work on. Changing the history can cause serious grief if not communicated well.
You’ll almost never rebase the master branch (or whatever your source of truth is). Hopefully you aren’t working too often on the master branch anyway.
As you’re getting more comfortable with the tool, test your rebases out on separate branches. Worst case scenario: You can delete the branch.
Questions? Ping me at @alexjlehner.