Git protip: gently force push
By Maxime Bréhin • Published on 23 January 2023
• 1 min
Cette page est également disponible en français.
Sometimes we must force the push to partially rewrite the remote history with our local one (e.g. after a local rebase). That subject is pretty controversial. Some people say we should never change the remote history, and as always with “always or never” stances, I believe they’re wrong…
That strife usually comes from a partial understanding of what the
push command can actually do. We can’t blame users for that: the command is poorly designed, with many option misnomers and dangerous defaults. Indeed, the easiest way is the most dangerous one: autocompletion starts with the infamous
To add insult to injury, most IDEs and editors offer a single approach to forced pushes, based on that very
--force alone! 🤦♂️🤦♂️
This is a shame, considering there’s an alternate option that ensures we only override our project history if we fetched remote updates beforehand:
Note however that, as another example of poor design, this variant alone isn’t safe enough: to also ensure that what we fetched was also applied to our local history, we must add yet another option:
Knowing that, you should ban the single
--force option as your default, unless you indeed want to erase what’s on the remote branch, regardless of third-party work there.
git push --force-with-lease --force-if-includes is hard to remember and to type, you likely want an alias. Here is mine:
git config --global alias.push-with-lease 'push --force-with-lease --force-if-includes'
More tips and tricks?
We’ve got a whole bunch of existing articles and screencasts and more to come. Also check out our 🔥 killer Git training course: 360° Git!