MeWrite Docs

fatal: refusing to merge unrelated histories

Gitで共通の履歴を持たないブランチをマージしようとした際のエラー

概要

Gitで共通のコミット履歴を持たない2つのブランチをマージしようとした際に発生するエラーです。Git 2.9以降、安全のためデフォルトでこのマージは拒否されます。

エラーメッセージ

fatal: refusing to merge unrelated histories

原因

  1. 別々に作成したリポジトリ: ローカルとリモートで別々に初期化
  2. GitHub上でREADMEを作成: リポジトリ作成時にREADME.mdを追加
  3. orphanブランチ: --orphanオプションで作成したブランチ
  4. リベース後の履歴不整合: 強制プッシュ後の履歴の断絶
  5. 異なるプロジェクトの統合: 2つの別プロジェクトを1つにまとめる

解決策

1. –allow-unrelated-historiesオプション

1
2
3
4
5
# マージ時に許可
git merge origin/main --allow-unrelated-histories

# プル時に許可
git pull origin main --allow-unrelated-histories

2. リベース時

1
git rebase origin/main --allow-unrelated-histories

3. 新規リポジトリの正しい手順

1
2
3
4
5
6
7
8
9
# ローカルでプロジェクトを作成
git init
git add .
git commit -m "Initial commit"

# GitHubでREADMEなしの空リポジトリを作成後
git remote add origin https://github.com/user/repo.git
git branch -M main
git push -u origin main

4. 既存リポジトリにREADMEがある場合

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# リモートの内容を取得
git fetch origin

# 許可してマージ
git merge origin/main --allow-unrelated-histories

# コンフリクトがあれば解決
git add .
git commit -m "Merge remote repository"
git push

5. リモートの内容を優先する場合

1
2
3
4
5
6
7
# リモートをクローンしてローカルのファイルをコピー
git clone https://github.com/user/repo.git temp
cp -r my-project/* temp/
cd temp
git add .
git commit -m "Add local project files"
git push

6. ローカルの内容を優先する場合(危険)

1
2
# 警告: リモートの履歴が失われる
git push origin main --force

7. サブツリーとしてマージ

1
2
3
4
5
6
# 別プロジェクトをサブディレクトリとして追加
git remote add other-project https://github.com/user/other.git
git fetch other-project
git merge -s ours --no-commit --allow-unrelated-histories other-project/main
git read-tree --prefix=other/ -u other-project/main
git commit -m "Merge other project as subdirectory"

コンフリクト解決

1
2
3
4
5
6
7
8
# マージ後にコンフリクトが発生した場合
git status  # コンフリクトファイルを確認

# ファイルを編集してコンフリクトを解決
# <<<<<<<, =======, >>>>>>> マーカーを削除

git add <resolved-files>
git commit -m "Resolve merge conflicts"

よくある間違い

  • GitHubでリポジトリ作成時に「Add a README file」をチェックしてしまう
  • --forceで強制プッシュしてリモートの履歴を消す
  • コンフリクト解決せずにコミットしようとする

関連エラー

参考リンク

Git の他のエラー

最終更新: 2025-12-13