Resources Infrastructure

Fix Git 'Refusing to Merge Unrelated Histories' Error

Resolve the Git fatal: refusing to merge unrelated histories error with the allow-unrelated-histories flag, resolve the resulting conflicts, and keep a clean commit graph.

TL;DR — Git refuses to merge two branches that share no common ancestor, to stop an unrelated project from being pulled in by mistake. When the merge is intended, add --allow-unrelated-histories to git pull or git merge, resolve any files that both histories created, and commit the result.

Running git pull or git merge and getting fatal: refusing to merge unrelated histories means Git found no common ancestor between the two branches. The quick fix is one flag:

git pull origin main --no-rebase --allow-unrelated-histories

--no-rebase tells git pull to merge. Without it, a Git with no pull.rebase or pull.ff setting stops with “Need to specify how to reconcile divergent branches” before the flag applies.

Before running it, check that you are pulling the project you expect. The rest of this page explains why the error exists, how to merge safely, and how to handle the same situation in an automated pipeline.

Why Git refuses to merge unrelated histories

Git stores history as a directed acyclic graph, where each commit points to its parents. To merge, Git walks back from both branch tips to find their common ancestor, the merge base, and runs a three-way merge between that base and the two tips.

When the branches started from different root commits, there is no merge base:

Local: R1 (git init) ---> C1 ---> C2 (HEAD)
Remote: R2 (created with README) ---> C3 ---> C4 (origin/main)
No commit is shared between the two lines.

Git used to merge such histories without complaint. The Git 2.9 release notes explain the change: an unsuspecting maintainer could pull a brand new history of an existing project into it. Since then, the git merge documentation states that the command refuses histories without a common ancestor unless you pass --allow-unrelated-histories.

Three situations trigger the error most often:

  1. Local and remote initialized separately. You run git init and commit locally, while the hosted repository was created with a README, .gitignore, or license. Each side has its own root commit, so the first git pull origin main fails.
  2. Combining repositories into a monorepo. Repositories built independently have disjoint histories, so merging one into another needs the flag.
  3. A re-initialized repository. Deleting the .git folder and running git init again starts a new history. Pulling from a remote that still holds the old commits raises the error. A missing or broken .git folder produces a different error, fatal: not a git repository.

Resolving the error safely

Step 1: Fetch without merging

Fetch the remote branch so you can inspect it without touching your working directory:

git fetch origin

Step 2: Check that this is the right project

Compare both histories and the files that differ:

git log origin/main --oneline
git log HEAD --oneline
git diff HEAD origin/main --stat

If the remote log shows a project you do not recognize, stop here: the error has just prevented a wrong merge.

Step 3: Merge with the flag

git merge origin/main --allow-unrelated-histories -m "Merge remote history"

git pull origin main --no-rebase --allow-unrelated-histories does the same in one step, since git pull passes the option to git merge.

Step 4: Resolve conflicts

With no common ancestor, any file that both histories added with different content, typically README.md, .gitignore, or a license, becomes an add/add conflict. List them:

git status

Edit each file to keep the right content and remove the markers:

<<<<<<< HEAD
# Local project name
Local setup instructions.
=======
# Remote project name
Remote setup and license details.
>>>>>>> origin/main

Then stage and commit:

git add README.md .gitignore
git commit -m "Resolve conflicts between local and remote histories"

When the flag is not the right fix

--allow-unrelated-histories is only correct when you really want to join two separate histories. Rule out these causes first:

  • Wrong remote. Run git remote -v. If origin points to another project, fix it with git remote set-url origin <url> instead of merging.
  • Wrong branch name. A repository created with master as its default branch and a remote using main (or the reverse) can lead you to pull a branch you did not mean to. Check with git branch -a and pull the right one.
  • You only need the remote content. If your local commits do not matter, for example a fresh git init with a single placeholder commit, it is simpler to start from the remote: clone it again, or run git fetch origin then git reset --hard origin/main. This discards your local commits, so copy anything you need first.
  • Combining projects into a monorepo. Merging another repository at the root mixes both file trees. To keep the other project in a subdirectory with its history, use git subtree add --prefix=<dir> <url> main (shipped in Git’s contrib, installed with most distributions) or move its files into a subdirectory in a commit before merging.

Merge or rebase?

