简体   繁体   中英

How does git merge two branches automatically?

My question is based on the example at: https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging

在此输入图像描述

Taken the example:

  1. Set variable = 2 in Commit C2, then change to variable = 4 in C4 and back to variable = 2 in C5
  2. Make a git merge master <branch of iss53> , resulting in Merge made by the 'recursive' strategy.
  3. The variable is 4.

But why?

I expected: As the ancestor sets variable = 2 and the commit (iss53) also sets variable = 2 the result after merge should be 2. Because the common ancestor and the newest version has set variable = 2

Is this behaviour depending on the merge strategy?

edit : I forgot to mention, that I changed variable = 3 in C3. But the result is the same.

I don't know if the steps you listed are verbatim what actually happened, but if so, then in commit C3 the variable still has the value 2, and in fact the variable's value is unchanged since commit C2 in the iss53 branch. You then merged master into iss53 . This brought in what Git perceived to be a change coming from a feature branch, that change being that the variable now has the value 4. Git kept the version coming from master , and this is the behavior I would typically expect from Git's auto merge algorithm.

In the case where both branches changed the value of the variable, then there would be a merge conflict. For example, if in commit C3 the variable were changed to 5, then Git would not know whose version of the truth to default to, and it would therefore not auto merge, instead marking that line as a merge conflict.

It's not a matter of which revision is chronologically newer. It's a matter of the content of the branches that you are merging and the content of the common ancestor.

C2 says 2, C5 says 2 (so no change from C2), C4 says 4 (there's a change) so git will keep it to be 4 after merging.

You might have funky scenarios like setting the value to be 6 on C3, then 2 on C5..... in this case there's again no change from C2 so the end result would be 4 because there's no change between C2 and C5 (even though there was a change in the middle).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM