- I'm working on a collaborative project
- I make a feature branch!
- I do some work on the branch and some more work on the branch
- Meanwhile, Master has new work on it and my feature branch doesn't have this work!
- I merge master into feature and this results in a new merge commit
- I keep working on my feature branch and a coworker adds new work to master
- I merge master in to my feature branch and this results in yet another merge commit!
- The feature branch has a bunch of merge commits. If the master branch is very active, my feature branch's history is muddied
- We get a much cleaner project history.
- No unnecessary merge commits!
- We end up with a linear project history.
- We can instead rebase the feature branch onto the master branch. This moves the entire feature branch so that it BEGINS at the tip of the master branch. All of the work is still there, but we have re-written history.
- Instead of using a merge commit, rebasing rewrites history by creating new commits for each of the original feature branch commits.
- It is not going to change the master branch, instead it is going to rewrite history by taking the feature branch commits and creating new ones that are based on the originals and putting them all at the tip of the master branch
- We are BASING that branch on the tip of the master branch
git switch feature git rebase master
There are two main ways to use the git rebase command:
- as an alternative to merging
- as a cleanup tool
- Never rebase commits that have been shared with others. If you have already pushed commits up to Github...DO NOT rebase them unless you are positive no one on the team is using those commits.
- You do not want to rewrite any git history that other people already have. It's a pain to reconcile the alternate histories!
- Sometimes we want to rewrite, delete, rename, or even reorder commits (before sharing them). We can do this using git rebase!
git rebasewith the -i option will enter the interactive mode, which allows us to edit commits, add files, drop commits, etc. Note that we need to specify how far back we want to rewrite commits.
Also, notice that we are not rebasing onto another branch. Instead, we are rebasing a series of commits onto the HEAD they currently are based on.
git rebase -i HEAD~4 # go back four commits
In our text editor, we'll see a list of commits alongside a list of commands that we can choose from. Here are a couple of the more commonly used commands:
- pick - use the commit
- reword - use the commit, but edit the commit message
- edit - use commit, but stop for amending
- fixup - use commit contents but meld it into previous
- commit and discard the commit message
- drop - remove commit