この記事の概要
・Githubを用いたソースコード管理に関する内容
・git操作時のエラーについての解決策のメモ
・gitの仕組み(リモートリポジトリとローカルリポジトリ、ブランチを切る、git add,commit,pushの流れ等)がある程度は分かる人向け
結論
GitHubを使って、異なる2つのPCでソースを共有する際、
refusing to merge unrelated histories
というエラーが発生する場合があり、
その解消には、
git merge --allow-unrelated-histories origin/master
をする必要がある
詳細の記述
前提
拠点Aと拠点Bで、それぞれ別々のPCを使って、同一のソースコードを管理する、というシチュエーション
前提に基づく具体的な作業内容・発生したエラーおよびその対処方法
1)拠点AのPCで、Githubに新規リポジトリを作成
2)拠点AのPCで、Gitの管理下に置きたいディレクトリに移動
3)README.mdに、echo hogehoge(=空でない何らかのファイルを作成する行為)
4)git init
5)git add -A
(全てをadd)
6)git commit -m "first commit"
(コミットメッセージつきのcommit実行)
7)git remote add origin git@github.com:ユーザー名/リポジトリ名.git
(1)で作成したリモートリポジトリをローカルのフォルダと関連づける)
8)git push origin master
(README.mdをリモートリポジトリにpush)
9)ブラウザでGithubの該当リポジトリページを開いて、README.mdが表示されればOK
拠点Bにて、
1)拠点BのPCで、Gitの管理下に置きたいディレクトリに移動
※このときディレクトリ内には、リモートリポジトリにpushしたいファイル群があることとする
2)git init
3)git remote add origin git@github.com:ユーザー名/リポジトリ名.git
(1)で作成したリモートリポジトリをローカルのフォルダと関連づける)
4)git add -A
5)git commit -m "first commit from B"
(コミットメッセージつきのcommit実行)
6)git push origin master
!!エラー発生!!
error: failed to push some refs to 'https://github.com/ユーザー名/リポジトリ名.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.
※対象のリモートリポジトリの内容を、拠点Bのローカルに反映させることを先に実行しなくてはならない
7)git pull origin master
(リモートリポジトリの最新の内容をローカルにpull)
8)git push origin master
(ローカルの内容をリモートリポジトリにpush)
!!エラー発生!!
error: failed to push some refs to 'https://github.com/ユーザー名/リポジトリ名.git'
hint: Updates were rejected because the tip of your current branch is behind
※拠点Bのローカルのmasterブランチが、リモートリポジトリよりも古い(ビハインド)のでpushできない
9)もう一度、git pull origin master(リモートリポジトリの内容をローカルに反映させる)
!!エラー発生!!
fatal: refusing to merge unrelated histories
※2つの無関係なヒストリー同士をmergeさせることはできない
※こちらの記事に詳しくあるが、gitの仕様であるとのこと
https://qiita.com/takanatsu/items/fc89de9bd11148da1438
※エラー解消のためには、2つ(リモートリポジトリとローカルリポジトリ)の無関係なヒストリーをmergeするコマンドを入力する必要がある
10)git merge --allow-unrelated-histories origin/master
実行結果
Merge made by the 'recursive' strategy.
README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 README.md
(リモートリポジトリにあったREADME.mdが拠点Bのローカルとmerge。拠点Bのローカルには、6)でpushしようとしていたファイル群と、README.mdが一緒にある状態になった)
11)git push origin master
(ローカルの内容をリモートリポジトリにpush)
Enumerating objects: 121, done.
Counting objects: 100% (121/121), done.
Delta compression using up to 4 threads
Compressing objects: 100% (102/102), done.
Writing objects: 100% (120/120), 187.77 KiB | 4.69 MiB/s, done.
Total 120 (delta 9), reused 0 (delta 0)
remote: Resolving deltas: 100% (9/9), done.
To https://github.com/ユーザー名/リポジトリ名.git
fb77a79..3423825 master -> master
12)ブラウザでGithubのリポジトリページを開いて、拠点Bのローカルのファイル群が表示されていれば、リモートリポジトリに拠点Bのローカルのファイル群をpush成功
あとがき
あまり一般的でないシチュエーションかもしれませんが、
もし詰まった方がいれば、その参考になれば幸いです。