How to Squash All Commits on a Branch in Git
This article will give instruction to squash all commits that have been done into a single commit.
Suppose we have made a bunch of commits on a feature branch, now we need to clean it up by grouping all those commits on this branch into just one commit. Git calls it squashing.
The idea for squashing all commits is as follows.
- Reset all changes with a soft reset.
- Add back the changes.
- Commit with a new message.
Git Soft-Reset Changes
A soft reset will undo all commits while not removing newly added files.
To do so, we must find the origin commit where the feature branch is based, which usually is the name of the origin branch, such as main
.
$ git log
commit a856ee456967a942ab379b27a4839962f88b92ce (HEAD -> feature/long-features)
Author: Cuong Nguyen
Date: Mon Dec 27 20:53:18 2021 +0700
Feature 2.3
commit 6f1599a18691906ed148dc40d2d290aaeceeaa5c
Author: Cuong Nguyen
Date: Mon Dec 27 20:53:03 2021 +0700
Subfeature 2
commit 94e35bae85f395c62fdaaa1aeaedbb11d2c94375
Author: Cuong Nguyen
Date: Mon Dec 27 20:52:39 2021 +0700
Subfeature 1
commit 9265e3bd97863fde0a13084f04163ceceff9a9d0 (grafted, tag: v1.0.0, branch-off-from-tag-v1.0.0)
Author: Cuong Nguyen
Date: Sun Dec 19 19:33:07 2021 +0700
Merge pull request #1 from stwarts/feature/shared-branch
In this example, we find out the branch feature/long-features
is checked out from the commit SHA 9265e3bd97863fde0a13084f04163ceceff9a9d0
(or from the branch name branch-off-from-tag-v1.0.0
.
To reset all modifications, use either git reset --soft 9265e3bd97863fde0a13084f04163ceceff9a9d0
or git reset --soft branch-off-from-tag-v1.0.0
.
$ git reset --soft 9265e3bd97863fde0a13084f04163ceceff9a9d0
$ git status
On branch feature/long-features
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: sub_feature_1.txt
new file: sub_feature_2.txt
The --soft
option specifies git to reset commits and keep new files.
Add Back the Changes
git add -A
is the command to use.
The -A
option specifies that all changes will be added.
Commit
The final step is to use git commit -m <message>
to generate a new commit.
$ git commit -m 'Squash 3 commits into 1'
[feature/long-features 8cc336c] Squash 3 commits into 1
2 files changed, 2 insertions(+)
create mode 100644 sub_feature_1.txt
create mode 100644 sub_feature_2.txt
$ git log
commit 8cc336c6d1b2e6ed55470f99b040d6835ec655e5 (HEAD -> feature/long-features)
Author: Cuong Nguyen <cuong.nguyen@oivan.com>
Date: Mon Dec 27 21:07:54 2021 +0700
Squash 3 commits into 1
commit 9265e3bd97863fde0a13084f04163ceceff9a9d0 (grafted, tag: v1.0.0, branch-off-from-tag-v1.0.0)
Author: Nguyễn Phú Cường <npcuong.011308@gmail.com>
Date: Sun Dec 19 19:33:07 2021 +0700
Merge pull request #1 from stwarts/feature/shared-branch