My Work Notes

28 Dec 2022

Ways to squash git commits

Soft reset

git reset --soft HEAD~3 && git commit

This command undoes the last three commits in a Git repository, preserves their changes in the working directory and staging area, and then creates a new commit with those changes. If you don’t want to write a new commit message from scratch, you can use:

git reset --soft HEAD~3 &&
git commit --edit -m"$(git log --format=%B --reverse HEAD..HEAD@{1})"

It will open your default editor with the last commit message ready to edit.

Interactive rebase

git rebase -i HEAD~3

This command opens your default editor with the last three commits ready to edit. You can squash them into one commit or edit the commit messages. To squash them into one commit, you need to change the word pick to squash for the commits you want to squash.

Merge

If you want to squash commits without force push, you can use merge. In case, you want to squash not all commits, move needed commits to a new branch. Let’s say you called it feature-brach.

Checkout to the branch you want to squash commits in, i.e. master:

git checkout master

Then merge feature-branch into master and commit the merge:

git merge --squash feature-brach && git commit

This command merges the feature branch into the current branch and squashes all the commits into one commit.

Bonus variant with merge

git reset --hard HEAD~3
git merge --squash HEAD@{1}
git commit

This command undoes the last three commits in a Git repository, preserves their changes in the working directory and staging area, and then creates a new commit with those changes. But there is no over git reset --soft with keeping all commit messages ready to edit (as the second command in the first section does).

This post is a synopsis of answers to this question on Stackoverflow.