DEV Community

Cover image for fatal: refusing to merge unrelated histories
Fredrick Abisai
Fredrick Abisai

Posted on • Edited on

fatal: refusing to merge unrelated histories

Have you ever encountered this error fatal: refusing to merge unrelated histories., while working with git? Well, I have and it wasn't fun. How did I get to that error, you may ask yourself.

This was how it all went down:

I generated an angular project and as you know angular by default comes with git initialized. I then went to create a project in GitHub and added an MIT License file then I came back to add a remote URL by this command in my Angular project

   git remote add origin git@github.com:user/example-project.git
Enter fullscreen mode Exit fullscreen mode

Upon writing the git push origin main then the error occurred.

After a length and thorough research on this error this is what I discovered:

Causes

1. Incompatibility between local repository and remote repository.

This mostly occurs in new projects, if there are some changes in a new remote repository and you have a new repository locally which there are also changes which are not pushed. This is what happened to me.

2. Initiation of merge between two branches with no shared history.

3. Corrupted .git directory.

In a nutshell, this error commonly occurs in situations where we are integrating disparate repositories or initiating a merge between branches with no shared history.

What is the way forward then, you may ask. Well here is how to solve it and avoid the irritation the error brings:

Solutions

1. Use Allow Unrelated Histories Flag (--allow-unrelated-histories)

This is a flag which can be used when merging two different branches or when pulling from same branch with incompatible changes.

When merging, this flag can be used as follows:

 git merge --allow-unrelated-histories <branch-name>
Enter fullscreen mode Exit fullscreen mode

When pulling, this flag can be used as follows:

git <branch-name> origin master --allow-unrelated-histories
Enter fullscreen mode Exit fullscreen mode

2. Create a new Commit

Create a new empty commit that connects unrelated branches then merge those branches.

  • Empty Commit
git commit --allow-empty -m "Merge unrelated branches"
Enter fullscreen mode Exit fullscreen mode
  • Merge unrelated branches
git merge <branch-name>
Enter fullscreen mode Exit fullscreen mode

But how do we prevent this error from totally occurring?

Prevention

1. Repository Initialization

When setting up a new repository, it’s advisable to initialize it using an existing project. This approach links their histories, helping to prevent the issue of unrelated histories.

More information can be found here.

Thank you for reading! Until next time βœ‹

Top comments (0)