Introduction

In Git, squashing commits is a powerful technique that combines multiple commits into a single, more concise commit. This can simplify your project's history and make it easier to review changes. One common method to achieve this is using the git merge --squash command.

Understanding git merge --squash

When you use git merge --squash, Git merges the changes from the source branch into the target branch, but instead of creating a new commit for each merged change, it creates a temporary commit that contains all the changes combined. This temporary commit is not automatically recorded in the history.

Steps to Squash Commits

  1. Switch to the target branch:

    git checkout <target-branch>
  2. Merge the source branch:

    git merge --squash <source-branch>
  3. Review the merged changes:

    git diff
  4. Create the final commit:

    git commit -m "Squashed commits from "

Example

Let's say you have a feature branch named feature-branch and you want to merge its changes into the main branch. Here's how you would use git merge --squash:

git checkout main
git merge --squash feature-branch
git commit -m "Merged feature changes"

Benefits of Squashing Commits

  • Cleaner history: Reduces the number of commits, making it easier to review changes.
  • Improved readability: A concise commit history can be easier to understand and navigate.
  • Simplified code review: Fewer commits to review can streamline the code review process.

When to Squash Commits

  • Small, related changes: If you've made a series of small, related changes, squashing them into a single commit can provide a better overview.
  • Experimental or temporary changes: If you've made changes that were experimental or temporary, squashing them can clean up the history.
  • Before creating a pull request: Squashing commits before submitting a pull request can help keep the review process focused.

Caution:

While squashing commits can be beneficial, it's important to use it judiciously. If you need to track individual commits for debugging or auditing purposes, consider merging normally instead of squashing.

Conclusion

git merge --squash is a valuable tool for maintaining a clean and organized Git history. By understanding how to use it effectively, you can streamline your development workflow and improve the readability of your project's changes.