How to force push in Git with style (and some safety)

Published on in Git

Last updated on

Never run git push --force. Instead run git push --force-with-lease or alias it to git please.

Table of contents

Please be polite

Never run git push --force or you might overwrite commits pushed by others. Instead run:

git push --force-with-lease

Or if using my git aliases:

git please

Please = force push with lease. So polite!

(Unfortunately I don't remember where I found this alias, so I can't give proper credit.)

--force vs --force-with-lease

Git's manual is too wordy, so I'm relying on the answers to git push --force-with-lease vs --force on Stack Overflow.

chevybow writes (slightly modified and shortened):

--force overwrites a remote branch with your local branch.

--force-with-lease is a safer option that will not overwrite any work on the remote branch if more commits were added to the remote branch (by another team member or coworker or what have you). It ensures you don't overwrite someone else's work by force pushing.

I just think of --force-with-lease as the option to use when I want to make sure I don't overwrite any teammate's code. A lot of teams at my company use --force-with-lease as the default option for a fail-safe. It's unnecessary in most circumstances but will save you lots of headache if you happen to overwrite something that another person contributed to remote.

Warning: fetching is risky

G. Sylvie Davies writes:

There's a sad implication here: since git fetch updates all refs under "refs/remotes/origin/*" to their latest versions, this combination of commands is essentially identical to git push --force:

git fetch

# The command below behaves identically to "git push --force"
# if a "git fetch" just happened!

git push --force-with-lease

To work around this inherent weakness in git push --force-with-lease I try to never run git fetch. Instead I always run git pull --rebase whenever I need to sync with upstream, since git pull only updates a single ref under refs/remotes, keeping the "lease" of --force-with-lease useful.

Does your code editor or IDE do automatic fetching? You might want to disable that unless you can accept the risk.

When to force push (with lease)

Some say that one should never force push. I say that's bollocks.

If you are working on your own short-lived branch (not master or main), feel free to rewrite its history: rebase, squash etc. After rewriting a branch's history, a force push is needed.

The "if" in the previous paragraph is a misnomer. Of course you are working on short-lived branches and not directly on the master/main branch, right? If you are not yet doing trunk based development, look it up.