Squashing
Squashing is the process of taking a series of commits and merge them into a single commit. This technique is especially useful when a feature branch has numerous small, incremental commits that clutter the commit history. By squashing these commits, you can present a more polished and cohesive history to your collaborators.

Use Cases:
  • Cleaning Up a Feature Branch
  • Improving Readability of Commit History
  • Reducing Noise in Merge Requests
  • Rewriting Commit Messages for Clarity

Squashing Example

Squashing Image from DevOps Council
Examples:

Squashing Locally:

Start an interactive rebase:
git rebase -i HEAD~4
# The 4 means you are starting an interactive rebase for the last 4 commits in your current branch.

# If you want to squash from a certain commit, you can use the commit hash instead of squash, for example:
git rebase -1 2e3f98521b41dab0bb362901b177af445b0de687~3

This opens an interactive editor showing the last 4 commits:
pick abcd123 Fix typo
pick efgh456 Add validation
pick ijkl789 New color
pick mnop012 Add error messages

Modify the Commands to Squash

Change all pick (except the first commit) to squash:

pick abcd123 Fix typo
squash efgh456 Add validation
squash ijkl789 New color
squash mnop012 Add error messages

# You dont always have to squash to the top commit, for example:
pick abcd123 Fix typo
pick efgh456 Add validation
squash ijkl789 New color
squash mnop012 Add error messages
# This will squash only the bottom 2 commits in to the "Add validation" commit.

Git will now ask you to modify the commit message. You'll see something like:

# This is a combination of 4 commits.
Fix typo

Add validation
New color
Add error messages

You can edit this commit message to something cleaner, for example:

Improve web app: fix typo, add validation, new color, and add error messages.

Squashing a pull request:

When merging a pull request, squashing and merging is 1 of 3 options you can choose from
Squash and Merge Image from Substack
This will combine all your commits in to one commit, and give you the option to change your commit message

Squashing Image from Thoughtbot

You can then confirm squash and merge, and all your commits will be squashed in to 1 commit