Your Git tool might sometimes refuse to merge branches, with the error: “fatal: refusing to merge unrelated histories”. We are showing how to overcome the problem.
1 Problem
Sometimes during work with GitHub, you will get into a situation where you created initial branches on both sides, local and remote. Naturally, you would like to merge the branches, but your Git tool might refuse to merge them because branches have “unrelated histories.” I will show the problem that appeared when I was using GitHub and SourceTree but can happen with other tools and remote repositories.
The problem that I had, that just happened, but I am sure will happen again to me and to other people, was that I during work finished with two initial branches created: main and master. The “main” branch is by default created by GitHub and there is a readme file there. The branch “master” is created by default by SourceTree and my code is in it.
Ok, there is no need to have two branches here, let’s merge them and get rid of one of them. Let’s keep GitHub default branch “main” and delete “master.”
But there is a problem when you try to merge those two branches:
It gives an error: “fatal: refusing to merge unrelated histories”
2 Solution
Since our two branches do not have a common ancestor commit, SurceTree thinks we are doing something wrong. But we know we are right and want to force it.
2.1. Forcing merge
I looked and it says in [1] that you cannot resolve that from SourceTree GUI. So, we need GitBash to run the command line Git commands. Explanation of problem and instructions are at [2].
We need to run “git merge <branch-name> --allow-unrelated-histories
”
So, you can open GitBash from SourceTree (Terminal button), and execute the command. You will be prompted to enter a commit comment in the separate text editor. Then merge will continue.
And here is what merged branches now look like:
References