Search code examples
gitgithubgit-revert

Revert HEAD{2} from a branch without reverting HEAD{1}


I am trying to contribute to a GitHub repository. The commit from before I started contributing I'll call "a". I made a commit "b" and my pull request for it was accepted. I then made another commit "c" and I have made a pull request for it but it has not yet been accepted. I made another commit "d" which I committed to a new branch so I'd be able to pull it separately. However, I forgot to rebase back to "b" before creating "d" so the branch for "d" also contains "c" meaning "c" would exist on both branches which I don't want.

So, currently I have this

a-b-c-d

But I want this

a-b-c
  \-d

How can I accomplish this?

This question has been marked as a duplicate of questions asking how to undo the last commit, but these do not answer my question because it's not the last commit I'm trying to undo but instead a commit twice back. Rebasing to HEAD{2} also doesn't work because that still undo's the last commit.


Solution

  • The easiest way:

    1. Remember the d's SHA1, let say it is 535dce28f1c68e8af9d22bc653aca426fb7825d8.
    2. git reset --hard HEAD~2
    3. git cherry-pick 535dce28f1c68e8af9d22bc653aca426fb7825d8

    More advanced:

    1. git rebase -i HEAD~3
    2. Change the second pick to drop, or remove that line, then save the file and exit from the editor.

    More advanced 2:

    1. git revert HEAD~1 will make b-c-d-^c
    2. git reset --soft HEAD~3 will reset to b and keep the changes on the disk
    3. git add -A && git commit will make b-d'.