Home > OS >  Why does git merge need a merge base?
Why does git merge need a merge base?

Time:07-29

I've heard that git merge involves the following steps:

  1. Finding a merge base
  2. Find diff between the current branch and the merge base
  3. Find diff between the target branch and the merge base
  4. Combine the two diff's from steps 2 and 3

I wonder why git merge doesn't directly find the diff between the current branch and the target branch to create the final merge commit. Would that not be more straightforward?

A related point is that the choice of the merge base is not very crucial. At least in theory, every commit can be used as the merge base and the final merge commit will be exactly the same.

CodePudding user response:

Consider the following scenario where you have commits A, B, and C

A - B
  \
    C

Commits B and C contain some unrelated changes. And then you want to merge C to B.

When comparing to merge base A, git can easily tell what changes B and C made individually, and can auto merge the changes. If there was no merge base, how could git tell how to do the merge? Git would only see that B and C contain different things - there would be no way to tell which side is the "new" thing you want to merge. Essentially, you would have to manually merge everything.

CodePudding user response:

I wonder why git merge doesn't directly find the diff between the current branch and the target branch to create the final merge commit. Would that not be more straightforward?

It would be, but it only works when you want the final state to be the same as one of the branches. If two branches have diverged, with one adding feature A and the other adding feature B, the desired merge is to have both features. Applying the diff A..B to A just gives you B, not A B.

And when the straightforward case is compatible with Git’s representation - that is, you’ve only made change B on top of A – all commits on A will already be part of B and the merge base will indeed be simply A.

  • Related