LoginSignup
268
164

More than 3 years have passed since last update.

[Git] fatal: refusing to merge unrelated historiesを解決する話

Last updated at Posted at 2020-08-06

TL;DR

git merge --allow-unrelated-histories origin/masterをする!

※ 2020/12/01追記
2020年10月より, デフォルトブランチがmasterからmainに変更になりました.(https://github.com/github/renaming) なので, 新しく作った方は

git merge --allow-unrelated-histories origin/mainになります!

なにが起きたの?

  1. GitHub上でリポジトリを作り, READMEを作成した.
  2. ローカルでgit initしてリポジトリを作り, git remote add origin <GitHubのリポジトリ>でリモートリポジトリを指定.
  3. ローカルで作業を行い,コミットしプッシュを行おうとした.

プッシュを行おうとしたら, 下のようになった.

To https://github.com/<user>/<repo_name>.git
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/<user>/<repo_name>.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

プッシュできなかったので,言われた通りにプル git pull origin main git pull origin masterを行なった.※2020/12/01 追記
すると, 下のようになった.

From https://github.com/<user>/<repo_name>
 * branch            master     -> FETCH_HEAD
fatal: refusing to merge unrelated histories

fatal: refusing to merge unrelated historiesと表示されプルできなかった.

解決策

git mergeコマンドに--allow-unrelated-historiesのオプションを使いして実行する.

git merge --allow-unrelated-histories origin/master

mainブランチがデフォルトのとき

git merge --allow-unrelated-histories origin/main

するとimage.png

のようにマージが行われ,無事にプッシュ作業が行うことができる!

どうしてこうなった?

通常のマージでは,共通の祖先から分岐したブランチ同士が結合される.しかし,今回の例では,Githubでのコミット,ローカルでのコミットはそれぞれ共通の祖先がない状態から行われてしまっている.このため,マージを行うことができなかった.

しかし--allow-unrelated-historiesオプションをつけると,共通の祖先を持っていないブランチ同士でもマージ作業を行うことができる.

所感

今回起きた問題は, リポジトリ作りたての一番はじめだけしか起こることがない珍しいケースだと思う.

(--orphan オプションをつけてブランチを作成すると,既存ブランチと完全に独立したブランチを作れるため,一応おこりえる?)

参考にしたサイト

268
164
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
268
164