問題の発生
git push origin mainを実行したら、以下のようなエラーが発生しました。
$ git status
On branch main
Your branch and 'origin/main' have diverged,
and have 1 and 3 different commits each, respectively.
ローカルとリモートのブランチが分岐してしまっていたのです。
原因
このエラーが発生した理由:
-
ローカルで作業していた間に、リモートリポジトリが更新されていた
- 私の場合、ローカルでworkflowファイルを削除
- 同時期にGitHub上でPRがマージされ、同じworkflowファイルが更新されていた
-
pull.rebaseの設定がされていなかった
- Gitが自動的にマージ方法を決定できない状態
解決方法
1. まずpullを試みる
$ git pull origin main
すると以下のエラーが表示されました:
hint: You have divergent branches and need to specify how to reconcile them.
fatal: Need to specify how to reconcile divergent branches.
2. マージ戦略を指定してpull
$ git pull --no-rebase origin main
3. マージコンフリクトの解決
コンフリクトが発生:
CONFLICT (modify/delete): .github/workflows/claude-code-review.yml deleted in HEAD and modified in cd25947...
CONFLICT (modify/delete): .github/workflows/claude.yml deleted in HEAD and modified in cd25947...
ローカルで削除したファイルがリモートで変更されていたため、コンフリクトが発生しました。
4. コンフリクトの解決
ローカルの削除を優先する場合:
$ git rm .github/workflows/claude-code-review.yml .github/workflows/claude.yml
$ git commit -m "Merge branch 'main' of https://github.com/username/repository"
5. pushの実行
$ git push origin main
無事にpushできました!
今後の予防策
-
定期的にpullする
- 作業前に
git pullを実行する習慣をつける
- 作業前に
-
pull戦略を設定する
# マージを使う場合 git config pull.rebase false # リベースを使う場合 git config pull.rebase true -
ブランチを使って作業する
- mainブランチで直接作業せず、機能ブランチを作成する
- PRを使ってマージする
まとめ
ブランチの分岐は、チーム開発や並行作業では避けられない問題です。適切なGitワークフローを採用し、定期的な同期を心がけることで、このような問題を最小限に抑えることができます。
コンフリクトが発生しても、落ち着いて対処すれば必ず解決できます!