29 January 2020

Git error on new repository: fatal: refusing to merge unrelated histories

Scenario

You have a local project you want to add to a git cloud repository (like github).
You create an empty git repository on the platform.
On your local system you add the repository to your project, for example by doing:

$ cd myProject
$ git remote add origin https://github.com/myAccount/myProject.git
$ git push -u origin -all
error: failed to push some refs to https://github.com/myAccount/myProject.git
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.


This should work without errors!? Well, let's follow the suggestion...

$ git pull origin master
warning: no common commits
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
From https://github.com/myAccount/myProject
 * branch            master     -> FETCH_HEAD
 * [new branch]      master     -> origin/master
fatal: refusing to merge unrelated histories


Cause

You get this error if you created the repository on the git cloud repository with one or more files in it, for example a README.md or a license file.

Solution

$ git pull --allow-unrelated-histories origin master
 From https://github.com/myAccount/myProject
 * branch            master     -> FETCH_HEAD
CONFLICT (add/add): Merge conflict in README.md
Auto-merging README.md
Automatic merge failed; fix conflicts and then commit the result.


Resolve the merge conflicts, then

$ git commit -a
$ git push -u --allEnumerating objects: 89, done.
Counting objects: 100% (89/89), done.
Delta compression using up to 8 threads
Compressing objects: 100% (81/81), done.
Writing objects: 100% (87/87), 25.17 KiB | 560.00 KiB/s, done.
Total 87 (delta 32), reused 0 (delta 0)
remote: Resolving deltas: 100% (32/32), done.
To https://github.com/myAccount/myProject
   efa6140..4dc0893  master -> master
Branch 'master' set up to track remote branch 'master' from 'origin'.



All's well now!

No comments:

Post a Comment