Merging Branches

Merging is carried out when we want to combine two branches, typically a feature branch into the master branch. Git has two merging strategies, fast-forward and three-way.

A fast-forward merge is carried out when there have been no changes to the receiving branch since the branch to be merged was created. It just moves the receiving branch pointer. A three-way merge is done when changes have been made to the receiving branch. In this case a new commit is made for the merge. Git will automatically choose the type of merge, we don’t have to do anything.

To perform a merge, we first checkout the receiving branch and then use the git merge command. Once the merge is completed, it is safe to delete the merged branch. To perform a merge, run the following commands:

git checkout <receiving-branch-name>
git merge <merging-branch-name>
git branch -d <merging-branch-name>  # Optional but usually done

When carrying out a three-way merge, git creates a new commit in the receiving branch with two parents. The previous commit in the receiving branch and the last commit in the merging branch. It moves the receiving branch pointer and the head to the new commit, but leaves the merging branch pointer alone. Again, the merging branch can be deleted.

When we perform a merge, we can get a merge conflict. This means that same parts of the same files have been edited in different branches. It is not possible to get merge conflicts in fast-forward merge, only in a three-way merge. Git will stop the merge when it detects a conflict as they have to be resolved manually.  We have to decide which changes we want to keep. Existing, new, both, or none. We make the necessary edits in our favourite editor and then resume the merge. VS Code makes it very easy to resolve conflicts. When the conflicts are fixed and added to the staging area, run git commit.

If we examine the staging area with git ls-files when we have conflicts, we will see three versions for each working directory file. Version 1 is the previously committed file, version 2 reflects the changes in the receiving branch, and version 3, the merging branch. Based on these three versions, git shows us the conflicts in the working directory.

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.