gitgitlabgit-revert

Reverse last commit from remote repository


After I merged master into my private branch, I made some mistakes in the build file. How can I remove this commit from remote?

When trying

git revert <SHA>

I get the following error message: Error: commit is a merge but no -m option was given. fatal: revert failed

Edit: this can be resolved by add the mailine number, but how do find out what parent number I want to revert to?


Solution

  • Be careful when reverting merge commits. As people have already said in the comments, when you revert a merge commit, or in general any commit, you're just introducing a new commit with opposite changes on top of the one to revert.

    From a content point of view, this action brings back your repository to the same state before the commit to revert was applied. All of your tracked files will look exactly like you wished. However, from a history point of you, you would still have the reverted (merge) commit with a new (opposite) commit on top.

    This situation can be represented as follows, with M being the merge commit, and M' the revert commit.

    A -- B -- C                 branchA
                 \
    D -- E -- F -- M -- M'      branchB
    

    This scenario has important implications, as the merge-base (the common ancestor between two branches) has now changed, and this is commit C (a.k.a branchA's tip), i.e. the only commit reachable from both branches. This means that a new merge won't include the same set of changes brought in by the previous merge, because those changes have already been integrated (badly) in your branch.

    In your scenario, the best thing you could do is to hard reset your branch to the commit before the merge, re-merge correctly the two branches, and then force push to the remote. Assuming that this is your current situation.

    A -- B -- C                 branchA
                 \
    D -- E -- F -- M            branchB
    

    You could enter:

    # make sure to be on branchB
    git checkout branchB
    
    # reset to the first parent of the merge commit
    git reset --hard branchB^
    
    # merge branchA into branchB correctly
    git merge branchA
    
    # force push to the remote, overwriting the previous (wrong) history with the correct one
    git push --force-with-lease origin branchB