Felix Rieseberg

Avoid Git Merge Conflicts During a Big Rebase

An original Nintendo Gameboy Pocket that has had a new RetroSix semi transparent shell applied.
Photo by Ben Griffiths / Unsplash

You made a bunch of commits on a feature branch right before going on vacation. Now that you've returned, master / main have moved on and Git seems to be unable to successfully rebase your changes without throwing massive merge conflicts in your face. If you made a real mess, you may have even merged master changes into your branch in between commits – and all hope seems lost. Good news: It's not. We can get all your changes into a clean single commit ready for a pull request.

If you're usually using git rebase main, you might want to look into git merge --squash. Let's walk through it.

1) Pull the latest version of main and checkout a new branch based on it. We'll be doing our temporary work here.

git checkout main
git pull
git checkout -b temp_work main

2) Pull in the changes from your ancient or messy feature branch. This command will take all your changes squashed together and stage them without creating a commit.

git merge --squash feature_branch

At this point, you might be getting a smaller number of unavoidable merge conflicts. Have faith that this is the smallest possible number of conflicts as you're skipping the many in-between commits you've originally created.

3) After fixing all remaining merge conflicts, commit your changes with an appropriate message. By default, Git will pre-fill your commit message with a helpful summary of where these changes came from – something that many tools like GitHub will pick up and continue to highlight in their interfaces.

git commit

4) If you'd like to re-use your old branch, you can now reset it to your temporary branch created above. In my workflow, I'd then force-push the changes up to GitHub before deleting my temporary work branch.

git checkout feature_branch
git reset --hard temp_work
git push -f
git branch -D temp_work

Good luck!