When developing new features or fixing issues in Git, you may create multiple commits. However, before merging into the main branch, to maintain a clean project history, you may need to squash these commits into one. This process is commonly known as Squashing commits. A commonly used tool in Git is git rebase. I will explain this process with a specific example:
Suppose you are working on a new feature and have made three commits on a branch named feature-branch. The details of these three commits are as follows:
- Add the framework for the new feature
- Implement the core part of the new feature
- Fix some bugs in the implementation
To squash these three commits into one before code review or merging into the main branch, follow these steps:
- Switch to your feature branch
bashgit checkout feature-branch
- Use
git rebasefor interactive history rewriting
bashgit rebase -i HEAD~3
This command opens a text editor listing the last three commits.
- In the text editor, you will see something like the following:
shellpick e3a1b35 Add the framework for the new feature squash 7ac9a67 Implement the core part of the new feature squash 4ed2a9d Fix some bugs in the implementation
To squash these commits into one, change all pick commands except the first to squash or s. This tells Git to merge these commits into the first one.
- Save and close the editor
Git will start squashing the commits and may open a new editor window for writing a new commit message. Here, you can write a concise message describing the entire feature.
- Complete the history rewriting
After this step, feature-branch will contain only one new commit with all changes from the previous three commits.
- Push the changes to the remote repository
If you have already pushed these commits to the remote repository, since the history has been rewritten, you need to force push:
bashgit push origin feature-branch --force
By doing this, you can effectively squash multiple commits into one, maintaining a clear and concise project history. This is very helpful for code reviews and long-term maintenance.