Why can't Git merge file changes with a modified parent/master?
I have a file with one line in开发者_StackOverflow社区 it. I create a branch and add a second line to the same file. Save and commit to the branch. I switch back to the master. And add a different, second line to the file. Save and commit to the master. So there's now 3 unique lines in total.
If I now try and merge the branch back to the master, it suffers a merge conflict.
Why cant Git simple merge each line, one after the other?
My attempt at merge behaves something like this:
PS D:\dev\testing\test1> git merge newbranch
Auto-merging hello.txt
CONFLICT (content): Merge conflict in hello.txt
Automatic merge failed; fix conflicts and then commit the result.
PS D:\dev\testing\test1> git diff
diff --cc hello.txt
index 726eeaf,e48d31a..0000000
--- a/hello.txt
+++ b/hello.txt
@@@ -1,2 -1,2 +1,6 @@@
This is the first line.
- New line added by master.
-Added a line in newbranch.
++<<<<<<< HEAD
++New line added by master.
++=======
++Added a line in newbranch.
++>>>>>>> newbranch
Is there a way to make it slot lines in automatically, one after the other?
Let's say the file branch A looks like:
First line
Branch A's second line
And branch B looks like:
First line
Branch B's second line
When you merge, there are two different ways to resolve it. Here's one way:
First line
Branch A's second line
Branch B's second line
Here's another way:
First line
Branch B's second line
Branch A's second line
Git has no idea which one of those two options you prefer, or if either are even acceptable merges.
There is a git merge strategy called union
that can be configured from the .gitattributes
config file that will do this for you, but you will have no control over the order the conflicting lines will end up in in the merged file, and no conflict markers to indicate where this occured.
You could also define a custom merge strategy that could use some specialised knowledge about the structure of the files to determine the correct order.
let's say you have this line:
printf(something);
in branchA, you make it:
while(x < 5)
printf(something);
in branchB, you make it:
if(y>10)
printf(something);
How can you merge this, or rather, would you trust the merge result that a tool created for this?
I can tell you why it can't merge the two - according to git, line 2 of FileA is "such and such" whereas line 2 of FileB is "something else". According to git therefore, it is trying to create File from FileA and FileB with one line having two possible values. It can't decide which one you want, so it dumps them both and gets you to fix it.
精彩评论