Squash my last X commits together using Git

前端 未结 30 4112
醉酒成梦
醉酒成梦 2020-11-21 05:17

How can I squash my last X commits together into one commit using Git?

30条回答
  •  孤城傲影
    2020-11-21 05:38

    In question it could be ambiguous what is meant by "last".

    for example git log --graph outputs the following (simplified):

    * commit H0
    |
    * merge
    |\
    | * commit B0
    | |
    | * commit B1
    | | 
    * | commit H1
    | |
    * | commit H2
    |/
    |
    

    Then last commits by time are H0, merge, B0. To squash them you will have to rebase your merged branch on commit H1.

    The problem is that H0 contains H1 and H2 (and generally more commits before merge and after branching) while B0 don't. So you have to manage changes from H0, merge, H1, H2, B0 at least.

    It's possible to use rebase but in different manner then in others mentioned answers:

    rebase -i HEAD~2

    This will show you choice options (as mentioned in other answers):

    pick B1
    pick B0
    pick H0
    

    Put squash instead of pick to H0:

    pick B1
    pick B0
    s H0
    

    After save and exit rebase will apply commits in turn after H1. That means that it will ask you to resolve conflicts again (where HEAD will be H1 at first and then accumulating commits as they are applied).

    After rebase will finish you can choose message for squashed H0 and B0:

    * commit squashed H0 and B0
    |
    * commit B1
    | 
    * commit H1
    |
    * commit H2
    |
    

    P.S. If you just do some reset to BO: (for example, using reset --mixed that is explained in more detail here https://stackoverflow.com/a/18690845/2405850):

    git reset --mixed hash_of_commit_B0
    git add .
    git commit -m 'some commit message'
    

    then you squash into B0 changes of H0, H1, H2 (losing completely commits for changes after branching and before merge.

提交回复
热议问题