How to Batch Update Git Commit Messages
At Mozilla we're mostly strict about receiving contributions via git/GitHub. Aside from requiring tests and enforcing code quality, one basic of submitting a commit (or several) is that the commit message begins with "bug #######", which is a reference to its Bugzilla bug. The message requirement makes sense but I hate going back to contributors and asking them to do "the paperwork" of changing their commit message to match our standard, so I generally try to make the update for them.
Recently MDN received a contribution which upgraded CKEditor and did so via approximately 60 commits, none of which referenced the bug number for the feature update. I badly wanted to do the commit message updates for this contributor, but I wanted to do so in an automated way -- a batch update to save me the time updating each message one by one. Welcome to
Prepending to Commit Messages
To prepend text to every commit message in a given range, you'd execute a message like:
git filter-branch --msg-filter 'echo "bug ###### - \c" && cat' master..HEAD
The combination of
--msg-filter will allow you to recurse through every commit message. The echo piece allows you to build the new string. The last piece is the range whose commit messages should be targeted -- in this case, I'm prepending the text to every commit in the feature branch.
You can also
sed to achieve this:
git filter-branch -f --msg-filter 'sed "s/^/bug ###### - /"' master..HEAD
Appending to Commit Messages
The case for appending to commit messages could be where you want to add the reviewer name(s) to the message. Appending is roughly the same:
git filter-branch -f --msg-filter 'cat && echo "[Reviewer Walsh]"' master..HEAD
The difference here is the position of the
cat command. Everything else can be the same.
I have a love/hate relationship with git -- I love git because it's so easy for 90% of my needs but hate it when I need the other 10%. Hopefully these examples help you if you run into this need in the future!