1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Git入門】pushが拒否された時の対処法

Posted at

はじめに

GitHubでリポジトリを作成した後、ローカルのプロジェクトをプッシュしようとした時に以下のようなエラーに遭遇し、解決に少し頭を悩ましましたので記事にします。

発生したエラー

エラー1: プッシュの拒否

! [rejected]        main -> main (fetch first)
error: failed to push some refs to 'github.com:username/repository.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally...

エラー2: ブランチの統合方法の指定が必要

hint: You have divergent branches and need to specify how to reconcile them.
hint: You can do so by running one of the following commands sometime before
hint: your next pull:
hint:   git config pull.rebase false  # merge
hint:   git config pull.rebase true   # rebase
hint:   git config pull.ff only       # fast-forward only

解決手順

1. まずリモートの変更を取得します
git pull origin main --allow-unrelated-histories
2. ブランチの統合方法を指定します
git config pull.rebase false
3. 再度プルを実行
git pull origin main --allow-unrelated-histories
4. コンフリクトが発生した場合は解消し、コミット
git add .
git commit -m "Resolve merge conflict"
5. 最後にプッシュ
git push -u origin main

git pullの統合方法について

プル時に表示される3つのオプションについて、それぞれの特徴を説明します。

1. mergeする方法

git config pull.rebase false  # merge

特徴

  • 最も一般的な選択肢です
  • リモートとローカルの変更を新しいコミットで統合します
  • 履歴が分かりやすく、安全です
  • マージコミットが作成されるため、履歴が若干複雑になる可能性があります

2. rebaseする方法

git config pull.rebase true  # rebase

特徴

  • ローカルの変更を、リモートの最新の状態の上に移動させます
  • 履歴がよりクリーンで直線的になります
  • コンフリクトの解決が複雑になる可能性があります
  • 既にプッシュした変更にはおすすめしません

3. fast-forward onlyする方法

git config pull.ff only  # fast-forward only

特徴

  • 最も厳格な選択肢です
  • マージやリベースを行わず、単純な履歴の更新のみを許可します
  • ローカルとリモートの履歴が分岐している場合はエラーになります
  • 確実な履歴管理が必要な場合に使用します

基本的な解決s

結論、git config pull.rebase falseがおすすめです:

  • 最も安全で理解しやすいです
  • コンフリクトの解決が比較的簡単です
  • チーム開発でも一般的に使用されています

補足

  • クリーンな履歴を保ちたい場合は git config pull.rebase true
  • 厳密な履歴管理が必要な場合は git config pull.ff only

まとめ

今回は、pushが拒否された時のエラー対処について解説しました。このエラーが発生する主な理由は、リモートとローカルの履歴の違いによるものです。

解決のポイントは以下の2つです

  • --allow-unrelated-historiesオプションを使用して、異なる履歴を持つブランチの統合を可能にする
  • マージ戦略を明示的に指定することで、スムーズな統合を実現する

特に初学者の方は、安全で分かりやすいgit config pull.rebase false(merge)を選択することをおすすめします。この方法であれば、チーム開発でも安心して使用できます。

1
1
0

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?