Search code examples
gitazure-devopsgit-revert

Revert and delete Azure DevOps commit history?


I made a small commit and pushed it to our main branch in Azure DevOps. I realized that this commit was obsolete, as it was based on wrong assumptions and miscommunication with my colleague, who made that last commit to the main.

However, I decided to revert my commit via a pull request, but I must have done it wrong. I reverted that revert, and I am basically back to the status of my original commit - which in a next step I would revert again (this time "right").

So the code base and all files would be fine in the main branch afterwards, it's just that our Azure DevOps history looks quite 'messy'. E.g. the commit line (graphical representation of commits with lines and dots).

I am quite aware that one of the purposes of using Git is full transparency, but we are a small team and communicate very open and agreed, that if possible we would like to get rid of that little 'intermezzo' of mine, if possible.

Is there any way to achieve this?


Solution

  • To get rid of one or more commits from the commit history, you could use git reset --hard or git rebase --interactive and then push force to the remote repository.

    In the first case, you would reset your repository to a specific commit, dropping the last n commits. In your case, the last three commits.

    # make sure to be on the right branch
    git checkout my_branch
    
    # resetting to the third to last commit
    git reset --hard HEAD~3
    
    # or alternatively, resetting to a specific commit via its SHA1
    git reset --hard <SHA1-third-to-last-commit>
    
    # aligning the remote's branch' history and tip to the local branch
    git push --force
    

    In the second case, you could perform an interactive rebase where you would drop the last three commits.

    # make sure to be on the right branch
    git checkout my_branch
    
    # starting the interactive rebase
    git rebase --interactive HEAD~3
    
    # aligning the remote's branch' history and tip to the local branch
    git push --force
    

    During the rebase, an editor will be opened, showing you your last three commits with the pick option pre-selected. Replace pick with drop, save, and finally close the editor.

    drop d790c9e my undesired commit
    drop 61f4eb1 first revert
    drop f33cd8c revert of the first revert
    

    Warning: as a general rule of thumb, before force pushing, make sure that all developers are aware that you're rewriting the branch' history and that none of their works is based on the dropped commits.