Video in progress
Someone force pushed to `main` from an old local copy and wiped out the last day's 30 merges. How do you recover, and what do you do so it does not happen again?
remote: + 8e41c2a...1f07b9d main -> main (forced update)
The commits are not lost: the old tip exists in someone's clone, on CI runners, in the platform's push logs, or in the server reflog. I find that SHA and move main back to it, and then forbid force push on protected branches.
📖 Answer
First, everyone should stop pushing to main, so the situation does not get tangled.
Sources for finding the old tip (usually one is enough):
- the line in the push log:
8e41c2a...1f07b9d, where the left-hand8e41c2ais the lost tip; - the GitHub/GitLab audit log and the "activity" page show the force push, and sometimes there is a restore button;
- any developer's clone or a CI runner that did a
git fetch:git reflog show origin/main; - on a self-hosted server, the server reflog if
core.logAllRefUpdatesis on.
Recovery:
git fetch origin
git push origin 8e41c2a:refs/heads/main --force-with-lease=main:1f07b9d
With a lease, so that you do not overwrite it if someone else pushed something again during the recovery. If new commits also landed after the force push, you cherry-pick or merge them on top of the restored tip.
Then the deploy side: in that window, CI may have released old code to prod, so check, and redeploy if needed.
Prevention:
- branch protection: force push forbidden, merge only through a PR, for admins too;
- reduce the risk from personal
push.defaultand aliases:--force-with-lease --force-if-includesinstead of--force; - a blameless postmortem: usually it is not one person, the permission was simply granted too broadly.
Sign up to mark studied questions and save your progress.