Tomáš Fejfar
Tomáš Fejfar

Reputation: 11217

How to prevent force push for a branch that might have been rebased

The idea was that --force-with-lease should prevent you from overwriting remote branch when it's unsafe. But in this scenario it does not work because the fetch.

How would you prevent this?

Upvotes: 2

Views: 989

Answers (1)

Chris Maes
Chris Maes

Reputation: 37782

That is not how git push --force-with-lease works. git push --force-with-lease was designed to avoid the following scenario:

# developer B
git checkout feature-branch
git commit -m "add part B"
git fetch # make sure no changes were made by developer A
git rebase origin/master # rewrite history for some reason
# developer A
git checkout feature-branch
git commit -m "add part A"
git push

If developer B now runs git push --force , he will throw away the work just pushed by developer A, since that work was added after B ran git fetch.

  • git push --force would pass, thus throwing away developer A's work
  • git push --force-with-lease would not pass (since origin/feature-branch has changed), thus preventing developer B from crushing A's work.

The underlying idea is that developer B is smart enough not to throw away developer A's work when rebasing.

I don't know of any pure git features that prevents force pushes on a branch, but most repository management services (bitbucket, gitlab, github, ...) will allow you to prevent force pushes on certain branches.


tip

I created a small script git-diff-remote which I put in /usr/bin:

#!/bin/bash
git fetch
git diff "$@" @{u} HEAD

now I always run

git diff-remote

which shows me what I will crush when running

git push --force-with-lease

Upvotes: 1

Related Questions