Last Updated: February 25, 2016
· destructuring

Recovering the HEAD right before a forced push

I like forced pushes in git. I use them all the time to collapse and reorganize feature branches, rebasing a feature branch just for clarity. But accidents happen. Sometimes you type "git push -f" and mess up a bunch of branches. Or your muscle memory types "git push -f origin master feature/david/cool_stuff". See the "master"? Whoops.

So here's how I think I'll remove most of the fear of losing commits from a forced push.

Install a github hook that'll mirror updates to branches. You get a backup of your repo, efficiently.

If you detect a forced push, create a branch with the current HEAD (representing the branch before the forced push) and name it "forced/$branch_name/YYYYMMDD/HHMMSS" in UTC. You can push this branch to github.

When someone notices a bad force push, they can recover as much as possible without waking up everyone and asking about missing commits:

git fetch origin
git branch -a | grep forced*20120820* | sort
git checkout forced/master/20120820/224143
git push -f origin forced/master/20120820/224143:master

Think that last line could be:

git push -f origin HEAD:master