gitgithubgit-mergegit-fetch

Impossible to merge branch: refusing to merge unrelated histories


I created a new remote repo ('myRepo') on Git. I checked the checkbox 'add a README.md', which also make a commit on this 'myRepo' repo.

Then I create a new folder, where I added somes files and did :

git init
git add .
git commit -m "init"
git remote add origin https://github.com/jozinho947/myRepo.git

# get the READ.me fetched on the 'origin/master' branch locally
git fetch

# get the READ.me merged in my local 'master' where i'm pointing
git merge origin/master

And then I have this error :

fatal: refusing to merge unrelated histories

I don't understand why I can't do this, and how to fix this.


Solution

  • The remote copy of your repo has a root commit, with no parent -- the 1st commit with a README.md file.

    With the actions you performed locally, your local repository also has a root commit with no parent.

    git merge refuses to work because it cannot find a common ancestor to these two commits.


    You probably want to replay your commits one after the other, use git rebase instead of git merge :

    git rebase origin/master
    

    This should apply your local root commit on top of the "README" commit.


    If you want to replay them in the opposite order (remote commit on top of your local commit) : use git cherry-pick origin/master. You will then need to force push your master branch.

    If you have good reason to keep two root commits in your repo : you can use the --allow-unrelated-histories option of git merge.