Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a seemingly possible merge using Git have conflicts?

Tags:

git

In short, why does a file foo.txt having content

a
b

failed to merge with the branch with foo.txt having content:

a

c

?

The longer version is: to experiment with Git and merging, I did the following:

  1. mkdir a new directory and cd into it and git init
  2. create a file foo.txt and add the line a (first time just like that, and second time with 2 empty lines after a)
  3. commit it, and now git checkout -b feature and git checkout -b sprint (so as far as I know, it makes no difference to do it in a row instead of first switching back to master and create sprint, because branches are created based on commitID, and either case, they are exactly the same.
  4. Now git co feature and make the file look like a and then empty line and then c on the third line
  5. Now commit it, and do git checkout sprint and make the file look like a and then next line b on its own.
  6. Now commit it, and now do a git merge feature

and supposedly, the merge could have succeeded, with the content

a
b
c

but why did it fail? Instead of guessing "maybe the lines are too close", can a more definitive answer from docs or reference be given?

I also tried adding an empty line between a and b, and between b and c so they are more spaced out, but without the initial empty lines in the first version of foo.txt, and the result was the same: merge conflict.

like image 951
nonopolarity Avatar asked Jan 28 '26 19:01

nonopolarity


1 Answers

Git checks for differences on a line level. So lets say your fist version of the file looks like this:

a

Now you create a second version of the file on a branch named feature:

a
b

In this version you have changed two lines. Why two lines do you think? Well there was a newline character added \n at the end of a.

In the branch sprint you added another version of the file:

a

c

Now you modified three lines.

If you now try to merge the two modifications git recognizes that you changed line 1 and 2 in both commits, so git doesn't know which version to take and a conflict occurs.

like image 100
Sascha Wolf Avatar answered Jan 31 '26 09:01

Sascha Wolf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!