Rewriting a pushed branch safely
Rebasing or squashing a branch that is already on the server is routine in review-based workflows. It only becomes dangerous when the push overwrites commits that someone else added in the meantime.
Prefer --force-with-lease
git push --force replaces the remote branch with yours, whatever it contains. git push --force-with-lease first checks that the remote branch still points where your remote-tracking branch says it does, and refuses otherwise. If a colleague pushed a fix after your last fetch, the push fails instead of silently discarding it.
The check compares against your last fetch, so a background git fetch, which some editors run on their own, defeats it. --force-if-includes, available since Git 2.30, additionally requires that the remote commits are part of your local history.
git fetch origin
git rebase origin/main
git push --force-with-lease --force-if-includes origin my-branch
The reflog is the undo button
Every movement of HEAD and of each branch is recorded in the reflog, and reachable entries are kept for 90 days by default. After a rebase that went wrong:
git reflog show my-branch
git reset --hard my-branch@{1}
my-branch@{1} is where the branch pointed before its last change. Rebase, merge and reset also set ORIG_HEAD to the previous tip.
Habits
- Rewrite only branches you own, and keep shared branches append-only.
- Before a large rewrite, create a throwaway pointer with
git branch backup/my-branch. - Compare the old and the new version of a series with
git range-diffbefore pushing.
Removing data from history
A rewrite removes a file from new clones, but not from existing clones, forks or caches. Anything sensitive that was ever pushed, such as a password or a private key, should be treated as exposed and replaced; the rewrite only stops it from spreading further.