Search code examples
gitgit-squash

Git delete past commits from the tree as well as working directory


Currently, my git tree looks like this

                 master
                   ^
                   |
                Commit 3
                   ^
                   |
                Commit 2
                   ^
                   |
                Commit 1
                   ^
                   |
           remote/origin/master

What I want to do is, remove the changes from Commit 2 and 3 like they never existed and then push the changes. There were some uncommitted changes that I stashed (They are mainly config files and makeFiles, so I don't want to have them in the tree). Also, I would like to know what is the best process to follow so that I don't end up messing my working directory like I have done now. Please help

Git-newbie,

Thanks.


Solution

  • rebase is your friend here. The rebase command offers an interactive mode in which you can decide on what to do for each commit in a specified commit range.

    The probably easiest way would just to rebase on top of the remote master branch.

    git rebase -i origin/master master
    

    You are telling git to rebase the master branch on top of it's remote counterpart. Without the -i flag (interactive) this would effictively do nothing.

    Now your configured editor should open and you should see something like this:

    pick abcdefg Commit 1
    pick hijklmn Commit 2
    pick opqrstu Commit 3
    (... maybe more commits)
    
    # Here will be comments which explain what's going on ...
    

    Now to drop commits you simply have to delete the corresponding line from the file. So it should look like this:

    pick abcdefg Commit 1
    (... maybe more commits)
    
    # Comments can stay ...
    

    Now close the editor and git will rebase the commits as specified on top of the origin/master branch.

    You can read more about interactive rebasing in the Changing History Chapter from the GitPro book or in the rebase documentation.

    Hope that helps!