Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nh2/4c0dab0966a17bc3f84719df03bcd72b to your computer and use it in GitHub Desktop.
Save nh2/4c0dab0966a17bc3f84719df03bcd72b to your computer and use it in GitHub Desktop.
git: Squashing commits on a branch including merges while retaining some individual commits

Initial state

We want to squash the v commits in

v1
v2
v3
k1
k2

where the history v1-v2-v3 has complicated merges inside, and we want to retain k1 and k2 as separate commits.

The desired state is:

[ v1 v2 v3 ]
k1
k2

where [ ... ] means "squashed into a single commit".

How to get there

Initial state:

v1
v2
v3
k1
k2

Step 1: Squash everything.

[ v1 v2 v3 k1 k2 ]

Step 2: Revert (in reverse order) and cherry-pick (in desired order) the k commits.

[ v1 v2 v3 k1 k2 ]
revert-k2
revert-k1
k1          (cherry-picked)
k2          (cherry-picked)

Step 3: Squash the revert-k1 commit into the previous.

[ v1 v2 v3 k1 k2 revert-k2 revert-k1 ]
k1
k2

This is equivalent to:

[ v1 v2 v3 k1 revert-k1 ]
k1
k2

This is equivalent to:

[ v1 v2 v3 ]
k1
k2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment