Force pushing git branches with a safety net

2 min read

This post is part of my Today I learned series in which I share all my learnings regarding web development.

Recently, I came across the for me unknown command line flag of git push--force-with-lease. After working years with git, I feel relatively comfortable with it today. I manage to squash commits, change the last commit or rebase things on the command line with confidence.

When you apply a lot of git magic rewriting the history of your git repository you might approach the point where you have to force push to a remote branch because it refuses to "accept your git magic".

# lots of git magic followed by:

$ git push origin foo --force 
# ☝️ will update the remote no matter what

Performing git push with the --force flag can be brutal. It overwrites the particular remote branch with your local version without any additional checks or asking for permission. When you're working with other people on the same branch, it can quickly happen that you overwrite commits done by your team members.

Think of the following example:

  • you do a git pull to get the latest changes
  • you do some git magic, but it takes a while
  • you force push your changes

Now let's assume it took you a while to perform a commit squash and another coworker pushes in the meantime new changes to the remote.

You'll overwrite these with your force push then without knowing.

The --force-with-lease can help to avoid this because it won't update the remote branch when it isn't in a known state.

# lots of git magic followed by:

$ git push origin foo --force-with-lease
# ☝️ can still be rejected when
# someone updated the branch upstream

There a few more minor things to know about --force-with-lease and Steve Smith wrote an excellent article on the whole topic. I recommend to check that one out. ;)

Tags

Load time