Confession time. Last week I rebased a branch that two colleagues had already pulled, pushed with --force, and deleted a commit one of them had added an hour earlier. Nobody died. The commit was recoverable from their clone. I spent the afternoon apologising to a person who had been entirely nice about it.
What I use now instead of --force:
git push --force-with-lease
It means: "overwrite the remote branch only if it still points where I last saw it". If somebody pushed a new commit in the meantime, the push is refused and you are forced to look at what you were about to throw away.
Caveat that took me too long to learn: the lease is based on your remote-tracking branch, origin/feature. If your editor or a background job runs git fetch for you, that ref moves, and the lease is satisfied even though you never looked at the new commit. Safer form:
git push --force-with-lease=feature:<sha-you-actually-looked-at>
And some rules that are easy to follow now:
- never rewrite a branch other people have based work on without telling them,
- rebase your own feature branch freely before it is shared,
- merge, don't rebase, on the shared long-lived ones.
If it goes wrong anyway: git reflog on any clone that had the old commit. It is the seatbelt of the whole system.