Force-push to a remote

TL;DR: It’s true as a rule of thumb you should not use git push --force. On the other hand, if you stay aware of how you’re affecting the commits on the remote, git push --force-with-lease (notice the difference) is really useful and wonderful.

“Force pushing” actually exists for a very good reason, and especially on a small team (definitely as a solo dev), you will find that it is a relatively natural and common occurrence. Instead of using git push --force, however, go ahead and do yourself a favor and generally only use git push --force-with-lease. The “with lease” bit means that if your push would steamroll any commit(s) on the target branch that you simply don’t have in your local repo, it will fail. This is a good safeguard to make sure you’re not shooting yourself in the foot, as having them present in your local repo means you will at least be able to recover the missing commit(s) if you steamroll out something that really should be there.

It’s useful after rebasing

Rebasing changes history (by reordering, adding, or removing commits, or otherwise modifying the defining characteristics of any commit), which means when you git push your branch after rebasing it on top of another branch, you will find that git complains, because your local branch no longer contains the history of the branch. It’s not a shocker – you should expect this because you rebased your local branch, which changed its history.

Especially if you want to avoid merge commits, you’ll need to periodically rebase feature branches on top of your mainline branch. Once you do this, you won’t be able to push to your remote feature branch without forcing.

Other reasons you might find yourself needing to force-push include:

  • After squashing multiple piecemeal/exploratory commits into an atomic commit before (fast-forward) merging to the mainline branch
  • After reordering commits for whatever reason
  • After updating commit messages