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

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

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.

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.

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.

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.

Понравилась статья? Поделить с друзьями:
  • Refulgence контроллер ошибка ah1
  • Refresh backgroundquery false ошибка
  • Reflash 12345 ошибка
  • Redmond rmc m20 ошибка е1
  • Ref ошибка эксель