gitgithubrebaseundo

Git undo force push to remote branch


I need to undo a force push to a remote branch, or apply the previous changes that were merged to the remote branch before the force push from my local.

This is a release branch. The origin release had many fixes merged into it that I was not aware of and I did not fetch to my local. When I pushed new changes from my local release branch to the origin, I force-pushed them. Now the origin release branch doesn't have any of the fixes that were merged into it.

I was able to rebase most of the individual commits with git rebase <COMMIT ID>, but some of them are returning the error fatal: no such branch/commit '<COMMIT ID>'.

I am assuming git fetch did not get the entire log? Why would some of these work and some not? They're all relatively recent, within the last ~20 commits pushed to the repo.


Solution

  • The easy solution: Get someone else to fix it

    Someone else on you team might have a version of the release branch which has all the old changes. Have them force push it.


    The reflog solution

    Look through the reflog of the release branch remote. You do however not have any guarantees that you have the correct state in your reflog since you used --force (I don't know the state of the remote branch but want to overwrite it anyway) rather than --force-with-lease (only overwrite the state of the remote if it is in the state I know)
    If you never had the deleted version try it on a pc where you know it has existed.


    The "merge it all again" solution

    Remember that even if the other developers deleted their branches after merge, if anyone on the team uses git pull/git fetch without the --prune option then they will still have the remote branches locally on their pc.


    Final comment on --force

    Don't use --force. The only times were a normal push will fail (and --force will succeed) is when there are other changes on the branch you are pushing to.
    It is useful for rewriting history for branches you yourself own. It will however always cause problems if you are working on a branch with someone else.

    I hope any of these will help.