my-git

Recover Force Push

English 中文

After a force push overwrites a remote branch, first retrieve the correct commit.

If someone still retains the old branch locally, it can usually be recovered.

Preserve the Current State

First notify the team to pause pushing to the related branch.

Then check locally:

git reflog
git log --oneline --decorate -20

You can also ask colleagues to check locally:

git reflog
git log --oneline --decorate -20

Find the Correct Commit

After confirming the good sha, first create a backup branch:

git branch backup-good-main <good-sha>

Check the content:

git show --stat <good-sha>
git diff <bad-sha>..<good-sha>

Restore Remote Branch

git push origin <good-sha>:main

If the main branch is protected, it requires administrator handling.

Follow-up Remediation

Further Reading