I learned this from Isaac Hildebrandt.
If main has been updated, my inclination has always been to pull from main into my feature branch. However, this is not best practice:
- Pulling from main lines all commits in history order.
- Your 'source of truth' will remain at an older main instead of the new one.
- If you happen to need to revert main, it's almost impossible--there isn't a clean line of where main is.
The thing to remember is the whatever main has is waayyyy more important than your branch. Here is why rebasing is much better:
- Rebasing takes your branch, scoops up your commits, and makes the newest main the foundation of your branch.
- Then it asks if you want to apply your commits.
- Then you resolve merge conflicts.
- Thus your branch always stay based on the latest main instead of some pieced together main.
Here is how to do that:
- (Optional) If you are worried about accidentally messing up your branch, you can always back it up by making a backup branch.
- (Optional) You can squash all of your commits together so that you only have to resolve merge conflicts on one commit instead of going through the same (or almost the same) files for a million commits:
git reset --soft HEAD~<number of commits to squash>
- Rebase to main.
- Command Line:
git rebase origin/main
- VS Code: Source Control ... → Branch → Rebase Branch... → origin/main
- Command Line:
- Pick if you want to keep all of your commits or merge them, etc.
- Resolve merge conflicts for each commit you keep.
- "Incoming" changes will be from your feature branch.
- "Current" changes will be from the latest main branch.
- Force push back to your remote branch. (It's safer to do this command line only.)
git push -f origin <your-branch-name>
![[attachments/git-merge-vs-rebase1.png]] Differences Between Git Merge and Rebase — and Why You Should Care
![[attachments/git-merge-vs-rebase2.png|300]] Git Merge vs Rebase