StrategyCommandResulting historyWhen to use itRisk
Mergegit merge origin/main --allow-unrelated-historiesBoth histories kept, joined by a two-parent merge commitShared histories, monorepo consolidationNon-linear graph
Rebasegit rebase origin/mainYour commits replayed on top of the remote branchA fresh local repository with a few unpushed commitsRewrites commit hashes; never rebase commits others have pulled

For a new local repository with one or two commits, rebasing onto the remote branch avoids an extra merge commit. Once both histories are shared, merge: it keeps authorship, dates, and signatures intact.

Ready to orchestrate your infrastructure?

When the error happens in a pipeline

The same error is more costly when Git runs unattended: a sync job, a GitOps reconciliation loop, or a script that pulls vendor templates. Nobody is at the terminal to read the log and decide whether the merge is intended. A useful automated job checks for a merge base first, merges only when it is safe, and hands conflicts to a person instead of force-pushing.

The Kestra flow below does that. It clones your repository, fetches an upstream repository, and checks for a common ancestor. If the histories are related, or a reconciliation branch is already waiting for review, it logs that and ends successfully. If they are unrelated and merge cleanly, it pushes a review branch and opens a GitLab merge request. If the merge conflicts, it aborts the merge and fails the run so the team is alerted.

id: git-repo-reconciliation
namespace: company.infrastructure
inputs:
- id: upstream_url
type: STRING
defaults: https://gitlab.com/your-org/upstream-templates.git
tasks:
- id: reconcile
type: io.kestra.plugin.scripts.shell.Commands
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: alpine/git:v2.54.1
env:
GITLAB_TOKEN: "{{ secret('GITLAB_TOKEN') }}"
UPSTREAM_URL: "{{ inputs.upstream_url }}"
commands:
- |
set -e
git clone "https://oauth2:${GITLAB_TOKEN}@gitlab.com/your-org/gitops-infra.git" repo
cd repo
git config user.name "Kestra automation"
git config user.email "automation@example.com"
git remote add upstream "$UPSTREAM_URL"
git fetch upstream main
if git merge-base HEAD upstream/main > /dev/null; then
echo "Histories are related, nothing to reconcile."
echo '::{"outputs":{"status":"related"}}::'
exit 0
fi
if git ls-remote --exit-code --heads origin chore/reconcile-upstream > /dev/null; then
echo "A reconciliation branch is already waiting for review."
echo '::{"outputs":{"status":"pending_review"}}::'
exit 0
fi
git checkout -b chore/reconcile-upstream
if git merge upstream/main --allow-unrelated-histories -m "Merge unrelated upstream history"; then
git push origin chore/reconcile-upstream
echo '::{"outputs":{"status":"merged"}}::'
else
git merge --abort
echo '::{"outputs":{"status":"conflict"}}::'
fi
- id: on_status
type: io.kestra.plugin.core.flow.Switch
value: "{{ outputs.reconcile.vars.status }}"
cases:
merged:
- id: open_merge_request
type: io.kestra.plugin.gitlab.mergerequests.Create
token: "{{ secret('GITLAB_TOKEN') }}"
projectId: your-org/gitops-infra
sourceBranch: chore/reconcile-upstream
targetBranch: main
title: "Merge unrelated upstream history"
mergeRequestDescription: "Upstream and main had no common ancestor. The histories merged without conflicts; review before merging."
conflict:
- id: stop_for_manual_merge
type: io.kestra.plugin.core.execution.Fail
errorMessage: "Upstream has an unrelated history and the merge conflicts. Merge it by hand with --allow-unrelated-histories."
defaults:
- id: nothing_to_merge
type: io.kestra.plugin.core.log.Log
message: "No merge needed: {{ outputs.reconcile.vars.status }}."

What this gives you over a bare git pull in a cron job:

  • The merge base is checked first. git merge-base returns an error when there is no common ancestor, so the flow decides what to do before anything is merged into main.
  • Nothing reaches main without review. A clean merge goes to a branch and a merge request; a conflicting one is aborted and fails the run, which triggers your usual failure alerts. While that branch is open, later runs skip the merge instead of failing on git push.
  • Isolated and credential-safe. The Git commands run in a fresh container each time, and the token comes from a Kestra secret rather than a script on a runner host.

Terraform, Ansible and Kubernetes, orchestrated from one place.

Frequently asked questions

Find answers to your questions right here, and don't hesitate to Contact Us if you couldn't find what you're looking for.