Search code examples
gitgit-mergesquashgit-squash

How to squash commits that contain a merge commit


Is there a way to squash commits that have a merge commit? I am able to squash when there is not any merge commits but I don't know how to do it when there is one.

Like these two commits.

git tree


Solution

  • Here I've built a graph like yours before the merge:

    * bbcdb99 (HEAD -> feature) d
    | * d568728 (master) c
    | * 8714c7f b
    |/  
    * f1aeb9a a
    

    Now I merge master into feature:

    *   264fc6c (HEAD -> feature) Merge branch 'master' into feature
    |\  
    | * d568728 (master) c
    | * 8714c7f b
    * | bbcdb99 d
    |/  
    * f1aeb9a a
    

    Well, if I want to squash feature down to just one commit and erase the merge commit, then I should not have merged like that. I should have done a squash merge! However, all is not lost. I can just reset soft back to f1aeb9a and make a new commit:

    $ git reset --soft f1aeb9a
    $ git commit -m"new commit"
    

    That gives this:

    * e26b588 (HEAD -> feature) new commit
    | * d568728 (master) c
    | * 8714c7f b
    |/  
    * f1aeb9a a
    

    Now "new commit" contains everything that was done on feature including the results of the merge from master. But of course we have lost the merge commit.