Refusing to merge unrelated histories git ошибка

Последнее обновление Сен 22, 2021

Git

fatal: refusing to merge unrelated histories

“ ошибка Git которая возникает, когда два не связанных между собой проектов объединяются (то есть проекты, которые не знают о существовании друг друга и не соответствующие фиксации истории).

5534126872461312

Рассмотрим следующие два случая, которые выдают эту ошибку:

  • Вы клонировали проект, и .gitкаталог каким-то образом был удален или поврежден. Это приводит к тому, что Git не знает о вашей локальной истории и, следовательно, заставляет его выдавать эту ошибку, когда вы пытаетесь отправить или извлечь из удаленного репозитория.

  • Вы создали новый репозиторий, добавили в него несколько коммитов , и теперь вы пытаетесь извлечь из удаленного репозитория, который уже имеет некоторые свои коммиты. Git также выдаст ошибку в этом случае, так как он понятия не имеет, как связаны два проекта.

Решение

Ошибка устраняется путем переключения переключателя allow-unrelated-history. После команды git pullили git mergeдобавьте следующий тег:

git pull origin master --allow-unrelated-histories

Более подробную информацию можно найти здесь, на официальной документации Git и .

Источник записи: https://www.educative.io

I am using the rebase for years and I had never encountered such a problem. However, your first problem is, that you try to do it directly on the remote branch development from the remote repository, called origin. That is literally wrong because rebase is a dangerous command, that restructures the git history. Having said that, you should first try on your local repository and pushing it only, if it works for you as expected.

So, my usual rebase workflow looks like following (but please keep in mind, that you should not use rebase on branches, which you are not the only one committee. For such branches, use simply merge and resolve conflicts, if applicable):

  1. make sure you have a clean working tree (no uncommit changes)
  2. checkout to the branch you want to rebase onto (for instance, let’s say it’s master; as a one-line command): git checkout master && git pull origin master && git checkout development
  3. Do the actual rebase: git rebase master
  4. If it’s done and everything works as expected, push it to your remote. For doing so, you need to force it, because the remote host already has the history in another order, the remote would answer with nothing to push. So, we need to say «my local version of the history is correct, overwrite everything on that remote branch using my local version of the history»: git push -f origin development

As I already mentioned, keep in mind, that rebase manipulates the git history, that is usually a bad thing. However, it’s possible to do that on branches, where no one else commits to. In order to keep the branch pull-able for the other developers, use another merge strategy like merge itself, squash or cherrypick. So, in other words: Rebase shouldn’t be your tool on distributed development. It works fine for you if you are the only one who works on this repository.

We use the feature branch strategy. In this, I usually use rebase in order to get the «updates» from the other developers, that happened in the meantime on the master branch. Doing so, it reduces the size of commits that are visible in a pull request. Therefore, it makes it easier for the code reviewer to see my changes made in this feature branch.

What is the ‘fatal: refusing to merge unrelated histories’ error?

The fatal: refusing to merge histories error is a fairly common Git error. It appears when a developer tries to merge two unrelated projects into a single branch.

This error appears when the branch has its commit histories and tags incompatible with the pull request or clone.

Why does ‘fatal: refusing to merge unrelated histories’ happen?

Here are some common scenarios where fatal: refusing to merge unrelated histories can occur.

  1. You have a new Git repository with some commits. You then try to pull from an existing remote repo. The merge becomes incompatible because the histories for branch and remote pull are different. Git sees the situation as you trying to merge two completely unrelated branches, and it doesn’t know what to do.
  2. There’s something wrong with the .git directory. It may have been accidentally deleted at some point or got corrupted. This can happen if you’ve cloned or cleaned a project. Here the error occurs because Git doesn’t have the necessary information about your local project’s history.
  3. The branches are at different HEAD positions when you try to push or pull data from a remote repo and cannot be matched due to a lack of commonality.

How to resolve ‘fatal: refusing to merge unrelated histories’

There are two ways of solving the fatal: refusing to merge unrelated histories error.

Option 1: Use ‘–allow-unrelated-histories’

One way to solve the issue is to use the --allow-unrelated-histories git flag.

Here the git command will look something like this: git pull origin master --allow-unrelated-histories.

You can substitute origin with the remote repository you are pulling from. You can also replace the master branch with whatever branch you want the pull request to merge into.

The idea behind --allow-unrelated-histories is that git lets you merge unrelated branches. This git flag works seamlessly when there are no file conflicts.

However, in reality, at least one thing pops up, and you will need to use the normal Git resolution flow to resolve them.

Here is an example of what a common conflict may look like when trying to merge branches:

 Auto-merging package.json
 CONFLICT (add/add): Merge conflict in package.json
 Auto-merging package-lock.json
 CONFLICT (add/add): Merge conflict in package-lock.json
 Auto-merging README.md
 CONFLICT (add/add): Merge conflict in README.md
 Auto-merging .gitignore
 CONFLICT (add/add): Merge conflict in .gitignore
 Automatic merge failed; fix conflicts and then commit the result.

Option 2: unstage, stash, clone, unstash, and then commit

