Меню

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

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.

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

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

Git

fatal: refusing to merge unrelated histories

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

5534126872461312

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

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

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

Решение

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

git&nbsp;pull&nbsp;origin&nbsp;master&nbsp;--allow-unrelated-histories

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

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

After using Git for a while, you’ll notice that there’s a lot of mistakes that can be difficult to fix. This isn’t the case with the fatal: refusing to merge unrelated histories error. Unlike a number of other errors, this issue has one solution that you can reuse whenever you encounter it.

In this guide, we’re going to talk about how to solve the fatal: refusing to merge unrelated histories errors in Git. Let’s get started!

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

Why Does the Error Occur?

The error fatal: refusing to merge unrelated histories occurs when two unrelated projects are merged into a single branch. This error arises because each project has its own history of commits and tags. These two histories will be incompatible with each other.

There are two main scenarios when this error may arise.

When you create a new repository, make a few commits, and try to pull from another remote repository, this error can occur. This error will be displayed because the local repository with which you are working will have a different history to the project which you are trying to retrieve.

You may encounter this error if the .git directory inside a project that has been deleted or corrupted. In this case, the Git command line may not be able to read your local project’s history.

When you try to push data to or pull data from a remote repository, this error will occur. This is because Git doesn’t know if the remote repository is compatible with your current repository.

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

We’ve done enough talking. To solve this issue, you can use the --allow-unrelated-histories flag when pulling data from a repository:

Git pull origin master –allow-unrelated-histories

You’ll want to substitute origin with the remote repository from which you are pulling resources. You should replace master with the branch that you want to retrieve.

This command was added to handle the rare event that you are working with two projects that have their own branches. 

Alternatively, you could clone a new version of the remote repository using git clone and start over. However, this is not usually necessary.

You can read more about the –allow-unrelated-histories flag on the official Git documentation.

Conclusion

The fatal: refusing to merge unrelated histories error occurs when either a .git directory is unreadable or when you are trying to pull data from a repository with its own commit history. This error tells you that you are trying to Git merge two unrelated projects to the same work tree.

Now you’re ready to solve this error using the –allow-unrelated-histories flag like an expert!

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Repair now ошибка на рено магнум
  • Repair needed пежо 3008 что значит ошибка