Search code examples
gitgit-rewrite-history

Edit git history


In my git repository I have only the master branch which contains 8 commits. At commit 2 I have inserted one wrong class and now I would rewrite the git history in such a way in commit 2 I haven't the wrong class and consequently the next commits have not it. What's the right method to do this?

Thanks in advance.


Solution

  • You could use this: git rebase -i HEAD~7, which will allow you to interactively rebase on the last 6 commits prior to the current HEAD.

    This will, by default, open a text editor pre-populated with some explanatory text and the last 7 commit IDs. You can basically follow the instructions, and change the line corresponding to the incorrect commit to start with edit:

    pick f7f3f6d whatever
    edit a5f4a0d did something wrong
    pick 310154e added foobar.junk and whatever.html
    pick d332af2 something else
    pick 7e2f413 yadda yadda
    ...
    
    #
    # Commands:
    #  p, pick = use commit
    #  r, reword = use commit, but edit the commit message
    #  e, edit = use commit, but stop for amending
    #  s, squash = use commit, but meld into previous commit
    #  f, fixup = like "squash", but discard this commit's log message
    #  x, exec = run command (the rest of the line) using shell
    #
    # These lines can be re-ordered; they are executed from top to bottom.
    #
    # If you remove a line here THAT COMMIT WILL BE LOST.
    #
    # However, if you remove everything, the rebase will be aborted.
    #
    # Note that empty commits are commented out
    

    After you save and exit, your index will then be rewound to the state it had just after git commiting the commit which you are editing.

    You should then edit it to correct it (e.g., git commit --amend), and optionally add new commits on top of it as well. After all that's done, use this to continue and replay to remaining (newer) commits on top of it: git rebase --continue.

    Note that this last line can trigger merge conflicts; I'm assuming you already know how to deal with those :)