A teammate force-pushed to `main` and your commits vanished from the remote. How do you recover?
AdvancedScenarioUndoing Mistakes
Answer
Situation read → The remote branch pointer moved; the old commits still exist in clones and, for a while, on the server.
What I'd do →
- Check your clone:
git reflog show origin/mainshows the old remote tip. - Restore the branch pointer:
git push origin <old-sha>:refs/heads/main --force-with-lease. Coordinate first. - On GitHub, the push activity or Events API shows the previous SHA:
gh api repos/ORG/REPO/events. - Add branch protection to block force pushes to
main.
Why → Anyone with an older clone holds the objects, so the data is rarely truly lost.
Interview tip → Use --force-with-lease, never plain --force, and block both on protected branches.
More on Undoing Mistakes
You committed on `main` when you meant to be on a feature branch. Nothing is pushed. Fix it.BeginnerYou made a typo in your last commit message and have not pushed.BeginnerA bad commit is already on shared `main`. Others have pulled it. How do you undo it?IntermediateYou ran `git reset --hard` and lost uncommitted-then-committed work. Can you get it back?IntermediateYou need to revert a merge commit on `main`. `git revert` says "commit is a merge but no -m option was given".IntermediateYou deleted a local branch with unmerged work by mistake.Beginner