The alternative (and longer) way of fixing the fatal: refusing to merge unrelated histories issues is to unstage your current commits, stash them, clone your required remote repository, and then place your stashed branch contents into the new clone.

This will ensure that any conflicts that you may encounter in the code are addressed before merging and prevent application errors from occurring.
To unstage all the files in your last commit, use the following git command: git reset HEAD~.

To stash your unsaved files, use the following git command: git stash.

This will give you a clean working tree to pull your remote repository into. Once you’ve successfully pulled into your branch, you can unstash your files, commit them as a separate commit and resolve any file conflicts that you may have.

To unstash your files, use git pop. This will move the changes stashed and reapplies them to your current working copy.

Alternatively, you can use git stash apply to add the changes to your current working copy of code.

Here is a quick summary of differences between git stash apply and <code”>git pop:

  • git pop: ‘pops’ the changes from the stash and applies them to the current code
  • git stash apply: keeps the changes in the stash and applies the changes to the current code

How to prevent ‘fatal: refusing to merge unrelated histories’

The easiest way to prevent the fatal: refusing to merge unrelated histories error is to avoid pulling remote repositories into branches that already have commits on them.
However, sometimes you just want to keep the commits. One way to prevent the error is to create a brand new branch, pull your required code in, and then manually merge your local branch into your main flow.

Here is a git example of the flow:

# branch A is where your current code is
# clone in your remote repo into a new and separate branch. 
# For our purposes, it's branch B
 ​
git clone -b [branch] [remote_repo]
 ​
# to merge A into B, you need to be on B
# merge your branches together
git merge A

The only thing about merges is that if there is a conflict in the code, there is no way around it other than resolving it as usual.
Here’s what your merge branch looks like on Git:

          C1---C2---C3 branch A
                      
  Ca---Cb---Cc---Ce---Cf branch B

Kubernetes Troubleshooting with Komodor

The above guide should help you through the troubleshooting steps you need to follow in order to resolve the fatal: refusing to merge unrelated histories Git error.

This is, of course, just one of many Git errors that you may come across in your K8s logs. Such deceptively minor and often easy-to-miss issues can cause serious issues and detecting them could be time-consuming, stressful, and often downright impossible.

This is why we created Komodor. Acting as a single source of truth (SSOT), Komodor streamlines and shortens k8s troubleshooting processes. Built by devs for devs, Komodor offers:

  • Change intelligence: Every issue is a result of a change. Within seconds we can help you understand exactly who did what and when.
  • In-depth visibility: A complete activity timeline, showing all code and config changes, deployments, alerts, code diffs, pod logs and etc. All within one pane of glass with easy drill-down options.
  • Insights into service dependencies: An easy way to understand cross-service changes and visualize their ripple effects across your entire system.
  • Seamless notifications: Direct integration with your existing communication channels (e.g., Slack) so you’ll have all the information you need, when you need it.

If you are interested in checking out Komodor, use this link to sign up for a Free Trial.

Sometimes, when a developer merges two projects, Git outputs the «fatal: refusing to merge unrelated histories» error. This error happens when Git tries to merge two project branches without a common base. Luckily, Git offers an easy command to fix this error.

To fix the «fatal: refusing to merge unrelated histories» error in Git, use the git pull command like so:

bashgit pull origin main --allow-unrelated-histories

This article will explain why this error happens and give a method to fix it.

Let’s get to it 😎.

git refusing to merge unrelated histories

Why does this error happen?

The «fatal: refusing to merge unrelated histories» error happens when two projects with mismatching commit histories or not aware of each other’s existence are merged.

This error can happen for many reasons.

Here are a few of them:

  • The .git directory is corrupted or deleted.
  • You have a new repository with a few commits.
  • The branches have different HEAD positions.
  • When setting up a different remote for a local repository.

How to fix this error?

By default, Git doesn’t allow merging two branches with no common base (since version 2.9).

That’s why Git introduced the —allow-unrelated-histories option.

The —allow-unrelated-histories option overwrites the default behavior and forces the merge to happen.

To fix the «fatal: refusing to merge unrelated histories» error, toggle the allow unrelated histories option on the git pull command, like so:

bashgit pull origin main --allow-unrelated-histories

Note: The git pull command is a shorthand for git fetch and git merge. That’s why when you pull, Git also merges. I’ve written an extensive guide on git fetch vs git pull (if you are interested).

How to prevent this error?

This error is hard to prevent because the merge happens out of necessity most of the time.

The best a developer can do is know why it happens and how to fix it.

Final thoughts

In conclusion, understanding how to fix this error is very important for developers because this error happens often.

Next time you see this error, you’ll know what to do.

git refusing to merge unrelated histories

Here are some other Git tutorials for your enjoyment:

  • Undo a rebase in Git
  • Abort a cherry-pick in Git
  • Push an empty commit in Git
  • Unstage all files in Git

Tim Mouskhelichvili

written by:

Hello! I am Tim Mouskhelichvili, a Freelance Developer & Consultant from Montreal, Canada.

I specialize in React, Node.js & TypeScript application development.

If you need help on a project, please reach out, and let’s work together.

You have received the dreaded fatal: refusing to merge unrelated histories error!

