Git merge is the process of combining the recent changes from several branches in to a single new commit, this commit points back to these branches. Because a branch is a named reference points to a commit. We say merge branches, though under the hood we are actually merging commits.

Fast-forward merge

A fast-forward merge can happen when there is a linear path from the current branch tip to the target branch (two branches are never actually diverged). In fast-forward merge, there is no actual merging. Git simply reset the current branch tip to the target branch tip.

3-way merge

However, a fast-forward merge is not possible if the branches have diverged. When there is a diverged path, Git performs 3-way merge. 3-way merge uses a dedicated commit to tie together two histories. The nomenclature comes from the fact that Git uses three commits to generate a merge commit: two branch tips and their common ancestor. By performing 3-way merge, you have to resolve any conflict between the two tips and the common base.

Git 3-way merge algorithm

The 3-way merge algorithm allows Git to merge branches while preserving the history and managing conflicts effectively.

  1. Identify the merge base Git locates the common ancestor of the two branches. Technically, this is the first commit that is reachable from both branches. This commit is called the merge base.
  2. Calculate two diffs Git calculate two separate diffs, these diffs represent the changes made on each branch since they split from the merge base:
  • Diff 1: Changes form the merge base to the tip of the current branch (branch you are merging into).
  • Diff 2: Changes from the merge base to the tip of the branch being merged.
  1. Generate patches based on diffs Git creates patches from these diffs. A patch is a representation of changes that, when applied to a code base, will modify to a new state. These patches contain information about line added, removed, or modified in each branch since the merge base.
  2. Apply patches Git starts with the content at the merge base, it then apply the patches (changes) from the current branch. Simultaneously, it applies the patches from the branch being merged. The algorithm attempts to integrate these changes into a new merge commit.
  3. Resolve conflict (if any) If the changes from both branches modify the same lines, Git cannot automatically resolve these conflicts, you have to manually resolve the conflicts.

Back to parent page: Git

DevOpsVCSGitGit_InternalsGit_BranchGit_Merge

Reference: