问题
Let's say I have a file with this content in master:
Line 1
Line 2
Line 3
Line 4
Now say I create and checkout a new branch called test. In this branch I change the file to this:
Line 1
Line 2
Line 3 Modified
Line 4
and I commit this and switch back to master. In master I change the file to:
Line 1
Line 2
Line 3
Line 4 Modified
and I commit. Now if I merge branch test into master, I get a conflict.
Why can't git auto resolve this, using the common ancestor? If I tell git to edit conflicts using BeyondCompare as the difftool, BeyondCompare autoresolves this without even telling the user, since this isn't a real conflict. Is there a way to get git to autoresolve these? I've tried the recursive and resolve merge strategies but neither do it.
It's an issue in our company because there are certain files where multiple developers change lines in close proximity and this causes many unnecessary conflicts when they pull.
回答1:
The reason that Git behaves like this is explained well in the answers to this question:
https://softwareengineering.stackexchange.com/questions/194788/why-doesnt-git-merge-adjacent-lines-without-conflict/378258#378258
Essentially, because you need the neighboring lines to provide context to the change (you can't just use line numbers, because something may have been added or deleted above), if the lines around it have changed you usually don't want Git to just naively continue with the merge. User Arsen7 gives a good example in that thread of how this could go badly wrong.
However, I agree with you that sometimes this is quite annoying, so I wrote a custom merge driver that can resolve such conflicts during merging/rebasing. It's designed to be interactive, because I always want to check that it's going to do the right thing before going ahead, but you could easily modify it not to be if you're confident it's going to work.
If you're interested, the script is available on GitHub under a GPLv3+ license:
https://github.com/paulaltin/git-subline-merge
回答2:
I stumbled upon the same problem, coming from SVN I found this very weird as well.
I do not have an answer to the why, but maybe this helps:
I use another merge tool (depending on what OS you are working on), i use meld diff for solving merge conflicts (I work on linux / ubuntu).
And you can set git to use this external merge application as well...
see http://meldmerge.org/
and google for 'use meld for git'
e.g. http://meldmerge.org/help/resolving-conflicts.html
回答3:
You can specify a custom merge driver that will not conflict in this case in a .gitattributes file that's in the repo.
来源:https://stackoverflow.com/questions/29276880/why-does-git-produce-a-merge-conflict-when-lines-next-to-each-other-are-changed