Skip to content

Squashing Commits

Renato Ramos Nascimento edited this page Aug 6, 2021 · 1 revision

In Git you can merge several commits into one with the powerful interactive rebase.

Choose your starting commit

The first thing to do is to invoke git to start an interactive rebase session:

git rebase --interactive HEAD~N

Where N is the number of the commits you want to join. If there are tons of commits you can start the session informing the commit hash like this:

git rebase --interactive [commit-hash]

Picking and Squashing

At this point your editor of choice will pop up, showing the list of commits you want to merge. The trick here is that they are showing in reverse order.

pick d94e78 Prepare the workbench for feature Z     --- older commit
pick 4e9baa Cool implementation 
pick afb581 Fix this and that  
pick 643d0e Code cleanup
pick 87871a I'm ready! 
pick 0c3317 Whoops, not yet... 
pick 871adf OK, feature Z is fully implemented      --- newer commit

Change the word pick to squash (or s for short)

pick d94e78 Prepare the workbench for feature Z     --- older commit
s 4e9baa Cool implementation 
s afb581 Fix this and that  
s 643d0e Code cleanup
s 87871a I'm ready! 
s 0c3317 Whoops, not yet... 
s 871adf OK, feature Z is fully implemented      --- newer commit

Save the file

Give a description of the new commit

Now in your file editor is asking you for the new commit description.

Save the file.

Now you have all the commits selected squashed into a just one commit.

Source

https://www.internalpointers.com/post/squash-commits-into-one-git