Squashing Commits & Keeping Your History Clean

I'm a big fan of committing early and often. However, if you are anything like me, that means your commit history looks something like this:

added feature
fixed typo
oops another typo
added tests
fix failing test
fix another failing test
UGH TYPO

Fine for me alone, but not a great reference for the rest of the team when they try to figure out WTF I was doing a month or a year later. I've already written about how to rebase and squash commits before, so I won't cover that again. I do want to go a little more into why it's important to do so. Each commit message should reflect a distinct piece of work done. What I need to do now is rebase and change my commits to be more like this:

Added endpoint to return list of components
Added unit tests for component index endpoint

Now, if someone does a git blame, they can get the full context of what I was doing, not just a one character typo change. It's also worth expanding out your messaging and putting more context in the description. Every team has their own style and rules, but, personally, this is my normal git workflow and I'm a huge fan.

Git Rebase

For a while I was staying away from git rebase because I kept getting crazy errors and commits that weren’t mine whenever I tried to rebase. No more!

# rebase!
git checkout branch-i-want-to-merge
git log
git rebase -i HEAD~6
git log
git rebase old-branch
git checkout old-branch
git merge branch-i-want-to-merge

Command by command:

I have a branch called branch-i-want-to-merge that has 6 commits. I have a master branch called old-branch that I want to merge my branch into, but not before cleaning up the commit history (does everyone need to know that I forgot an s?).

I have branch-i-want-to-merge checked out. I double check my number of commits by doing a git log and counting them. I see 6, so I do a git rebase -i HEAD~6. After this, I do a git log again to verify that I only have 1 commit.

Now I want to make sure my new branch has all the commits from the old branch, so I do git rebase old-branch. Success!

Final steps: I check out old-branch, then do merge in my new branch with a git merge branch-i-want-to-merge. All done! That wasn’t so hard, right?