Search code examples
gitgit-revert

Revert a pushed merge to erase local undesired changes pushed by mistake


I pushed a merge in a parent repository with submodules. Lets say I merged my main branch in my feature/Foo branch. By mistake I pushed along with the merge, local changes and locally created new files that should not have been pushed.

For example I have:

LOCAL CHANGES: (uncommitted changes)

  • 5 locally changed files
  • 5 locally new files

MERGE CHANGES: (coming from the main branch)

  • 5 change by the merge files
  • 5 added new by the merge files

Now I need to revert the pushed merge. I know how git revert works to revert a commit, creates just a commit with the opposite changes, so when reverting a merge, it reverts all the changes. Local changes + changes carried along with the merge are reverted, so an opposite change is created to undo all the changed/created files performed in the merge commit.

Solution I adopted:

So to leave the version as I wanted, this is, with the changes only brought by the MERGE CHANGES and not the local changes, I have to file by file select/discard the cahnges I want in the revert commit, this is, check the log manually and discard the changes I do not want for the revert. These are the ones brought by the merge because I want to revert only the files changed/added locally by mistake.

Why?

Because if I revert all the changes, I am reverting also the ones brought by the merge and after If I re-merege that the comment with the changes I need, nothing happens, because merge flow was solved already. By these I mean that the main branch changes are not brought again to the feature/Foo branch. Seems that even though I am 2 commits ahead from the original merge after the revert, the merge flow was solved in the original merge commit (check "Final commit to restore original merge" in the explanatory graph).

My desire:

Get to know the way to do this with git, and not manually checking the log of each of the file for a selective revert. Ideally, not removing remote branches/commits an in the safest of the ways. Would not matter if the revert appears in the history.

Explanatory graph:

enter image description here


Solution

  • I think it is a lot easier to simply create a new commit with some of the local files checked out from an older version. No need to revert the merge and then to apply fancy magic to this merge commit :)

    It should be as simple as:

    git checkout commit-before-merge -- file1 file2 file3
    git commit -m 'Remove accidental local changes'
    

    Description: copy the content of the specified files from the commit before the merge. Create a commit with these changes. This effectively "reverts" those changes.