Search code examples
gitrebasesquash

How do I squash commits on a branch that has children


So I have a situation with a master and a bugfix branch that continues it. I tried squashing some commits on master and then rebasing bugfix on it but I got merge conflicts. What is the proper way to do it ? I work locally and there is no remote.

It looks like this :

A - B - C - D - E - F [master]
                     \                 
                      G - H - I - J - K [bugfix]

I want to squash A - B - C - D - E - F and still have bugfix continuing the squashed master branch.


Solution

  • Jubob's point about shared history is a very important one, as rebasing or squashing shared commits is strongly discouraged.

    I will assume that you are working with local commits.

    Suppose you started with this:

    [master] A---B---C---D
                          \
    [bugfix]               1---2---3
    

    and you decided to squash B, C and D into a new commit D'

    [master] A---D'
              \
    [bugfix]   B---C---D---1---2---3
    

    Note that commits B, C and D remain in the bugfix branch. If you simply rebase bugfix onto master, Git will try to do this:

    [master] A---D'
                  \
    [bugfix]       B---C---D---1---2---3
    

    But the changes introduced by B, C and D are already contained in D'. What you really want to end up with is this:

    [master] A---D'
                  \
    [bugfix]       1---2---3
    

    You can accomplish this with the --onto option of rebase:

    git rebase --onto master D bugfix
    

    D should be the latest commit in bugfix that should not be included when rebasing.