Search code examples
githublocalcommitundogit-remote

Error: Undo last git commit on both local and remote


Let say I have a branch on my local A and this is exist in remote as well origin/A. Both my local and remote branch is in sync. For example in local I have commit like - C1, C2, C3 and C4 and same in my remote as well.

Now I want to revert the change that I commit for C4. I already pushed this to remote, so I want to do that in remote as well.

NOTE: I found lot of question in stackoverflow for this. Here is one. But it's not working for me!

As per this I tried:

git reset --hard HEAD~1
git push -f origin A

First command works fine and my local version does not have the C4 commit now.

Problem is in the second command. It showing remote: error: denying non-fast-forward refs/heads/A (you should pull first).

How to solve this issue?


Solution

  • Your current approach to remove the most recent commit is completely correct:

    git reset --hard HEAD~1
    git push -f origin A
    

    Unfortunately, GitHub does not seem to be allowing you to do the force push. However, there is an alternative. You could instead git revert the most recent commit. This will add a new commit on top of the branch which will undo whatever the most recent commit did. Presumably you won't have any problems in adding a new commit in GitHub. If you want to go this route, try the following:

    git revert HEAD
    git push origin A
    

    Your new branch diagrams will be left looking like this:

    remote: C1 -- C2 -- C3 -- C4 -- R
    local:  C1 -- C2 -- C3 -- C4 -- R
    

    where R is the commit which reverted commit C4. Functionally speaking, the two branches will behave as if neither the C4 nor R commits are there, i.e.:

    local/remote: C1 -- C2 -- C3