Search code examples
gitgit-mergegit-merge-conflict

Why git cannot merge a text file with different changes in different lines?


I was wondering if some of you have faced this issue.

I have a txt file in my main branch. I added 4 lines

Line1
Line2
Line3 
Line4

Then I created 2 branches from the main. feature1 and feature2.

In feature1 I changed the first line from Line1 to Line1changed.
In feature2 I changed the second line from Line2 to Line2changed.

I merged feature1 into main branch without any problem, then when I tried to merge feature2 into main branch a conflict was detected.

$ git merge feature2
Auto-merging file.txt
CONFLICT (content): Merge conflict in file.txt
Automatic merge failed; fix conflicts and then commit the result.

I would like to know why.

$ git diff
diff --cc file.txt
index cd3d4bb,bb25698..0000000
--- a/file.txt
+++ b/file.txt
@@@ -1,4 -1,4 +1,9 @@@
++<<<<<<< HEAD
 +Line1changed
 +Line2
++=======
+ Line1
+ Line2changed
++>>>>>>> feature2
  Line3
  Line4

Solution

  • The default merge configuration will auto-merge if changes don't overlap. But "overlap" is defined in a way that includes adjacent lines. So for example, when you make a change to line 1, that would overlap another change on line 1 or line 2 (as well as insertions before or after line 1).