You might find yourself asking one of the following questions:

  1. What is refusing to merge unrelated histories?
  2. How do you combine two unrelated histories?
  3. What is unrelated history in git?
  4. How do you fix unrelated branches?

Well look no further, below you will learn how to solve this problem quickly and also learn about why it happens in the first place.

Tldr; Quick Solution!

git pull origin branchname --allow-unrelated-histories

This will solve the “fatal: refusing to merge unrelated histories” error; but for a deeper understanding, continue reading below!

Why does this happen?

Git is all about Deltas (the difference between 2 or more states of something), and if you have 2 histories that don’t appear to have the same bunch of things, then it won’t know what to change, or in what order.

At this point, a fatal error will be thrown stating refusing to merge unrelated histories.

It actually makes perfect sense. But how do we fix it?

Option 1 (easy)

The easiest way is to git clone the remote repo into a new directory (~/tmp) or somewhere like that (a throwaway) and then simply copy/paste all your files that you want in there and then git push them.

Option 2 (better)

Use the --allow-unrelated-histories flag to just force it through!

Note that this could work if you know what you’re doing, but could well break everything, so use it at your own risk!

git pull origin branchname --allow-unrelated-histories

The commands to use

git pull origin master --allow-unrelated-histories
git merge origin origin/master
... add and commit here...
git push origin master

Consider the following two cases that throw this error:

  • You have cloned a project and, somehow, the .git directory got deleted or corrupted. This leads Git to be unaware of your local history and will, therefore, cause it to throw this error when you try to push to or pull from the remote repository.

  • You have created a new repository, added a few commits to it, and now you are trying to pull from a remote repository that already has some commits of its own. Git will also throw the error in this case, since it has no idea how the two projects are related.

Solution

The error is resolved by toggling the allow-unrelated-histories switch. After a git pull or git merge command, add the following tag:

git pull origin master --allow-unrelated-histories

More information can be found here, ​ on Git’s official documentation.

When developers start using Git as a version controlling system for their projects, they encounter many fatal errors, one of which is “fatal: git refusing to merge unrelated histories”. The solutions to these fatal errors are often complex and situation-based.

However, the error we are talking about in this article is not that difficult to resolve. There is a simple, straightforward solution to it which we will be discussing in this brief article. Also, we will investigate the reasons that cause the error occurrence.

What are the Causes of the “fatal: refusing to merge unrelated histories” Error?

This error appears when some of your ambiguous actions confuse Git on how to function further. Typically, when you try to merge two unrelated projects with different commit histories into a single branch, the error pops up. The two histories will remain incompatible since they don’t have common tags and commit message.

Following are the two main scenarios that can raise the discussed fatal error:

        • You create a remote repository that has its own history in the .git directory, and then you create a local git repository that has a different .git directory of its own with the history of your local commits.
        • Later, after making several commits, you try to pull or merge this local repository to the remote one, and boom, you are hit by the error.

          Why so? Because the repositories that you are trying to connect have different .git directories and hence different histories, and Git does not know how these two projects are related to each other.

      • You are also vulnerable to this fatal error if the .git directory inside your project has been corrupted or deleted. In that case, Git loses track of the project because of the absence of history.

How to fix “fatal: refusing to merge unrelated histories” Error?

The solution to this fatal error is to use –allow-unrelated-histories flag with the git pull command or git merge command. Your command will somehow look like the following:

Git pull origin master –allow-unrelated-histories 

Here, the origin is to be replaced with the name of your remote repository and master with the branch name that you want to work in.

Conclusion

In this brief yet convenient guide, we discussed one of the most commonly faced Git fatal errors caused by nothing hugely wrong but by little ambiguity in the workflow. The error is simple to resolve with the help of one additional flag embedded with the common Git commands.

We discussed the solution and the causes of the error, and if you are falling in one of the discussed scenarios, this guide must be a go-to way to your problem’s solution.

Read also:

  • Fix: ‘git’ is not recognized as an internal or external command, operable program, or batch file error? [Solved]
  • Git Prune: Command to Clean Up Local Branches
  • How to Uncommit Changes in Git? [Complete Guide]
  • How to Undo a Git add

The “fatal: refusing to merge unrelated histories” Git error occurs when two unrelated projects are merged (i.e., projects that are not aware of each other’s existence and have mismatching commit histories).

Consider the following two cases that throw this error:

  1. You have cloned a project and, somehow, the .git directory got deleted or corrupted. This leads Git to be unaware of your local history and will, therefore, cause it to throw this error when you try to push to or pull from the remote repository.

  2. You have created a new repository, added a few commits to it, and now you are trying to pull from a remote repository that already has some commits of its own. Git will also throw the error in this case, since it has no idea how the two projects are related.

Solution
The error is resolved by toggling the allow-unrelated-histories switch. After a git pull or git merge command, add the following tag:

git pull origin master --allow-unrelated-histories

Понравилась статья? Поделить с друзьями:
  • Refused to apply style from ошибка
  • Refulgence контроллер ошибка ah1
  • Refs sys ошибка
  • Remmina ошибка при запуске сеанса ssh kex error
  • Remlichtschakelaar controleren ошибка опель