gitgit-resetgit-revert

How can I undo pushed commits using git?


I have a project in a remote repository, synchronized with a local repository (development) and the server one (prod). I've been making some commited changes already pushed to remote and pulled from the server. Now, I want to undo those changes. So I could just git checkout to the commit before the changes and commit the new changes, but I'm guessing that there will be problems to push them again to remote. Any suggestion on how should I proceed?


Solution

  • You can revert individual commits with:

    git revert <commit_hash>
    

    This will create a new commit which reverts the changes of the commit you specified. Note that it only reverts that specific commit, and not commits that come after that. If you want to revert a range of commits, you can do it like this:

    git revert <oldest_commit_hash>..<latest_commit_hash>
    

    It reverts all the commits after <oldest_commit_hash> up to and including <latest_commit_hash>. Some versions of git also revert the <oldest_commit_hash> itself, so double check if that commit gets reverted or not. You can always drop the latest revert commit (which reverts the oldest commit) with g reset --hard HEAD~.

    To find out the hash of the commit(s) you can use git log.

    Look at the git-revert man page for more information about the git revert command. Also, look at this answer for more information about reverting commits.

    Extra note for re-applying reverted commits:

    Usually you revert commits because you discovered the commits that you pushed turn out to have an issue. Then you first want to restore the repo to a stable state, before you continue to fix the issue. So then you would first do the git revert, as described before. Then push those revert commits, so the remote is stable. After that you would want to re-apply the reverted commits locally, so your local repo's files are back to the state before the revert. Then you can fix the issue.

    To re-apply the reverted commits, you have to revert the revert commits. So what you would do, is to again execute the git revert command, but then with the range of commits of the revert commits. So your new revert commits will revert the previous revert commits. Then your files are back to the state before the first revert. Then you can fix the issue, create a new commit with the fix, and then push the new commits.