Navigating Git History: A Tale of Commit Message Redemption
I needed to rewrite multiple commit messages that contained typos — not just one, but several. Here's how I did it and what I learned.
The Situation
Picture this: You've been coding away, committing changes left and right, when suddenly you realize something's amiss. Your commit messages are missing crucial information. It's not just one commit, but several that need attention. What do you do?
A quick git log --oneline revealed our oversight:
d45e21f Update user authentication
7a9b3c2 Refactor database queries
f1e8d6a Implement new feature
2c5b9e0 Fix bug in login flow
Our goal was to prefix each commit with the story number (e.g., "[Story #42]"). While I knew how to amend a single commit, rewriting multiple commit messages was new territory.
The Solution: Interactive Rebase
We turned to Git's interactive rebase feature. Here's the process we followed:
-
Initiate the rebase:
git rebase -i HEAD~4 -
In the opened editor, we changed 'pick' to 'reword' for each commit we wanted to modify:
reword 2c5b9e0 Fix bug in login flow reword f1e8d6a Implement new feature reword 7a9b3c2 Refactor database queries reword d45e21f Update user authentication -
Git then prompted us to edit each commit message in turn. We added the story number to each:
[Story #42] Fix bug in login flow -
After editing all messages, our revised history looked like this:
8f2g3h1 [Story #42] Update user authentication 6k7m9n4 [Story #42] Refactor database queries 3p5q7r2 [Story #42] Implement new feature 1s3t5u8 [Story #42] Fix bug in login flow
Lessons Learned
1. Plan Ahead: Establishing and following commit message conventions from the start can save time and headaches.
2. Power of Interactive Rebase: This tool is invaluable for maintaining a clean, informative commit history.
3. Caution with Shared Branches: Rewriting history on shared branches can cause conflicts. It's best to fix commit messages before pushing or on personal branches.
4. Git Aliases: Creating aliases for common Git commands can streamline your workflow. For example:
git config --global alias.rb 'rebase -i'
Now you can use git rb HEAD~4 for interactive rebase.
5. Commit Often, Perfect Later: Don't let perfect be the enemy of good. Commit frequently and use these techniques to clean up history before sharing.
Commit history is documentation. Keep it clean.

