If branches have divergent commits, a fast-forward merge is not possible. In this case, Git will perform a three-way merge. Here’s how it works:
Steps in a Three-Way Merge:
-
Identify Common Ancestor: Git finds the most recent common ancestor commit of the two branches being merged. This is the last commit that both branches share.
-
Compare Changes: Git compares the changes made in both branches since the common ancestor:
- Changes in the target branch (e.g.,
master). - Changes in the source branch (e.g.,
feature-branch).
- Changes in the target branch (e.g.,
-
Merge Changes: Git combines the changes from both branches. If there are no conflicting changes, Git automatically creates a new merge commit that incorporates the changes from both branches.
-
Resolve Conflicts (if any): If there are conflicting changes (i.e., changes made to the same lines in both branches), Git will mark these conflicts in the affected files. You will need to manually resolve these conflicts before completing the merge.
Example Command:
To merge branches with divergent commits, you would use:
git checkout master
git merge feature-branch
Visual Representation:
Before the merge:
A -- B -- C (feature-branch)
/
D -- E -- F (master)
After the three-way merge:
A -- B -- C
/ \
D -- E -- F -- G (master)
Here, G is the new merge commit that combines the changes from both branches.
Summary:
When branches have divergent commits, Git creates a new merge commit to maintain the history of both branches, allowing you to see how the project evolved over time.
