Skip to main content

When does a merge conflict happen?

What is merge conflict

Merge conflict arises when you have two people changing the same line in a file OR if one person deleted the file but the other modified (effectively keeping that file), then you tried to integrate the changes together via either git merge or git rebase. Git cannot determine which one of the changes is correct.

The merge process will come to a halt and need the developer's manually intervention in order to proceed with the merge.

Creating merge conflict with git merge

To create a merge conflict with git merge it is relatively simple, say you are on the main branch, spawn off a branch called feature-a. As of now, main and feature-a are in sync because no commits have been made yet.

Now say in main you create a file named "lmao", and appended "this is cool" to the file. Stage it and commit it.

Now checkout into feature-a and create the same file named "lmao", but this time append "this is not cool" to the file.

You see that we created the same file for both branches, but the content they have are different and they are both at line number 1.

Now if you attempt to say merge feature-a into main now by doing git merge at main, you will get a merge conflict, because git sees that both of the branches are changing the same file at the same line, and it doesn't know which one of changes do you want.

Creating merge conflict with git rebase

Basing off from the same scenario as above, if you are currently at feature-a branch and say you want to integrate the changes that your co-worker have been making in main. If you run git rebase main you will also run into merge conflict.

But wait, isn't git rebase "replaying" the commits that you have made after it moves the feature-a branch to sync with main? Well yes, but you will have to define what "replaying" is actually doing.

Under the hood, git rebase uses git cherry-pick, which will let you add arbitrary commits to the current checked out branch. How does git cherry-pick work underneath? It internally finds the diffs and then apply the patches  which is the same exact way how git merge merges. So git rebase is actually using git merge in a way under the hood, which as you know will have merge conflicts.

If you want to read more about why git rebase results in merge conflicts this is a good stackoverflow question: Link