push --force-with-lease by default

There currently is no way to configure git to always use force-with-lease instead of force. As such the next best available option is, as so often, to create an alias which serves this purpose.

EDIT This is still true in May 2022. But git 2.30 added an additional option force-if-includes which makes force-with-lease even safer; checkout this in-depth answer if you want to understand the reasoning.

Create an alias

To create an alias one would use git config --global alias.<alias-name> <command>, in our case I would suggest something similar to this.

git config --global alias.pushfwl "push --force-with-lease"

This will create an entry in your global .gitconfig file (which you can usually find in your home directory). After this you can use git pushfwl to force-with-lease.

Get your hands dirty

Alternatively you could decide to implement this feature yourself! If you aren't sure where to start, you might want to take a look at the documentation directory in the git repository. Here you can find the coding guidelines and information on how to submit patches.

You can find all these links and more on the official community page.


My solution was to create a wrapper script, and use an alias so that I always use it in place of the real git.

Whenever I try to git push -f, I see the following:

⚡ git push -f
use this instead so you don't cause race conditions in the 
repo: git push --force-with-lease

Some advantages of this script are:

  • it trains me to habitually use --force-with-lease, so i don't get nagged when i get it wrong
  • if, for some reason, we really do need to force push, git push --force will work.

How to implement it:

  1. create a custom script that will pass through any params to git, except for -f
  2. alias that script so we use it instead of git

These instructions assume Linux or Mac, running bash. I haven't tried this with zsh or Windows, but I assume it'll work there too.

~/.bash_profile:

alias git=~/.git_wrapper.sh

~./git_wrapper.sh:

#!/bin/bash
for arg in "$@"; do
    if [ "$arg" = "push" ]; then
        ispush=1
    elif [ "$ispush" = 1 -a "$arg" = '-f' ]; then
        echo "use this instead so you don't cause race conflicts in the repo: git push --force-with-lease"
        exit 1
    fi
done

git "$@"

With those changes, restart your terminal and git should now get uppity when you try to force push.

Tags:

Git