3 Squashing
Harry Kar edited this page 2018-10-25 23:01:06 +00:00

Let's say you did a PR to add a single book in a single commit, but due to formatting errors you added 5 more commits until the PR passes Travis. Obviously, merging your PR would add 6 commits for a single line of content, which is not acceptable.

"Merging" these commits into one single commit is known as "squashing commits".

Here's the simplest way to do it:

If you want to write the new commit message from scratch (assume we would like to rebase 6 commits starting at the latest one, which is the current HEAD):

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

If you want to start editing the new commit message with a concatenation of the existing commit messages then you need to extract those messages and pass them to git commit:

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

Both of those methods squash the last six commits into a single new commit in the same way. The soft reset just re-points HEAD to the last commit that you do not want to squash. Neither the index nor the working tree are touched by the soft reset, leaving the index in the desired state for your new commit (i.e. it already has all the changes from the commits that you are about to “throw away”).

Here's another one longer way to do it:

  1. In your git repo, do git rebase -i HEAD~6 (because we would like to rebase 6 commits starting at the latest one, which is the current HEAD)
  2. It will open an editor. Each line starting with pick describes a commit. On the first line, you will see the first commit of this PR, this is the commit we would like to keep, so we will not modify this line. For all the following lines, replace pick with fixup.
  3. Close the editor. Git will start rewriting history.
  4. git push --force