Workflows

Git Squash Commits

Squashing Commits

Git squash combines multiple commits into one with rebase.

Understanding Git Squash

Git squash is a technique that allows developers to combine multiple commits into a single commit. This is particularly useful for cleaning up a project's commit history before merging a feature branch into the main branch. Squashing commits helps maintain a cleaner and more understandable Git history.

Why Squash Commits?

Squashing commits offers several benefits:

  • Clarity: A single commit represents a complete feature or fix, making the history easier to follow.
  • Reduced Noise: Removes unnecessary or trivial commits (e.g., typos, minor fixes).
  • Atomic Changes: Ensures that each commit is a standalone change, making it easier to revert if needed.

How to Squash Commits Using Interactive Rebase

The most common way to squash commits is to use Git's interactive rebase feature. Follow these steps to squash commits:

Replace n with the number of commits you want to squash. This command will open an editor displaying the last n commits.

In the editor, you'll see a list of commits. To squash commits, change the word pick to squash (or simply s) for the commits you want to combine. The first commit should remain as pick.

After editing, save and close the editor. Git will then prompt you to merge the commit messages. You can customize the commit message as needed. Once done, save and close the editor again.

Finalizing the Squash Operation

After completing the interactive rebase, you may need to force-push the changes to the remote branch to update the history:

Be cautious with force-pushing, especially on shared branches, as it can overwrite others' work.

Best Practices for Squashing Commits

  • Squash commits before sharing your branch with others to avoid complications.
  • Use meaningful commit messages when merging the commit messages.
  • Avoid squashing commits on public branches where others might already have pulled the changes.