Search code examples
gitrebasetree-conflict

How do I avoid a conflict during rebase when a later commit resolves the conflict?


How to easily rebase branch with conflicts that are already fixed at the end of the rebase in git?

For example, I am on a feature branch and there are 2 commits in the master branch for the rebase.
First commit makes a conflict, but if the rebase joined both of the commits together, there would not be a conflict after the second commit.
So how to rebase it as a whole instead of rebasing it 1 by 1 and solving the conflicts twice?

I think it must be answered somewhere, but I can't find anything, because all the similar questions titles are vague.


Solution

  • You should squash the commits in question before you rebase onto master. Do this with an interactive rebase onto the most recent common ancestor:

    git rebase -i $(git merge-base master HEAD)
    

    That way, the combined commit, when represented as a patch, can be applied to master cleanly:

    git rebase master
    

    The original first commit you are trying to apply to master will conflict, plain and simple. You must be able to check out that "state" once it is finished, so Git makes you resolve the conflict. Your fundamental question boils down to "how can I apply a patch that contains a conflict without creating a conflict," which you obviously cannot do. By squashing the commits first, you remove the need to apply the conflicted commit.