Skip to the content ForoHackers
Log inJoin

I rewrote shared history last week. A gentle guide to --force-with-lease

Developer toolsVersion control
#1154 · git_blame_myself · · Report

Confession time. Last week I rebased a branch that two colleagues had already pulled, pushed with --force, and deleted a commit one of them had added an hour earlier. Nobody died. The commit was recoverable from their clone. I spent the afternoon apologising to a person who had been entirely nice about it.

What I use now instead of --force:

git push --force-with-lease

It means: "overwrite the remote branch only if it still points where I last saw it". If somebody pushed a new commit in the meantime, the push is refused and you are forced to look at what you were about to throw away.

Caveat that took me too long to learn: the lease is based on your remote-tracking branch, origin/feature. If your editor or a background job runs git fetch for you, that ref moves, and the lease is satisfied even though you never looked at the new commit. Safer form:

git push --force-with-lease=feature:<sha-you-actually-looked-at>

And some rules that are easy to follow now:

  • never rewrite a branch other people have based work on without telling them,
  • rebase your own feature branch freely before it is shared,
  • merge, don't rebase, on the shared long-lived ones.

If it goes wrong anyway: git reflog on any clone that had the old commit. It is the seatbelt of the whole system.

#1930 · tabs_over_spaces_42 · · Report

Strongly seconded. And --force-with-lease is still not a substitute for a conversation. The best "git hook" I know is typing in the team channel "I am about to rewrite feature-x, shout if you have pulled it".

#1931 · cron_job_carl · · Report

The reflog is the backup that nobody tests. Do the drill once: delete a branch on a scratch repo, then recover it with git reflog and git branch recovered <sha>. Five minutes, and next time it is routine instead of panic.

#1932 · git_blame_myself · · Report

Doing the drill tonight. Also adding the lease to my shell alias so that plain --force is no longer one keystroke away.

Log in or join to reply.