'Why is `git push --force-with-lease` failing with "rejected ... stale info" even when my local repo is up to date with remote?

I'm trying to force push a rebase of a feature branch to a remote repository. To be a bit safer, I'm trying to use --force-with-lease to make sure no other changes have happened in the branch since I last fetched it.

This is failing for reasons I don't understand:

$ git branch
* my-branch
  master

$ git push --force-with-lease origin my-branch -u
To gitlab.com:example/my-project.git
 ! [rejected]        my-branch -> my-branch (stale info)
error: failed to push some refs to '[email protected]:example/my-project.git'

I tried a fetch to see if my local cache had somehow gotten out of sync:

$ git fetch

$ git push --force-with-lease origin my-branch -u
To gitlab.com:example/my-project.git
 ! [rejected]        my-branch -> my-branch (stale info)
error: failed to push some refs to '[email protected]:example/my-project.git'

I tried simplifying the push command a bit:

$ git push --force-with-lease
To gitlab.com:example/my-project.git
 ! [rejected]        my-branch -> my-branch (stale info)
error: failed to push some refs to '[email protected]:example/my-project.git'

I tried limiting the check to my branch:

$ git push --force-with-lease=my-branch:origin/my-branch
To gitlab.com:example/my-project.git
 ! [rejected]        my-branch -> my-branch (stale info)
error: failed to push some refs to '[email protected]:example/my-project.git'

As you can see, it fails the same way every time.

Why is my push failing, and how do I fix it?



Solution 1:[1]

In this case it turned out that the problem was that the remote branch had been deleted, but there was still a copy of it in my local repo. Fetch doesn't delete local copies by default, which is why it had no effect.

Adding the --prune option to my initial git pull (before doing my rebase) corrects this problem.

Solution 2:[2]

In my case a plain git fetch followed by the push again solved the problem.

Solution 3:[3]

If you have just done your rebase and don't want to start over again please run git remote prune origin. If you then run git push --force-with-lease again, it will work.

Solution 4:[4]

You may face this issue, when you're checked out to the pr using gh pr checkout <num> and trying to force push after making some changes.

The correct way to push to someone else pr is to add a remote to there repo and checkout to the branch which was used to create the pr. Then you can push your commits. It'll appear in the pr.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Laurence Gonsalves
Solution 2 Bohumir Zamecnik
Solution 3
Solution 4 Krishna