git --force-with-lease Gotcha

It’s always better to use the --force-with-lease option over --force when force pushing to a remote branch. However, it’s important to remember that --force-with-lease isn’t magic.

--force-with-lease simply checks your local remote branch (./.git/refs/remotes/origin/<branch>) against the actual remote branch. This means that the following:

git fetch
git push --force-with-lease

or if you even just git pull on a different branch (this is essentially the same git fetch) will behave the same as a --force push and nuke any changes made by another developer.

Here’s an example of a common workflow that renders --force-with-lease unable to prevent the push:

# Changes made by another developer are present but not in your local remote refs.
# You want to rebase your changes.
git checkout master
git pull # causes local refs to update
git checkout -
git rebase master
# Now this acts the same as --force and overwrites changes made by the other developer.
git push --force-with-lease