OK, don’t panic. I know that rebasing has a very scary reputation, but it is actually pretty straight forward. Before we begin, please note that rebasing has very little to do with Interactive Rebasing covered in part 3 of this series.
The goal of rebasing is to maintain a clean history of commits. Rather than having many merges cluttering up your history, Rebasing allows you to “merge” your feature branch onto the main branch.
This is key: normal merging merges your branch into the main branch, while rebasing merges it onto the main branch.
The rest of this post will be spent explaining what I mean by that. Suppose your repo looks like this very simplified diagram:
Notice that Feature 1 branched off Main but Main then had a new commit added. You can’t do a Fast Forward merge here, you are reduced to adding a merge commit –shown as A in this diagram:
This can clutter your history with merge commits that can make it harder to follow the progression of your feature branch. Rather than doing this, however, you can rebase your Feature1 branch. That causes the history to show Feature1 as branching not from the second commit in Main but rather as having branched from the tip of Main (the latest commit):
This is called rewriting history. It is typically drawn like this (which is the same thing re-envisioned)
You can see that from this perspective Feature1 is pretending that it was branched off of the third commit from Main, and gives you a clear path from Feature1 to Main, avoiding skipping any of the commits and, more important, avoiding creating a merge commit in the combined branches.
To do this, check out Feature1 and rebase it onto main
git checkout feature1 git rebase main
Note: you do this on your local machine, never where there may be shared code (e.g., origin).
You can do this again and again on your local machine, but sooner or later you’ll need to merge your rebased branch into the commits on origin.
That’s all it takes. — Not as scary as you may have heard.