0
0

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

問題の発生

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.

ローカルとリモートのブランチが分岐してしまっていたのです。

原因

このエラーが発生した理由:

  1. ローカルで作業していた間に、リモートリポジトリが更新されていた

    • 私の場合、ローカルでworkflowファイルを削除
    • 同時期にGitHub上でPRがマージされ、同じworkflowファイルが更新されていた
  2. 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できました!

今後の予防策

  1. 定期的にpullする

    • 作業前にgit pullを実行する習慣をつける
  2. pull戦略を設定する

    # マージを使う場合
    git config pull.rebase false
    
    # リベースを使う場合
    git config pull.rebase true
    
  3. ブランチを使って作業する

    • mainブランチで直接作業せず、機能ブランチを作成する
    • PRを使ってマージする

まとめ

ブランチの分岐は、チーム開発や並行作業では避けられない問題です。適切なGitワークフローを採用し、定期的な同期を心がけることで、このような問題を最小限に抑えることができます。

コンフリクトが発生しても、落ち着いて対処すれば必ず解決できます!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?