Search code examples
gitgit-resetgit-revert

Git revert several commits


I have made several commits to my local branch estimation and pushed them to the remote branch estimation.

Now, I want to remove the last 3 commits completely.

I tried to do git reset HEAD^ and git reset HEAD --hard 3 times but when I tried to push the changes, it complained about tip of the HEAD not aligned.

How do I do it?

EDIT:

The history looks like following:

commit e572aab4e18

commit e21e7310bc4

commit 4f372a513da

commit 31a4ac607ae

commit a1a6e3f02dd

I would like to remove top 4 and go back to commit a1a6e3f02dd and make both local and remote branch on same HEAD.


Solution

  • First: You should only do this for a branch that you're not sharing; if the branch is checked out by others, this process will put their local copies out of sync with the remote and they won't be able to just push commits to the branch anymore. This can be sorted out but it's potentially a mess.

    Given that, if I understand you correctly, you're in this situation:

    xxxxxxx Bad commit #3
    yyyyyyy Bad commit #2
    zzzzzzz Bad commit #3
    wwwwwww This and everything before it are fine
    

    You want to drop the commits after wwwwwwww and fix the remote branch to match.

    First, back up the branch you're doing surgery on so you can restore it if you mess up, and then switch back to the branch you want to remove commits from.

    git checkout -b broken-estimation
    git checkout estimation
    

    Run git log to find the SHA1 of the first commit you want to keep. Once you have that SHA1, reset the branch to that:

    git reset --hard kkkkkkk
    

    where kkkkkk is the SHA1 of the first commit you want to keep on the branch.

    Run git log again to ensure you've got the desired SHA1 as the tip of this branch; it should be the first commit you see in the git log output. If you've not trimmed off enough commits, redo the git reset --hard with the proper SHA1 to remove more commits.

    If you removed too many commits, restore the estimation branch from the backup you took:

    git checkout -B estimation broken-estimation
    

    and redo the git log to find the SHA1 of the commit you want at the tip, followed by git reset --hard kkkkkkk (with kkkkkkk being the SHA1 you actually wanted) to drop the undesired commits following that commit.

    Once you've got the branch in the desired state, you can push the fixed branch to the remote, replacing the old version:

    git push -f the_proper_remote estimation
    

    Once you're certain that your repairs are correct, you can delete the backup copy of the branch:

    git branch -d broken-estimation