はじめに
GitHubのリモートリポジトリにローカルリポジトリを push
しようとした際にエラーが発生しました。
原因と解決方法を整理しておきます。
手順
今回の作業の流れは以下の通りです。
① ローカルでプロジェクトを作成
② GitHubでリモートリポジトリを作成
③ ローカルリポジトリをGitHubのリモートリポジトリに push
エラー内容
③の git push
実行時に以下のエラーが発生しました。
username@/path/to/your/project % git push -u origin main
To https://github.com/{username}/{new_repo}
! [rejected] main -> main (fetch first)
error: failed to push some refs to 'https://github.com/{username}/{new_repo}'
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.
原因
リモートリポジトリにはすでに何らかのコミットが存在しており、ローカルの main ブランチと同期が取れていなかったために発生しました。
解決方法
1. リモートリポジトリの内容をローカルリポジトリへ取り込む
まず、リモートの変更をローカルに反映し、競合(conflict)を解決してから push
する方法です。
git pull origin main --rebase
このコマンドを実行すると、リモートの変更をローカルに適用しつつ、ローカルの変更を後ろに並べ直します。
もし競合(conflict)が発生した場合は、手動で修正して git add .
した後、以下のコマンドを実行してください。
git rebase --continue
リベースが完了したら、改めて push
します。
git push -u origin main
2. リモートリポジトリの履歴を強制的に上書く
リモートの main ブランチを完全に上書きしたい場合は、強制 push
を行います。
この操作を実行すると、リモートの履歴が失われる可能性があります。
今回は、まだリモートリポジトリに push
していない個人用プロジェクトだったため、この方法を使用しました。
git push -u origin main --force
最後に
久しぶりに git push しようとしたら、意外と忘れていることも多く良い復習になりました。
特に、リモートリポジトリの状態をしっかり確認してから push する習慣をつけたいと思います。
参考サイト