What is squash before merge in coding practice


“Squash before merge” is a practice in version control systems, specifically in Git, where multiple smaller commits in a feature branch are combined into a single commit before merging that branch into a main branch like main or master. This is done to keep the commit history clean and concise, making it easier to understand the changes introduced by the feature branch.

Here’s how it typically works:

  1. Developing the Feature: You create a feature branch from the main branch and make multiple commits as you develop the feature.
  2. Reviewing: Once the feature is complete, you open a pull request or merge request, which might go through a code review process. During this time, you might make additional commits based on feedback.
  3. Squashing Commits: Before merging the feature branch back into the main branch, you “squash” all of the commits in the feature branch into a single commit. This combined commit contains all the changes made in the feature branch.
  4. Merging: The single, squashed commit is then merged into the main branch.

Benefits of Squashing Before Merge

  • Simpler History: A single commit makes the commit history cleaner and easier to follow.
  • Atomic Changes: Each feature or fix is encapsulated in a single commit, making it easier to revert if necessary.
  • Easier Code Reviews: Reviewers can focus on the overall changes rather than sifting through many smaller, possibly inconsequential commits.

How to Squash Commits

You can squash commits before merging using Git’s interactive rebase feature:

  1. Rebase Interactive:

    git rebase -i HEAD~n

    Replace n with the number of commits you want to squash.

  2. Mark Commits to Squash: In the interactive rebase screen, mark the commits you want to squash by replacing pick with squash or s.

  3. Reword Commit Message: After marking the commits to squash, you’ll be prompted to edit the commit message for the squashed commit. You can combine the messages or write a new one summarizing the changes.

  4. Push the Rebase:

    git push --force

    Since rebase rewrites the commit history, you’ll need to force-push the changes to your remote branch.

Some version control systems and tools like GitHub also offer an option to “Squash and merge” directly from the pull request interface, making it even more straightforward without needing to use the command line.

Using the “squash before merge” practice helps streamline your project’s commit history and enhances the clarity and maintainability of your codebase.


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC