Squashing Commits: A Comprehensive Guide 🎯

beginner
22 min

Squashing Commits: A Comprehensive Guide 🎯

Welcome to our guide on squashing commits! In this lesson, we'll learn what squashing commits means, why it's useful, and how to do it using Git. 📝

Understanding Commits 📝

In Git, a commit is a snapshot of your project's current state. Each commit contains changes, a commit message, and a unique identifier. 💡 Commits help you track your project's history and changes.

Why Squash Commits? 💡

Squashing commits combines multiple commits into one, making the commit history cleaner and easier to understand. This is particularly useful when you have many small commits for a single feature or bug fix.

Squashing Commits: The Step-by-Step Process 💡

Let's squash commits using the interactive rebase feature of Git.

  1. Navigate to the branch where you have the commits you want to squash:
bash
git checkout <your-branch>
  1. Start an interactive rebase, which will allow you to rearrange and squash commits:
bash
git rebase -i HEAD~<number-of-commits>

Replace <number-of-commits> with the number of commits you want to squash.

  1. You'll see a list of commits with each on a separate line. The command will look like this:
bash
pick <commit-hash> <commit-message>
  1. To squash commits, change the word pick to squash on the lines of the commits you want to combine. The result will look like this:
bash
squash <commit-hash-1> <commit-message-1> squash <commit-hash-2> <commit-message-2>
  1. Save and close the editor. Git will prompt you to enter a new commit message for the combined commits.

  2. Finally, force push the branch to update the commit history:

bash
git push --force-with-lease

And that's it! You've squashed commits using Git. ✅

Practical Example 💡

Let's squash the last three commits in our feature/my-feature branch:

bash
git checkout feature/my-feature git rebase -i HEAD~3

Change pick to squash on the lines of the commits you want to combine, save and close the editor, enter a new commit message, and force push the branch.

Quiz 📝

Quick Quiz
Question 1 of 1

What does squashing commits do?

Happy coding! 😊