How to Squash the 1st and 3rd Commit
2. Interactive Rebase
The secret weapon in our quest to squash commits is the interactive rebase. Think of it as a time machine that lets you rewrite history — or at least, rewrite your local branch's history. It allows you to manipulate, reorder, and, most importantly, squash commits. Don't worry, it sounds scarier than it is. We'll walk through it together.
First, you'll need to identify the common ancestor of your branch and the branch you want to rebase onto (typically `main` or `develop`). This is important because you'll start the rebase from just before the first commit you want to manipulate. If the commits you're squashing are among the first commits of your branch, you'll usually rebase from the `main` branch (or whichever branch you branched off of).
The command you'll use is `git rebase -i HEAD~n`, where `n` is the number of commits you want to go back in history. So, if your first commit is the first on the branch, and you only have 3 commits total, you would rebase starting with HEAD~3, because you want to include all 3 commits in the interactive rebase. Git will then open an editor with a list of your commits, in reverse chronological order, with each commit prefixed by the word `pick`.
This is where the magic happens. In the editor, you'll change the `pick` command for the 3rd commit to `squash` (or just `s`). This tells Git to merge that commit into the commit immediately above it. Crucially, leave the `pick` command for the 1st commit as is. You'll also want to change the 2nd commit as pick too. Now, save the file and close the editor. Git will then prompt you to edit the commit message for the resulting squashed commit.