gitmergemerge-conflict-resolutionmerge-conflict

Git - how git merge works


I am trying to learn about git merge and I am facing a merge conflict.

Here is my branch structure:

enter image description here

I am modifying and tracking just one file file.txt.

At commit C, this is the content of the file is

text in first main
text in second main

The content of the file at commit Main is:

text in first main
text in second main

text in fourth main

And at commit Dev, the content of the file is:



text in first dev

When I am doing a merge of main into dev, I am getting a merge conflict

<<<<<<< HEAD
text in first main
text in second main

text in fourth main
=======


text in first dev
>>>>>>> dev

I don't understand why is there a merge conflict. There is data present in the file in main at line 1,2 and 4. And in dev, the file contains text at line 3. Shouldn't the merge create a single file with data in line 1, 2 and 3 and 4 which looks like:

text in first main
text in second main
text in first dev
text in fourth main

I have tried to understand how merge in git works but I am not able to understand it well enough to know why there is a merge conflict in my git repo as shown above. Can someone please explain me why is it happening?


Solution

  • When merging, git is not so much looking at the line numbers. It looks at what changes you made.

    On Dev the change (from C, the shared root) is that you deleted the content of the file and added three new lines. While on main, the lines are preserved and modified.

    When merging git can't do both of this changes at the same time. Either you replace the lines (Dev) or you modify them (Main). That's why you get the merge conflict.