I believe you will find different recipes for that in the SO question "How do I combine the first two commits of a git repository?"
Charles Bailey provided there the most detailed answer, reminding us that a commit is a full tree (not just diffs from a previous states).
And here the old commit (the "initial commit") and the new commit (result of the squashing) will have no common ancestor.
That mean you can not "commit --amend
" the initial commit into new one, and then rebase onto the new initial commit the history of the previous initial commit (lots of conflicts)
Rather (with A the original "initial commit", and B a subsequent commit needed to be squashed into the initial one):
# Go back to the last commit that we want to form the initial commit (detach HEAD)
git checkout <sha1_for_B>
# reset the branch pointer to the initial commit,
# but leaving the index and working tree intact.
git reset --soft <sha1_for_A>
# amend the initial tree using the tree from 'B'
git commit --amend
# temporarily tag this new initial commit
# (or you could remember the new commit sha1 manually)
git tag tmp
# go back to the original branch (assume master for this example)
git checkout master
# Replay all the commits after B onto the new initial commit
git rebase --onto tmp <sha1_for_B>
# remove the temporary tag
git tag -d tmp
That way, the "rebase --onto
" does not introduce conflicts during the merge, since it rebases history made after the last commit (B) to be squashed into the initial one (which was A) to tmp (representing the squashed new initial commit): trivial fast-forward merges only.
That works for "A-B
", but also "A-...-...-...-B
" (any number of commits can be squashed into the initial one this way)