【git】リモート/ローカルリポジトリとの紐づけが上手く行かない時の対処方法
「既存のローカルリポジトリ」と「新規のリモートリポジトリ」を紐づけたはずなのに、pullやpushが上手く行かなかった時の備忘録
【解決方法】「–allow-unrelated-histories」をつけてマージ
まず、解決方法として--allow-unrelated-historiesをつけてマージ
※origin/masterのmaster部分は任意のブランチに書き換え
git merge --allow-unrelated-histories origin/master
--allow-unrelated-historiesは異なるコミット履歴を持ったブランチを強制的にマージするオプション。
【原因】リモート/ローカルリポジトリで異なるデータがあった
原因としては、「新規で作成したリモートリポジトリ」でREADMEや.gitignoreを作成し、ローカルリポジトリにも内容が異なる.gitignoreが存在していた。恐らく競合しており、上手くpullやpushができなかったのだと思う。
なので、git merge --allow-unrelated-histories origin/masterを実行して強制的にマージすることで解決。
終わり
※以下は【解決方法】にたどり着くために対応した流れの備忘録。(個人的なメモ)
1. git pushが上手く行かない時の対応メモ
ローカルリポジトリとリモートリポジトリを紐づけ、git add .、git commit -m コミットメッセージ、git push origin masterを実行したところ以下のエラー
$ git push origin master
To https://bitbucket.org/ID/リポジトリ名.git
! [rejected] master -> master (non-fast-forward)
error: failed to push some refs to 'https://bitbucket.org/ID/リポジトリ名.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
エラーメッセージに書かれている通りgit pull実行すると以下のようなメッセージ
$ git pull
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details.
git pull <remote> <branch>
If you wish to set tracking information for this branch you can do so with:
git branch --set-upstream-to=origin/<branch> master
git pullができない。
2. git pullが上手く行かない時の対応メモ
pullが上手く行かない原因は、リモートリポジトリに新規で作成された.gitignoreがローカルリポジトリの.gitignoreと競合していることが原因。
そのため、追跡しているリモートブランチが上手く紐づいてないことが原因と予想し、以下の流れで確認と対処。
1. 追跡しているリモートブランチ確認
追跡しているリモートブランチをgit branch -vvで確認
$ git branch -vv
* master 5b68b2b コミットメッセージ
2. 追跡するリモートブランチを設定
上のエラーメッセージ2に書かれているgit branch --set-upstream-to=origin/branch masterを書き換えて実行
※下記コードはgit pullをしたら自動的にoriginのmasterブランチからpullできるようになる記述
$ git branch --set-upstream-to=origin/master master
branch 'master' set up to track 'origin/master'.
再度git branch -vvで確認するとリモートブランチが上手く紐づいたことが確認できる
$ git branch -vv
* master 5b68b2b [origin/master: ahead 1, behind 1] コミットメッセージ
aheadは既存のローカルリポジトリの変更で、behindはリモートリモートリポジトリにある.gitignoreとの差分だと思われる
3. リモートリポジトリにある差分を取り込む
再度pullを行うと別のエラーが出る
$ git pull
fatal: refusing to merge unrelated histories
なので、git merge --allow-unrelated-histories origin/masterを実行する。
$ git merge --allow-unrelated-histories origin/master
Auto-merging .gitignore
CONFLICT (add/add): Merge conflict in .gitignore
Automatic merge failed; fix conflicts and then commit the result.
--allow-unrelated-historiesは共通の祖先を持っていないブランチ同士をマージすることができるらしい。
※ブランチの表記が以下のように変わる
変化:master→(master|MERGING)
4. コンフリクトを解消してpush
マージが無事にできたので、.gitignoreで起きているコンフリクトを解消(ローカルのデータで上書き)をすることで無事にアップロードできるようになった
git add .
# コミットするとブランチの表記が元に戻る
# (master|MERGING) → masterに戻る
git commit -m ""
git push origin master
終わり