Squashing Commits in a Git Feature Branch: A Cleaner Git History

Git provides powerful tools to manage your project’s version history, and one useful technique is squashing commits. Squashing allows you to combine multiple small, related commits into a single, more meaningful commit. This helps maintain a clean and understandable Git history. In this guide, we’ll walk through the process of squashing commits in a feature branch.

Prerequisites: Ensure Your Branch is Up to Date

Before squashing commits, it’s essential to ensure your feature branch is up to date with the latest changes from the remote repository. Use the following commands:

git fetch origin
git checkout feature_branch
git pull origin feature_branch

Step 1: Initiate an Interactive Rebase

Navigate to your feature branch and initiate an interactive rebase. Replace n with the number of commits you want to squash:

git checkout feature_branch
git rebase -i HEAD~n

Alternatively, if you want to squash all commits since the branch diverged from the main branch:

git rebase -i origin/main

Step 2: Squash Commits

Your default text editor will open with a list of commits and their actions. Change pick to squash (or s) for the commits you want to squash:

pick abc123 Commit message 1
squash def456 Commit message 2
squash ghi789 Commit message 3

Save and close the file.

Step 3: Edit the Commit Message

Another editor window will open for you to edit the commit message. You can keep the existing messages, combine them, or write a completely new one. Save and close the file.

Step 4: Complete the Rebase

After squashing the commits, complete the rebase:

git rebase --continue

If there are conflicts, resolve them before continuing.

Step 5: Force Push

Since you’ve rewritten the commit history, force push the changes to the remote repository:

git push origin feature_branch --force

Be cautious with force pushes, especially in collaborative environments. Communicate with collaborators to avoid disrupting their work.