< up >
2024-03-11

git force-push for professionals

tl;dr: Use --force-with-lease instead of --force to avoid overwriting upstream changes.

Introduction

1st git rule: don’t force-push. But as an atendee of the rebase-i-make-my-own-history club, force push is necessary.

But nevertheless overwrites happen, especially when multiple people work on the same branch. This happens mostly for automatic pull-requests like dependency updates.

--force-with-lease got your covered:

Imagine that you have to rebase what you have already published. You will have to bypass the “must fast-forward” rule in order to replace the history you originally published with the rebased history. If somebody else built on top of your original history while you are rebasing, the tip of the branch at the remote may advance with their commit, and blindly pushing with –force will lose their work.

Example

  1. make a change upstream
  2. make a change locally
  3. push locally: `git push –force-with-lease’:
To github.com:RaphaelPour/120.git
 ! [rejected]        main -> main (stale info)
 error: failed to push some refs to 'github.com:RaphaelPour/120.git'

Otherwise, --force would just steamroll’ main:

Enumerating objects: 11, done.
Counting objects: 100% (11/11), done.
Delta compression using up to 16 threads
Compressing objects: 100% (11/11), done.
Writing objects: 100% (11/11), 4.64 KiB | 2.32 MiB/s, done.
Total 11 (delta 3), reused 0 (delta 0), pack-reused 0 (from 0)
remote: Resolving deltas: 100% (3/3), done.
To github.com:RaphaelPour/120.git
 + 2b495e8...ac28eb3 main -> main (forced update)