It happens to me very often that someone helps me out on a branch and pushes their code on a fixup commit. Every time it happens, I panic! I used to be very bad at git, my git tree would look like crap due to multiple unexpected merges. I was starting to get ashamed. Not only that, but I definitely didn’t know how to squash commits. However, I decided to learn and focus on git this last year to avoid these silly mistakes and get better at it. Here is how I managed to squash my commits using the command line. Note that you might use a graphical git manager, this could make this process easier.
Start an interactive rebase
Squashing commits means that you have to start an interactive rebase. Choose the starting commit. In my case, it’s 2 because I just want to squash a fixup commit in my previous commit.
git rebase -i HEAD~2
At this point your editor of choice will pop up, This is the file that will open :
pick 571afa fixup commit
pick 652fec feature: commit message specific to the feature
Replace the pick by squash, or s for brevity, in front of the commit you want to squash. Then save the file and close it.
squash 571afa fixup commit
pick 652fec feature: commit message specific to the feature
A new window will open with the 2 messages of the commits you want to squash together. Change the name of the commit if you want one clean commit message and save. Then run :
git push -f
You can check the outcome on your git repository. Only one commit gathering the modifications you did on your two old commits should be in the git history. This is how to squash commits, Easy, right?!